gitweb / gitweb.perlon commit Merge branch 'maint' (c1c10a3)
   1#!/usr/bin/perl
   2
   3# gitweb - simple web interface to track changes in git repositories
   4#
   5# (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
   6# (C) 2005, Christian Gierke
   7#
   8# This program is licensed under the GPLv2
   9
  10use strict;
  11use warnings;
  12use CGI qw(:standard :escapeHTML -nosticky);
  13use CGI::Util qw(unescape);
  14use CGI::Carp qw(fatalsToBrowser);
  15use Encode;
  16use Fcntl ':mode';
  17use File::Find qw();
  18use File::Basename qw(basename);
  19binmode STDOUT, ':utf8';
  20
  21BEGIN {
  22        CGI->compile() if $ENV{'MOD_PERL'};
  23}
  24
  25our $cgi = new CGI;
  26our $version = "++GIT_VERSION++";
  27our $my_url = $cgi->url();
  28our $my_uri = $cgi->url(-absolute => 1);
  29
  30# core git executable to use
  31# this can just be "git" if your webserver has a sensible PATH
  32our $GIT = "++GIT_BINDIR++/git";
  33
  34# absolute fs-path which will be prepended to the project path
  35#our $projectroot = "/pub/scm";
  36our $projectroot = "++GITWEB_PROJECTROOT++";
  37
  38# target of the home link on top of all pages
  39our $home_link = $my_uri || "/";
  40
  41# string of the home link on top of all pages
  42our $home_link_str = "++GITWEB_HOME_LINK_STR++";
  43
  44# name of your site or organization to appear in page titles
  45# replace this with something more descriptive for clearer bookmarks
  46our $site_name = "++GITWEB_SITENAME++"
  47                 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
  48
  49# filename of html text to include at top of each page
  50our $site_header = "++GITWEB_SITE_HEADER++";
  51# html text to include at home page
  52our $home_text = "++GITWEB_HOMETEXT++";
  53# filename of html text to include at bottom of each page
  54our $site_footer = "++GITWEB_SITE_FOOTER++";
  55
  56# URI of stylesheets
  57our @stylesheets = ("++GITWEB_CSS++");
  58# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
  59our $stylesheet = undef;
  60# URI of GIT logo (72x27 size)
  61our $logo = "++GITWEB_LOGO++";
  62# URI of GIT favicon, assumed to be image/png type
  63our $favicon = "++GITWEB_FAVICON++";
  64
  65# URI and label (title) of GIT logo link
  66#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
  67#our $logo_label = "git documentation";
  68our $logo_url = "http://git.or.cz/";
  69our $logo_label = "git homepage";
  70
  71# source of projects list
  72our $projects_list = "++GITWEB_LIST++";
  73
  74# the width (in characters) of the projects list "Description" column
  75our $projects_list_description_width = 25;
  76
  77# default order of projects list
  78# valid values are none, project, descr, owner, and age
  79our $default_projects_order = "project";
  80
  81# show repository only if this file exists
  82# (only effective if this variable evaluates to true)
  83our $export_ok = "++GITWEB_EXPORT_OK++";
  84
  85# only allow viewing of repositories also shown on the overview page
  86our $strict_export = "++GITWEB_STRICT_EXPORT++";
  87
  88# list of git base URLs used for URL to where fetch project from,
  89# i.e. full URL is "$git_base_url/$project"
  90our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
  91
  92# default blob_plain mimetype and default charset for text/plain blob
  93our $default_blob_plain_mimetype = 'text/plain';
  94our $default_text_plain_charset  = undef;
  95
  96# file to use for guessing MIME types before trying /etc/mime.types
  97# (relative to the current git repository)
  98our $mimetypes_file = undef;
  99
 100# assume this charset if line contains non-UTF-8 characters;
 101# it should be valid encoding (see Encoding::Supported(3pm) for list),
 102# for which encoding all byte sequences are valid, for example
 103# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
 104# could be even 'utf-8' for the old behavior)
 105our $fallback_encoding = 'latin1';
 106
 107# You define site-wide feature defaults here; override them with
 108# $GITWEB_CONFIG as necessary.
 109our %feature = (
 110        # feature => {
 111        #       'sub' => feature-sub (subroutine),
 112        #       'override' => allow-override (boolean),
 113        #       'default' => [ default options...] (array reference)}
 114        #
 115        # if feature is overridable (it means that allow-override has true value),
 116        # then feature-sub will be called with default options as parameters;
 117        # return value of feature-sub indicates if to enable specified feature
 118        #
 119        # if there is no 'sub' key (no feature-sub), then feature cannot be
 120        # overriden
 121        #
 122        # use gitweb_check_feature(<feature>) to check if <feature> is enabled
 123
 124        # Enable the 'blame' blob view, showing the last commit that modified
 125        # each line in the file. This can be very CPU-intensive.
 126
 127        # To enable system wide have in $GITWEB_CONFIG
 128        # $feature{'blame'}{'default'} = [1];
 129        # To have project specific config enable override in $GITWEB_CONFIG
 130        # $feature{'blame'}{'override'} = 1;
 131        # and in project config gitweb.blame = 0|1;
 132        'blame' => {
 133                'sub' => \&feature_blame,
 134                'override' => 0,
 135                'default' => [0]},
 136
 137        # Enable the 'snapshot' link, providing a compressed tarball of any
 138        # tree. This can potentially generate high traffic if you have large
 139        # project.
 140
 141        # To disable system wide have in $GITWEB_CONFIG
 142        # $feature{'snapshot'}{'default'} = [undef];
 143        # To have project specific config enable override in $GITWEB_CONFIG
 144        # $feature{'snapshot'}{'override'} = 1;
 145        # and in project config gitweb.snapshot = none|gzip|bzip2|zip;
 146        'snapshot' => {
 147                'sub' => \&feature_snapshot,
 148                'override' => 0,
 149                #         => [content-encoding, suffix, program]
 150                'default' => ['x-gzip', 'gz', 'gzip']},
 151
 152        # Enable text search, which will list the commits which match author,
 153        # committer or commit text to a given string.  Enabled by default.
 154        # Project specific override is not supported.
 155        'search' => {
 156                'override' => 0,
 157                'default' => [1]},
 158
 159        # Enable grep search, which will list the files in currently selected
 160        # tree containing the given string. Enabled by default. This can be
 161        # potentially CPU-intensive, of course.
 162
 163        # To enable system wide have in $GITWEB_CONFIG
 164        # $feature{'grep'}{'default'} = [1];
 165        # To have project specific config enable override in $GITWEB_CONFIG
 166        # $feature{'grep'}{'override'} = 1;
 167        # and in project config gitweb.grep = 0|1;
 168        'grep' => {
 169                'override' => 0,
 170                'default' => [1]},
 171
 172        # Enable the pickaxe search, which will list the commits that modified
 173        # a given string in a file. This can be practical and quite faster
 174        # alternative to 'blame', but still potentially CPU-intensive.
 175
 176        # To enable system wide have in $GITWEB_CONFIG
 177        # $feature{'pickaxe'}{'default'} = [1];
 178        # To have project specific config enable override in $GITWEB_CONFIG
 179        # $feature{'pickaxe'}{'override'} = 1;
 180        # and in project config gitweb.pickaxe = 0|1;
 181        'pickaxe' => {
 182                'sub' => \&feature_pickaxe,
 183                'override' => 0,
 184                'default' => [1]},
 185
 186        # Make gitweb use an alternative format of the URLs which can be
 187        # more readable and natural-looking: project name is embedded
 188        # directly in the path and the query string contains other
 189        # auxiliary information. All gitweb installations recognize
 190        # URL in either format; this configures in which formats gitweb
 191        # generates links.
 192
 193        # To enable system wide have in $GITWEB_CONFIG
 194        # $feature{'pathinfo'}{'default'} = [1];
 195        # Project specific override is not supported.
 196
 197        # Note that you will need to change the default location of CSS,
 198        # favicon, logo and possibly other files to an absolute URL. Also,
 199        # if gitweb.cgi serves as your indexfile, you will need to force
 200        # $my_uri to contain the script name in your $GITWEB_CONFIG.
 201        'pathinfo' => {
 202                'override' => 0,
 203                'default' => [0]},
 204
 205        # Make gitweb consider projects in project root subdirectories
 206        # to be forks of existing projects. Given project $projname.git,
 207        # projects matching $projname/*.git will not be shown in the main
 208        # projects list, instead a '+' mark will be added to $projname
 209        # there and a 'forks' view will be enabled for the project, listing
 210        # all the forks. If project list is taken from a file, forks have
 211        # to be listed after the main project.
 212
 213        # To enable system wide have in $GITWEB_CONFIG
 214        # $feature{'forks'}{'default'} = [1];
 215        # Project specific override is not supported.
 216        'forks' => {
 217                'override' => 0,
 218                'default' => [0]},
 219);
 220
 221sub gitweb_check_feature {
 222        my ($name) = @_;
 223        return unless exists $feature{$name};
 224        my ($sub, $override, @defaults) = (
 225                $feature{$name}{'sub'},
 226                $feature{$name}{'override'},
 227                @{$feature{$name}{'default'}});
 228        if (!$override) { return @defaults; }
 229        if (!defined $sub) {
 230                warn "feature $name is not overrideable";
 231                return @defaults;
 232        }
 233        return $sub->(@defaults);
 234}
 235
 236sub feature_blame {
 237        my ($val) = git_get_project_config('blame', '--bool');
 238
 239        if ($val eq 'true') {
 240                return 1;
 241        } elsif ($val eq 'false') {
 242                return 0;
 243        }
 244
 245        return $_[0];
 246}
 247
 248sub feature_snapshot {
 249        my ($ctype, $suffix, $command) = @_;
 250
 251        my ($val) = git_get_project_config('snapshot');
 252
 253        if ($val eq 'gzip') {
 254                return ('x-gzip', 'gz', 'gzip');
 255        } elsif ($val eq 'bzip2') {
 256                return ('x-bzip2', 'bz2', 'bzip2');
 257        } elsif ($val eq 'zip') {
 258                return ('x-zip', 'zip', '');
 259        } elsif ($val eq 'none') {
 260                return ();
 261        }
 262
 263        return ($ctype, $suffix, $command);
 264}
 265
 266sub gitweb_have_snapshot {
 267        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
 268        my $have_snapshot = (defined $ctype && defined $suffix);
 269
 270        return $have_snapshot;
 271}
 272
 273sub feature_grep {
 274        my ($val) = git_get_project_config('grep', '--bool');
 275
 276        if ($val eq 'true') {
 277                return (1);
 278        } elsif ($val eq 'false') {
 279                return (0);
 280        }
 281
 282        return ($_[0]);
 283}
 284
 285sub feature_pickaxe {
 286        my ($val) = git_get_project_config('pickaxe', '--bool');
 287
 288        if ($val eq 'true') {
 289                return (1);
 290        } elsif ($val eq 'false') {
 291                return (0);
 292        }
 293
 294        return ($_[0]);
 295}
 296
 297# checking HEAD file with -e is fragile if the repository was
 298# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
 299# and then pruned.
 300sub check_head_link {
 301        my ($dir) = @_;
 302        my $headfile = "$dir/HEAD";
 303        return ((-e $headfile) ||
 304                (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
 305}
 306
 307sub check_export_ok {
 308        my ($dir) = @_;
 309        return (check_head_link($dir) &&
 310                (!$export_ok || -e "$dir/$export_ok"));
 311}
 312
 313# rename detection options for git-diff and git-diff-tree
 314# - default is '-M', with the cost proportional to
 315#   (number of removed files) * (number of new files).
 316# - more costly is '-C' (or '-C', '-M'), with the cost proportional to
 317#   (number of changed files + number of removed files) * (number of new files)
 318# - even more costly is '-C', '--find-copies-harder' with cost
 319#   (number of files in the original tree) * (number of new files)
 320# - one might want to include '-B' option, e.g. '-B', '-M'
 321our @diff_opts = ('-M'); # taken from git_commit
 322
 323our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
 324do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
 325
 326# version of the core git binary
 327our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
 328
 329$projects_list ||= $projectroot;
 330
 331# ======================================================================
 332# input validation and dispatch
 333our $action = $cgi->param('a');
 334if (defined $action) {
 335        if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
 336                die_error(undef, "Invalid action parameter");
 337        }
 338}
 339
 340# parameters which are pathnames
 341our $project = $cgi->param('p');
 342if (defined $project) {
 343        if (!validate_pathname($project) ||
 344            !(-d "$projectroot/$project") ||
 345            !check_head_link("$projectroot/$project") ||
 346            ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
 347            ($strict_export && !project_in_list($project))) {
 348                undef $project;
 349                die_error(undef, "No such project");
 350        }
 351}
 352
 353our $file_name = $cgi->param('f');
 354if (defined $file_name) {
 355        if (!validate_pathname($file_name)) {
 356                die_error(undef, "Invalid file parameter");
 357        }
 358}
 359
 360our $file_parent = $cgi->param('fp');
 361if (defined $file_parent) {
 362        if (!validate_pathname($file_parent)) {
 363                die_error(undef, "Invalid file parent parameter");
 364        }
 365}
 366
 367# parameters which are refnames
 368our $hash = $cgi->param('h');
 369if (defined $hash) {
 370        if (!validate_refname($hash)) {
 371                die_error(undef, "Invalid hash parameter");
 372        }
 373}
 374
 375our $hash_parent = $cgi->param('hp');
 376if (defined $hash_parent) {
 377        if (!validate_refname($hash_parent)) {
 378                die_error(undef, "Invalid hash parent parameter");
 379        }
 380}
 381
 382our $hash_base = $cgi->param('hb');
 383if (defined $hash_base) {
 384        if (!validate_refname($hash_base)) {
 385                die_error(undef, "Invalid hash base parameter");
 386        }
 387}
 388
 389my %allowed_options = (
 390        "--no-merges" => [ qw(rss atom log shortlog history) ],
 391);
 392
 393our @extra_options = $cgi->param('opt');
 394if (defined @extra_options) {
 395        foreach(@extra_options)
 396        {
 397                if (not grep(/^$_$/, keys %allowed_options)) {
 398                        die_error(undef, "Invalid option parameter");
 399                }
 400                if (not grep(/^$action$/, @{$allowed_options{$_}})) {
 401                        die_error(undef, "Invalid option parameter for this action");
 402                }
 403        }
 404}
 405
 406our $hash_parent_base = $cgi->param('hpb');
 407if (defined $hash_parent_base) {
 408        if (!validate_refname($hash_parent_base)) {
 409                die_error(undef, "Invalid hash parent base parameter");
 410        }
 411}
 412
 413# other parameters
 414our $page = $cgi->param('pg');
 415if (defined $page) {
 416        if ($page =~ m/[^0-9]/) {
 417                die_error(undef, "Invalid page parameter");
 418        }
 419}
 420
 421our $searchtype = $cgi->param('st');
 422if (defined $searchtype) {
 423        if ($searchtype =~ m/[^a-z]/) {
 424                die_error(undef, "Invalid searchtype parameter");
 425        }
 426}
 427
 428our $searchtext = $cgi->param('s');
 429our $search_regexp;
 430if (defined $searchtext) {
 431        if ($searchtype ne 'grep' and $searchtype ne 'pickaxe' and $searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
 432                die_error(undef, "Invalid search parameter");
 433        }
 434        if (length($searchtext) < 2) {
 435                die_error(undef, "At least two characters are required for search parameter");
 436        }
 437        $search_regexp = quotemeta $searchtext;
 438}
 439
 440# now read PATH_INFO and use it as alternative to parameters
 441sub evaluate_path_info {
 442        return if defined $project;
 443        my $path_info = $ENV{"PATH_INFO"};
 444        return if !$path_info;
 445        $path_info =~ s,^/+,,;
 446        return if !$path_info;
 447        # find which part of PATH_INFO is project
 448        $project = $path_info;
 449        $project =~ s,/+$,,;
 450        while ($project && !check_head_link("$projectroot/$project")) {
 451                $project =~ s,/*[^/]*$,,;
 452        }
 453        # validate project
 454        $project = validate_pathname($project);
 455        if (!$project ||
 456            ($export_ok && !-e "$projectroot/$project/$export_ok") ||
 457            ($strict_export && !project_in_list($project))) {
 458                undef $project;
 459                return;
 460        }
 461        # do not change any parameters if an action is given using the query string
 462        return if $action;
 463        $path_info =~ s,^$project/*,,;
 464        my ($refname, $pathname) = split(/:/, $path_info, 2);
 465        if (defined $pathname) {
 466                # we got "project.git/branch:filename" or "project.git/branch:dir/"
 467                # we could use git_get_type(branch:pathname), but it needs $git_dir
 468                $pathname =~ s,^/+,,;
 469                if (!$pathname || substr($pathname, -1) eq "/") {
 470                        $action  ||= "tree";
 471                        $pathname =~ s,/$,,;
 472                } else {
 473                        $action  ||= "blob_plain";
 474                }
 475                $hash_base ||= validate_refname($refname);
 476                $file_name ||= validate_pathname($pathname);
 477        } elsif (defined $refname) {
 478                # we got "project.git/branch"
 479                $action ||= "shortlog";
 480                $hash   ||= validate_refname($refname);
 481        }
 482}
 483evaluate_path_info();
 484
 485# path to the current git repository
 486our $git_dir;
 487$git_dir = "$projectroot/$project" if $project;
 488
 489# dispatch
 490my %actions = (
 491        "blame" => \&git_blame2,
 492        "blobdiff" => \&git_blobdiff,
 493        "blobdiff_plain" => \&git_blobdiff_plain,
 494        "blob" => \&git_blob,
 495        "blob_plain" => \&git_blob_plain,
 496        "commitdiff" => \&git_commitdiff,
 497        "commitdiff_plain" => \&git_commitdiff_plain,
 498        "commit" => \&git_commit,
 499        "forks" => \&git_forks,
 500        "heads" => \&git_heads,
 501        "history" => \&git_history,
 502        "log" => \&git_log,
 503        "rss" => \&git_rss,
 504        "atom" => \&git_atom,
 505        "search" => \&git_search,
 506        "search_help" => \&git_search_help,
 507        "shortlog" => \&git_shortlog,
 508        "summary" => \&git_summary,
 509        "tag" => \&git_tag,
 510        "tags" => \&git_tags,
 511        "tree" => \&git_tree,
 512        "snapshot" => \&git_snapshot,
 513        "object" => \&git_object,
 514        # those below don't need $project
 515        "opml" => \&git_opml,
 516        "project_list" => \&git_project_list,
 517        "project_index" => \&git_project_index,
 518);
 519
 520if (!defined $action) {
 521        if (defined $hash) {
 522                $action = git_get_type($hash);
 523        } elsif (defined $hash_base && defined $file_name) {
 524                $action = git_get_type("$hash_base:$file_name");
 525        } elsif (defined $project) {
 526                $action = 'summary';
 527        } else {
 528                $action = 'project_list';
 529        }
 530}
 531if (!defined($actions{$action})) {
 532        die_error(undef, "Unknown action");
 533}
 534if ($action !~ m/^(opml|project_list|project_index)$/ &&
 535    !$project) {
 536        die_error(undef, "Project needed");
 537}
 538$actions{$action}->();
 539exit;
 540
 541## ======================================================================
 542## action links
 543
 544sub href(%) {
 545        my %params = @_;
 546        # default is to use -absolute url() i.e. $my_uri
 547        my $href = $params{-full} ? $my_url : $my_uri;
 548
 549        # XXX: Warning: If you touch this, check the search form for updating,
 550        # too.
 551
 552        my @mapping = (
 553                project => "p",
 554                action => "a",
 555                file_name => "f",
 556                file_parent => "fp",
 557                extra_options => "opt",
 558                hash => "h",
 559                hash_parent => "hp",
 560                hash_base => "hb",
 561                hash_parent_base => "hpb",
 562                page => "pg",
 563                order => "o",
 564                searchtext => "s",
 565                searchtype => "st",
 566        );
 567        my %mapping = @mapping;
 568
 569        $params{'project'} = $project unless exists $params{'project'};
 570
 571        my ($use_pathinfo) = gitweb_check_feature('pathinfo');
 572        if ($use_pathinfo) {
 573                # use PATH_INFO for project name
 574                $href .= "/$params{'project'}" if defined $params{'project'};
 575                delete $params{'project'};
 576
 577                # Summary just uses the project path URL
 578                if (defined $params{'action'} && $params{'action'} eq 'summary') {
 579                        delete $params{'action'};
 580                }
 581        }
 582
 583        # now encode the parameters explicitly
 584        my @result = ();
 585        for (my $i = 0; $i < @mapping; $i += 2) {
 586                my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
 587                if (defined $params{$name}) {
 588                        push @result, $symbol . "=" . esc_param($params{$name});
 589                }
 590        }
 591        $href .= "?" . join(';', @result) if scalar @result;
 592
 593        return $href;
 594}
 595
 596
 597## ======================================================================
 598## validation, quoting/unquoting and escaping
 599
 600sub validate_pathname {
 601        my $input = shift || return undef;
 602
 603        # no '.' or '..' as elements of path, i.e. no '.' nor '..'
 604        # at the beginning, at the end, and between slashes.
 605        # also this catches doubled slashes
 606        if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
 607                return undef;
 608        }
 609        # no null characters
 610        if ($input =~ m!\0!) {
 611                return undef;
 612        }
 613        return $input;
 614}
 615
 616sub validate_refname {
 617        my $input = shift || return undef;
 618
 619        # textual hashes are O.K.
 620        if ($input =~ m/^[0-9a-fA-F]{40}$/) {
 621                return $input;
 622        }
 623        # it must be correct pathname
 624        $input = validate_pathname($input)
 625                or return undef;
 626        # restrictions on ref name according to git-check-ref-format
 627        if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
 628                return undef;
 629        }
 630        return $input;
 631}
 632
 633# decode sequences of octets in utf8 into Perl's internal form,
 634# which is utf-8 with utf8 flag set if needed.  gitweb writes out
 635# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
 636sub to_utf8 {
 637        my $str = shift;
 638        my $res;
 639        eval { $res = decode_utf8($str, Encode::FB_CROAK); };
 640        if (defined $res) {
 641                return $res;
 642        } else {
 643                return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
 644        }
 645}
 646
 647# quote unsafe chars, but keep the slash, even when it's not
 648# correct, but quoted slashes look too horrible in bookmarks
 649sub esc_param {
 650        my $str = shift;
 651        $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
 652        $str =~ s/\+/%2B/g;
 653        $str =~ s/ /\+/g;
 654        return $str;
 655}
 656
 657# quote unsafe chars in whole URL, so some charactrs cannot be quoted
 658sub esc_url {
 659        my $str = shift;
 660        $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
 661        $str =~ s/\+/%2B/g;
 662        $str =~ s/ /\+/g;
 663        return $str;
 664}
 665
 666# replace invalid utf8 character with SUBSTITUTION sequence
 667sub esc_html ($;%) {
 668        my $str = shift;
 669        my %opts = @_;
 670
 671        $str = to_utf8($str);
 672        $str = $cgi->escapeHTML($str);
 673        if ($opts{'-nbsp'}) {
 674                $str =~ s/ /&nbsp;/g;
 675        }
 676        $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
 677        return $str;
 678}
 679
 680# quote control characters and escape filename to HTML
 681sub esc_path {
 682        my $str = shift;
 683        my %opts = @_;
 684
 685        $str = to_utf8($str);
 686        $str = $cgi->escapeHTML($str);
 687        if ($opts{'-nbsp'}) {
 688                $str =~ s/ /&nbsp;/g;
 689        }
 690        $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
 691        return $str;
 692}
 693
 694# Make control characters "printable", using character escape codes (CEC)
 695sub quot_cec {
 696        my $cntrl = shift;
 697        my %es = ( # character escape codes, aka escape sequences
 698                   "\t" => '\t',   # tab            (HT)
 699                   "\n" => '\n',   # line feed      (LF)
 700                   "\r" => '\r',   # carrige return (CR)
 701                   "\f" => '\f',   # form feed      (FF)
 702                   "\b" => '\b',   # backspace      (BS)
 703                   "\a" => '\a',   # alarm (bell)   (BEL)
 704                   "\e" => '\e',   # escape         (ESC)
 705                   "\013" => '\v', # vertical tab   (VT)
 706                   "\000" => '\0', # nul character  (NUL)
 707                   );
 708        my $chr = ( (exists $es{$cntrl})
 709                    ? $es{$cntrl}
 710                    : sprintf('\%03o', ord($cntrl)) );
 711        return "<span class=\"cntrl\">$chr</span>";
 712}
 713
 714# Alternatively use unicode control pictures codepoints,
 715# Unicode "printable representation" (PR)
 716sub quot_upr {
 717        my $cntrl = shift;
 718        my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
 719        return "<span class=\"cntrl\">$chr</span>";
 720}
 721
 722# git may return quoted and escaped filenames
 723sub unquote {
 724        my $str = shift;
 725
 726        sub unq {
 727                my $seq = shift;
 728                my %es = ( # character escape codes, aka escape sequences
 729                        't' => "\t",   # tab            (HT, TAB)
 730                        'n' => "\n",   # newline        (NL)
 731                        'r' => "\r",   # return         (CR)
 732                        'f' => "\f",   # form feed      (FF)
 733                        'b' => "\b",   # backspace      (BS)
 734                        'a' => "\a",   # alarm (bell)   (BEL)
 735                        'e' => "\e",   # escape         (ESC)
 736                        'v' => "\013", # vertical tab   (VT)
 737                );
 738
 739                if ($seq =~ m/^[0-7]{1,3}$/) {
 740                        # octal char sequence
 741                        return chr(oct($seq));
 742                } elsif (exists $es{$seq}) {
 743                        # C escape sequence, aka character escape code
 744                        return $es{$seq}
 745                }
 746                # quoted ordinary character
 747                return $seq;
 748        }
 749
 750        if ($str =~ m/^"(.*)"$/) {
 751                # needs unquoting
 752                $str = $1;
 753                $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
 754        }
 755        return $str;
 756}
 757
 758# escape tabs (convert tabs to spaces)
 759sub untabify {
 760        my $line = shift;
 761
 762        while ((my $pos = index($line, "\t")) != -1) {
 763                if (my $count = (8 - ($pos % 8))) {
 764                        my $spaces = ' ' x $count;
 765                        $line =~ s/\t/$spaces/;
 766                }
 767        }
 768
 769        return $line;
 770}
 771
 772sub project_in_list {
 773        my $project = shift;
 774        my @list = git_get_projects_list();
 775        return @list && scalar(grep { $_->{'path'} eq $project } @list);
 776}
 777
 778## ----------------------------------------------------------------------
 779## HTML aware string manipulation
 780
 781sub chop_str {
 782        my $str = shift;
 783        my $len = shift;
 784        my $add_len = shift || 10;
 785
 786        # allow only $len chars, but don't cut a word if it would fit in $add_len
 787        # if it doesn't fit, cut it if it's still longer than the dots we would add
 788        $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
 789        my $body = $1;
 790        my $tail = $2;
 791        if (length($tail) > 4) {
 792                $tail = " ...";
 793                $body =~ s/&[^;]*$//; # remove chopped character entities
 794        }
 795        return "$body$tail";
 796}
 797
 798## ----------------------------------------------------------------------
 799## functions returning short strings
 800
 801# CSS class for given age value (in seconds)
 802sub age_class {
 803        my $age = shift;
 804
 805        if (!defined $age) {
 806                return "noage";
 807        } elsif ($age < 60*60*2) {
 808                return "age0";
 809        } elsif ($age < 60*60*24*2) {
 810                return "age1";
 811        } else {
 812                return "age2";
 813        }
 814}
 815
 816# convert age in seconds to "nn units ago" string
 817sub age_string {
 818        my $age = shift;
 819        my $age_str;
 820
 821        if ($age > 60*60*24*365*2) {
 822                $age_str = (int $age/60/60/24/365);
 823                $age_str .= " years ago";
 824        } elsif ($age > 60*60*24*(365/12)*2) {
 825                $age_str = int $age/60/60/24/(365/12);
 826                $age_str .= " months ago";
 827        } elsif ($age > 60*60*24*7*2) {
 828                $age_str = int $age/60/60/24/7;
 829                $age_str .= " weeks ago";
 830        } elsif ($age > 60*60*24*2) {
 831                $age_str = int $age/60/60/24;
 832                $age_str .= " days ago";
 833        } elsif ($age > 60*60*2) {
 834                $age_str = int $age/60/60;
 835                $age_str .= " hours ago";
 836        } elsif ($age > 60*2) {
 837                $age_str = int $age/60;
 838                $age_str .= " min ago";
 839        } elsif ($age > 2) {
 840                $age_str = int $age;
 841                $age_str .= " sec ago";
 842        } else {
 843                $age_str .= " right now";
 844        }
 845        return $age_str;
 846}
 847
 848# convert file mode in octal to symbolic file mode string
 849sub mode_str {
 850        my $mode = oct shift;
 851
 852        if (S_ISDIR($mode & S_IFMT)) {
 853                return 'drwxr-xr-x';
 854        } elsif (S_ISLNK($mode)) {
 855                return 'lrwxrwxrwx';
 856        } elsif (S_ISREG($mode)) {
 857                # git cares only about the executable bit
 858                if ($mode & S_IXUSR) {
 859                        return '-rwxr-xr-x';
 860                } else {
 861                        return '-rw-r--r--';
 862                };
 863        } else {
 864                return '----------';
 865        }
 866}
 867
 868# convert file mode in octal to file type string
 869sub file_type {
 870        my $mode = shift;
 871
 872        if ($mode !~ m/^[0-7]+$/) {
 873                return $mode;
 874        } else {
 875                $mode = oct $mode;
 876        }
 877
 878        if (S_ISDIR($mode & S_IFMT)) {
 879                return "directory";
 880        } elsif (S_ISLNK($mode)) {
 881                return "symlink";
 882        } elsif (S_ISREG($mode)) {
 883                return "file";
 884        } else {
 885                return "unknown";
 886        }
 887}
 888
 889# convert file mode in octal to file type description string
 890sub file_type_long {
 891        my $mode = shift;
 892
 893        if ($mode !~ m/^[0-7]+$/) {
 894                return $mode;
 895        } else {
 896                $mode = oct $mode;
 897        }
 898
 899        if (S_ISDIR($mode & S_IFMT)) {
 900                return "directory";
 901        } elsif (S_ISLNK($mode)) {
 902                return "symlink";
 903        } elsif (S_ISREG($mode)) {
 904                if ($mode & S_IXUSR) {
 905                        return "executable";
 906                } else {
 907                        return "file";
 908                };
 909        } else {
 910                return "unknown";
 911        }
 912}
 913
 914
 915## ----------------------------------------------------------------------
 916## functions returning short HTML fragments, or transforming HTML fragments
 917## which don't belong to other sections
 918
 919# format line of commit message.
 920sub format_log_line_html {
 921        my $line = shift;
 922
 923        $line = esc_html($line, -nbsp=>1);
 924        if ($line =~ m/([0-9a-fA-F]{8,40})/) {
 925                my $hash_text = $1;
 926                my $link =
 927                        $cgi->a({-href => href(action=>"object", hash=>$hash_text),
 928                                -class => "text"}, $hash_text);
 929                $line =~ s/$hash_text/$link/;
 930        }
 931        return $line;
 932}
 933
 934# format marker of refs pointing to given object
 935sub format_ref_marker {
 936        my ($refs, $id) = @_;
 937        my $markers = '';
 938
 939        if (defined $refs->{$id}) {
 940                foreach my $ref (@{$refs->{$id}}) {
 941                        my ($type, $name) = qw();
 942                        # e.g. tags/v2.6.11 or heads/next
 943                        if ($ref =~ m!^(.*?)s?/(.*)$!) {
 944                                $type = $1;
 945                                $name = $2;
 946                        } else {
 947                                $type = "ref";
 948                                $name = $ref;
 949                        }
 950
 951                        $markers .= " <span class=\"$type\" title=\"$ref\">" .
 952                                    esc_html($name) . "</span>";
 953                }
 954        }
 955
 956        if ($markers) {
 957                return ' <span class="refs">'. $markers . '</span>';
 958        } else {
 959                return "";
 960        }
 961}
 962
 963# format, perhaps shortened and with markers, title line
 964sub format_subject_html {
 965        my ($long, $short, $href, $extra) = @_;
 966        $extra = '' unless defined($extra);
 967
 968        if (length($short) < length($long)) {
 969                return $cgi->a({-href => $href, -class => "list subject",
 970                                -title => to_utf8($long)},
 971                       esc_html($short) . $extra);
 972        } else {
 973                return $cgi->a({-href => $href, -class => "list subject"},
 974                       esc_html($long)  . $extra);
 975        }
 976}
 977
 978# format git diff header line, i.e. "diff --(git|combined|cc) ..."
 979sub format_git_diff_header_line {
 980        my $line = shift;
 981        my $diffinfo = shift;
 982        my ($from, $to) = @_;
 983
 984        if ($diffinfo->{'nparents'}) {
 985                # combined diff
 986                $line =~ s!^(diff (.*?) )"?.*$!$1!;
 987                if ($to->{'href'}) {
 988                        $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
 989                                         esc_path($to->{'file'}));
 990                } else { # file was deleted (no href)
 991                        $line .= esc_path($to->{'file'});
 992                }
 993        } else {
 994                # "ordinary" diff
 995                $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
 996                if ($from->{'href'}) {
 997                        $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
 998                                         'a/' . esc_path($from->{'file'}));
 999                } else { # file was added (no href)
1000                        $line .= 'a/' . esc_path($from->{'file'});
1001                }
1002                $line .= ' ';
1003                if ($to->{'href'}) {
1004                        $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1005                                         'b/' . esc_path($to->{'file'}));
1006                } else { # file was deleted
1007                        $line .= 'b/' . esc_path($to->{'file'});
1008                }
1009        }
1010
1011        return "<div class=\"diff header\">$line</div>\n";
1012}
1013
1014# format extended diff header line, before patch itself
1015sub format_extended_diff_header_line {
1016        my $line = shift;
1017        my $diffinfo = shift;
1018        my ($from, $to) = @_;
1019
1020        # match <path>
1021        if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1022                $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1023                                       esc_path($from->{'file'}));
1024        }
1025        if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1026                $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1027                                 esc_path($to->{'file'}));
1028        }
1029        # match single <mode>
1030        if ($line =~ m/\s(\d{6})$/) {
1031                $line .= '<span class="info"> (' .
1032                         file_type_long($1) .
1033                         ')</span>';
1034        }
1035        # match <hash>
1036        if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1037                # can match only for combined diff
1038                $line = 'index ';
1039                for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1040                        if ($from->{'href'}[$i]) {
1041                                $line .= $cgi->a({-href=>$from->{'href'}[$i],
1042                                                  -class=>"hash"},
1043                                                 substr($diffinfo->{'from_id'}[$i],0,7));
1044                        } else {
1045                                $line .= '0' x 7;
1046                        }
1047                        # separator
1048                        $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1049                }
1050                $line .= '..';
1051                if ($to->{'href'}) {
1052                        $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1053                                         substr($diffinfo->{'to_id'},0,7));
1054                } else {
1055                        $line .= '0' x 7;
1056                }
1057
1058        } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1059                # can match only for ordinary diff
1060                my ($from_link, $to_link);
1061                if ($from->{'href'}) {
1062                        $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1063                                             substr($diffinfo->{'from_id'},0,7));
1064                } else {
1065                        $from_link = '0' x 7;
1066                }
1067                if ($to->{'href'}) {
1068                        $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1069                                           substr($diffinfo->{'to_id'},0,7));
1070                } else {
1071                        $to_link = '0' x 7;
1072                }
1073                my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1074                $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1075        }
1076
1077        return $line . "<br/>\n";
1078}
1079
1080# format from-file/to-file diff header
1081sub format_diff_from_to_header {
1082        my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1083        my $line;
1084        my $result = '';
1085
1086        $line = $from_line;
1087        #assert($line =~ m/^---/) if DEBUG;
1088        # no extra formatting for "^--- /dev/null"
1089        if (! $diffinfo->{'nparents'}) {
1090                # ordinary (single parent) diff
1091                if ($line =~ m!^--- "?a/!) {
1092                        if ($from->{'href'}) {
1093                                $line = '--- a/' .
1094                                        $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1095                                                esc_path($from->{'file'}));
1096                        } else {
1097                                $line = '--- a/' .
1098                                        esc_path($from->{'file'});
1099                        }
1100                }
1101                $result .= qq!<div class="diff from_file">$line</div>\n!;
1102
1103        } else {
1104                # combined diff (merge commit)
1105                for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1106                        if ($from->{'href'}[$i]) {
1107                                $line = '--- ' .
1108                                        $cgi->a({-href=>href(action=>"blobdiff",
1109                                                             hash_parent=>$diffinfo->{'from_id'}[$i],
1110                                                             hash_parent_base=>$parents[$i],
1111                                                             file_parent=>$from->{'file'}[$i],
1112                                                             hash=>$diffinfo->{'to_id'},
1113                                                             hash_base=>$hash,
1114                                                             file_name=>$to->{'file'}),
1115                                                 -class=>"path",
1116                                                 -title=>"diff" . ($i+1)},
1117                                                $i+1) .
1118                                        '/' .
1119                                        $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1120                                                esc_path($from->{'file'}[$i]));
1121                        } else {
1122                                $line = '--- /dev/null';
1123                        }
1124                        $result .= qq!<div class="diff from_file">$line</div>\n!;
1125                }
1126        }
1127
1128        $line = $to_line;
1129        #assert($line =~ m/^\+\+\+/) if DEBUG;
1130        # no extra formatting for "^+++ /dev/null"
1131        if ($line =~ m!^\+\+\+ "?b/!) {
1132                if ($to->{'href'}) {
1133                        $line = '+++ b/' .
1134                                $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1135                                        esc_path($to->{'file'}));
1136                } else {
1137                        $line = '+++ b/' .
1138                                esc_path($to->{'file'});
1139                }
1140        }
1141        $result .= qq!<div class="diff to_file">$line</div>\n!;
1142
1143        return $result;
1144}
1145
1146# create note for patch simplified by combined diff
1147sub format_diff_cc_simplified {
1148        my ($diffinfo, @parents) = @_;
1149        my $result = '';
1150
1151        $result .= "<div class=\"diff header\">" .
1152                   "diff --cc ";
1153        if (!is_deleted($diffinfo)) {
1154                $result .= $cgi->a({-href => href(action=>"blob",
1155                                                  hash_base=>$hash,
1156                                                  hash=>$diffinfo->{'to_id'},
1157                                                  file_name=>$diffinfo->{'to_file'}),
1158                                    -class => "path"},
1159                                   esc_path($diffinfo->{'to_file'}));
1160        } else {
1161                $result .= esc_path($diffinfo->{'to_file'});
1162        }
1163        $result .= "</div>\n" . # class="diff header"
1164                   "<div class=\"diff nodifferences\">" .
1165                   "Simple merge" .
1166                   "</div>\n"; # class="diff nodifferences"
1167
1168        return $result;
1169}
1170
1171# format patch (diff) line (not to be used for diff headers)
1172sub format_diff_line {
1173        my $line = shift;
1174        my ($from, $to) = @_;
1175        my $diff_class = "";
1176
1177        chomp $line;
1178
1179        if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1180                # combined diff
1181                my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1182                if ($line =~ m/^\@{3}/) {
1183                        $diff_class = " chunk_header";
1184                } elsif ($line =~ m/^\\/) {
1185                        $diff_class = " incomplete";
1186                } elsif ($prefix =~ tr/+/+/) {
1187                        $diff_class = " add";
1188                } elsif ($prefix =~ tr/-/-/) {
1189                        $diff_class = " rem";
1190                }
1191        } else {
1192                # assume ordinary diff
1193                my $char = substr($line, 0, 1);
1194                if ($char eq '+') {
1195                        $diff_class = " add";
1196                } elsif ($char eq '-') {
1197                        $diff_class = " rem";
1198                } elsif ($char eq '@') {
1199                        $diff_class = " chunk_header";
1200                } elsif ($char eq "\\") {
1201                        $diff_class = " incomplete";
1202                }
1203        }
1204        $line = untabify($line);
1205        if ($from && $to && $line =~ m/^\@{2} /) {
1206                my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1207                        $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1208
1209                $from_lines = 0 unless defined $from_lines;
1210                $to_lines   = 0 unless defined $to_lines;
1211
1212                if ($from->{'href'}) {
1213                        $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1214                                             -class=>"list"}, $from_text);
1215                }
1216                if ($to->{'href'}) {
1217                        $to_text   = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1218                                             -class=>"list"}, $to_text);
1219                }
1220                $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1221                        "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1222                return "<div class=\"diff$diff_class\">$line</div>\n";
1223        } elsif ($from && $to && $line =~ m/^\@{3}/) {
1224                my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1225                my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1226
1227                @from_text = split(' ', $ranges);
1228                for (my $i = 0; $i < @from_text; ++$i) {
1229                        ($from_start[$i], $from_nlines[$i]) =
1230                                (split(',', substr($from_text[$i], 1)), 0);
1231                }
1232
1233                $to_text   = pop @from_text;
1234                $to_start  = pop @from_start;
1235                $to_nlines = pop @from_nlines;
1236
1237                $line = "<span class=\"chunk_info\">$prefix ";
1238                for (my $i = 0; $i < @from_text; ++$i) {
1239                        if ($from->{'href'}[$i]) {
1240                                $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1241                                                  -class=>"list"}, $from_text[$i]);
1242                        } else {
1243                                $line .= $from_text[$i];
1244                        }
1245                        $line .= " ";
1246                }
1247                if ($to->{'href'}) {
1248                        $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1249                                          -class=>"list"}, $to_text);
1250                } else {
1251                        $line .= $to_text;
1252                }
1253                $line .= " $prefix</span>" .
1254                         "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1255                return "<div class=\"diff$diff_class\">$line</div>\n";
1256        }
1257        return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1258}
1259
1260## ----------------------------------------------------------------------
1261## git utility subroutines, invoking git commands
1262
1263# returns path to the core git executable and the --git-dir parameter as list
1264sub git_cmd {
1265        return $GIT, '--git-dir='.$git_dir;
1266}
1267
1268# returns path to the core git executable and the --git-dir parameter as string
1269sub git_cmd_str {
1270        return join(' ', git_cmd());
1271}
1272
1273# get HEAD ref of given project as hash
1274sub git_get_head_hash {
1275        my $project = shift;
1276        my $o_git_dir = $git_dir;
1277        my $retval = undef;
1278        $git_dir = "$projectroot/$project";
1279        if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
1280                my $head = <$fd>;
1281                close $fd;
1282                if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
1283                        $retval = $1;
1284                }
1285        }
1286        if (defined $o_git_dir) {
1287                $git_dir = $o_git_dir;
1288        }
1289        return $retval;
1290}
1291
1292# get type of given object
1293sub git_get_type {
1294        my $hash = shift;
1295
1296        open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
1297        my $type = <$fd>;
1298        close $fd or return;
1299        chomp $type;
1300        return $type;
1301}
1302
1303sub git_get_project_config {
1304        my ($key, $type) = @_;
1305
1306        return unless ($key);
1307        $key =~ s/^gitweb\.//;
1308        return if ($key =~ m/\W/);
1309
1310        my @x = (git_cmd(), 'config');
1311        if (defined $type) { push @x, $type; }
1312        push @x, "--get";
1313        push @x, "gitweb.$key";
1314        my $val = qx(@x);
1315        chomp $val;
1316        return ($val);
1317}
1318
1319# get hash of given path at given ref
1320sub git_get_hash_by_path {
1321        my $base = shift;
1322        my $path = shift || return undef;
1323        my $type = shift;
1324
1325        $path =~ s,/+$,,;
1326
1327        open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
1328                or die_error(undef, "Open git-ls-tree failed");
1329        my $line = <$fd>;
1330        close $fd or return undef;
1331
1332        if (!defined $line) {
1333                # there is no tree or hash given by $path at $base
1334                return undef;
1335        }
1336
1337        #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1338        $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
1339        if (defined $type && $type ne $2) {
1340                # type doesn't match
1341                return undef;
1342        }
1343        return $3;
1344}
1345
1346# get path of entry with given hash at given tree-ish (ref)
1347# used to get 'from' filename for combined diff (merge commit) for renames
1348sub git_get_path_by_hash {
1349        my $base = shift || return;
1350        my $hash = shift || return;
1351
1352        local $/ = "\0";
1353
1354        open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
1355                or return undef;
1356        while (my $line = <$fd>) {
1357                chomp $line;
1358
1359                #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423  gitweb'
1360                #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f  gitweb/README'
1361                if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
1362                        close $fd;
1363                        return $1;
1364                }
1365        }
1366        close $fd;
1367        return undef;
1368}
1369
1370## ......................................................................
1371## git utility functions, directly accessing git repository
1372
1373sub git_get_project_description {
1374        my $path = shift;
1375
1376        open my $fd, "$projectroot/$path/description" or return undef;
1377        my $descr = <$fd>;
1378        close $fd;
1379        if (defined $descr) {
1380                chomp $descr;
1381        }
1382        return $descr;
1383}
1384
1385sub git_get_project_url_list {
1386        my $path = shift;
1387
1388        open my $fd, "$projectroot/$path/cloneurl" or return;
1389        my @git_project_url_list = map { chomp; $_ } <$fd>;
1390        close $fd;
1391
1392        return wantarray ? @git_project_url_list : \@git_project_url_list;
1393}
1394
1395sub git_get_projects_list {
1396        my ($filter) = @_;
1397        my @list;
1398
1399        $filter ||= '';
1400        $filter =~ s/\.git$//;
1401
1402        my ($check_forks) = gitweb_check_feature('forks');
1403
1404        if (-d $projects_list) {
1405                # search in directory
1406                my $dir = $projects_list . ($filter ? "/$filter" : '');
1407                # remove the trailing "/"
1408                $dir =~ s!/+$!!;
1409                my $pfxlen = length("$dir");
1410
1411                File::Find::find({
1412                        follow_fast => 1, # follow symbolic links
1413                        dangling_symlinks => 0, # ignore dangling symlinks, silently
1414                        wanted => sub {
1415                                # skip project-list toplevel, if we get it.
1416                                return if (m!^[/.]$!);
1417                                # only directories can be git repositories
1418                                return unless (-d $_);
1419
1420                                my $subdir = substr($File::Find::name, $pfxlen + 1);
1421                                # we check related file in $projectroot
1422                                if ($check_forks and $subdir =~ m#/.#) {
1423                                        $File::Find::prune = 1;
1424                                } elsif (check_export_ok("$projectroot/$filter/$subdir")) {
1425                                        push @list, { path => ($filter ? "$filter/" : '') . $subdir };
1426                                        $File::Find::prune = 1;
1427                                }
1428                        },
1429                }, "$dir");
1430
1431        } elsif (-f $projects_list) {
1432                # read from file(url-encoded):
1433                # 'git%2Fgit.git Linus+Torvalds'
1434                # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1435                # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1436                my %paths;
1437                open my ($fd), $projects_list or return;
1438        PROJECT:
1439                while (my $line = <$fd>) {
1440                        chomp $line;
1441                        my ($path, $owner) = split ' ', $line;
1442                        $path = unescape($path);
1443                        $owner = unescape($owner);
1444                        if (!defined $path) {
1445                                next;
1446                        }
1447                        if ($filter ne '') {
1448                                # looking for forks;
1449                                my $pfx = substr($path, 0, length($filter));
1450                                if ($pfx ne $filter) {
1451                                        next PROJECT;
1452                                }
1453                                my $sfx = substr($path, length($filter));
1454                                if ($sfx !~ /^\/.*\.git$/) {
1455                                        next PROJECT;
1456                                }
1457                        } elsif ($check_forks) {
1458                        PATH:
1459                                foreach my $filter (keys %paths) {
1460                                        # looking for forks;
1461                                        my $pfx = substr($path, 0, length($filter));
1462                                        if ($pfx ne $filter) {
1463                                                next PATH;
1464                                        }
1465                                        my $sfx = substr($path, length($filter));
1466                                        if ($sfx !~ /^\/.*\.git$/) {
1467                                                next PATH;
1468                                        }
1469                                        # is a fork, don't include it in
1470                                        # the list
1471                                        next PROJECT;
1472                                }
1473                        }
1474                        if (check_export_ok("$projectroot/$path")) {
1475                                my $pr = {
1476                                        path => $path,
1477                                        owner => to_utf8($owner),
1478                                };
1479                                push @list, $pr;
1480                                (my $forks_path = $path) =~ s/\.git$//;
1481                                $paths{$forks_path}++;
1482                        }
1483                }
1484                close $fd;
1485        }
1486        return @list;
1487}
1488
1489our $gitweb_project_owner = undef;
1490sub git_get_project_list_from_file {
1491
1492        return if (defined $gitweb_project_owner);
1493
1494        $gitweb_project_owner = {};
1495        # read from file (url-encoded):
1496        # 'git%2Fgit.git Linus+Torvalds'
1497        # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1498        # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1499        if (-f $projects_list) {
1500                open (my $fd , $projects_list);
1501                while (my $line = <$fd>) {
1502                        chomp $line;
1503                        my ($pr, $ow) = split ' ', $line;
1504                        $pr = unescape($pr);
1505                        $ow = unescape($ow);
1506                        $gitweb_project_owner->{$pr} = to_utf8($ow);
1507                }
1508                close $fd;
1509        }
1510}
1511
1512sub git_get_project_owner {
1513        my $project = shift;
1514        my $owner;
1515
1516        return undef unless $project;
1517
1518        if (!defined $gitweb_project_owner) {
1519                git_get_project_list_from_file();
1520        }
1521
1522        if (exists $gitweb_project_owner->{$project}) {
1523                $owner = $gitweb_project_owner->{$project};
1524        }
1525        if (!defined $owner) {
1526                $owner = get_file_owner("$projectroot/$project");
1527        }
1528
1529        return $owner;
1530}
1531
1532sub git_get_last_activity {
1533        my ($path) = @_;
1534        my $fd;
1535
1536        $git_dir = "$projectroot/$path";
1537        open($fd, "-|", git_cmd(), 'for-each-ref',
1538             '--format=%(committer)',
1539             '--sort=-committerdate',
1540             '--count=1',
1541             'refs/heads') or return;
1542        my $most_recent = <$fd>;
1543        close $fd or return;
1544        if (defined $most_recent &&
1545            $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
1546                my $timestamp = $1;
1547                my $age = time - $timestamp;
1548                return ($age, age_string($age));
1549        }
1550        return (undef, undef);
1551}
1552
1553sub git_get_references {
1554        my $type = shift || "";
1555        my %refs;
1556        # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
1557        # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
1558        open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
1559                ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
1560                or return;
1561
1562        while (my $line = <$fd>) {
1563                chomp $line;
1564                if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type/?[^^]+)!) {
1565                        if (defined $refs{$1}) {
1566                                push @{$refs{$1}}, $2;
1567                        } else {
1568                                $refs{$1} = [ $2 ];
1569                        }
1570                }
1571        }
1572        close $fd or return;
1573        return \%refs;
1574}
1575
1576sub git_get_rev_name_tags {
1577        my $hash = shift || return undef;
1578
1579        open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
1580                or return;
1581        my $name_rev = <$fd>;
1582        close $fd;
1583
1584        if ($name_rev =~ m|^$hash tags/(.*)$|) {
1585                return $1;
1586        } else {
1587                # catches also '$hash undefined' output
1588                return undef;
1589        }
1590}
1591
1592## ----------------------------------------------------------------------
1593## parse to hash functions
1594
1595sub parse_date {
1596        my $epoch = shift;
1597        my $tz = shift || "-0000";
1598
1599        my %date;
1600        my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
1601        my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
1602        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
1603        $date{'hour'} = $hour;
1604        $date{'minute'} = $min;
1605        $date{'mday'} = $mday;
1606        $date{'day'} = $days[$wday];
1607        $date{'month'} = $months[$mon];
1608        $date{'rfc2822'}   = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
1609                             $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
1610        $date{'mday-time'} = sprintf "%d %s %02d:%02d",
1611                             $mday, $months[$mon], $hour ,$min;
1612        $date{'iso-8601'}  = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
1613                             1900+$year, $mon, $mday, $hour ,$min, $sec;
1614
1615        $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
1616        my $local = $epoch + ((int $1 + ($2/60)) * 3600);
1617        ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
1618        $date{'hour_local'} = $hour;
1619        $date{'minute_local'} = $min;
1620        $date{'tz_local'} = $tz;
1621        $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
1622                                  1900+$year, $mon+1, $mday,
1623                                  $hour, $min, $sec, $tz);
1624        return %date;
1625}
1626
1627sub parse_tag {
1628        my $tag_id = shift;
1629        my %tag;
1630        my @comment;
1631
1632        open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
1633        $tag{'id'} = $tag_id;
1634        while (my $line = <$fd>) {
1635                chomp $line;
1636                if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
1637                        $tag{'object'} = $1;
1638                } elsif ($line =~ m/^type (.+)$/) {
1639                        $tag{'type'} = $1;
1640                } elsif ($line =~ m/^tag (.+)$/) {
1641                        $tag{'name'} = $1;
1642                } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
1643                        $tag{'author'} = $1;
1644                        $tag{'epoch'} = $2;
1645                        $tag{'tz'} = $3;
1646                } elsif ($line =~ m/--BEGIN/) {
1647                        push @comment, $line;
1648                        last;
1649                } elsif ($line eq "") {
1650                        last;
1651                }
1652        }
1653        push @comment, <$fd>;
1654        $tag{'comment'} = \@comment;
1655        close $fd or return;
1656        if (!defined $tag{'name'}) {
1657                return
1658        };
1659        return %tag
1660}
1661
1662sub parse_commit_text {
1663        my ($commit_text, $withparents) = @_;
1664        my @commit_lines = split '\n', $commit_text;
1665        my %co;
1666
1667        pop @commit_lines; # Remove '\0'
1668
1669        if (! @commit_lines) {
1670                return;
1671        }
1672
1673        my $header = shift @commit_lines;
1674        if ($header !~ m/^[0-9a-fA-F]{40}/) {
1675                return;
1676        }
1677        ($co{'id'}, my @parents) = split ' ', $header;
1678        while (my $line = shift @commit_lines) {
1679                last if $line eq "\n";
1680                if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1681                        $co{'tree'} = $1;
1682                } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
1683                        push @parents, $1;
1684                } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1685                        $co{'author'} = $1;
1686                        $co{'author_epoch'} = $2;
1687                        $co{'author_tz'} = $3;
1688                        if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
1689                                $co{'author_name'}  = $1;
1690                                $co{'author_email'} = $2;
1691                        } else {
1692                                $co{'author_name'} = $co{'author'};
1693                        }
1694                } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1695                        $co{'committer'} = $1;
1696                        $co{'committer_epoch'} = $2;
1697                        $co{'committer_tz'} = $3;
1698                        $co{'committer_name'} = $co{'committer'};
1699                        if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
1700                                $co{'committer_name'}  = $1;
1701                                $co{'committer_email'} = $2;
1702                        } else {
1703                                $co{'committer_name'} = $co{'committer'};
1704                        }
1705                }
1706        }
1707        if (!defined $co{'tree'}) {
1708                return;
1709        };
1710        $co{'parents'} = \@parents;
1711        $co{'parent'} = $parents[0];
1712
1713        foreach my $title (@commit_lines) {
1714                $title =~ s/^    //;
1715                if ($title ne "") {
1716                        $co{'title'} = chop_str($title, 80, 5);
1717                        # remove leading stuff of merges to make the interesting part visible
1718                        if (length($title) > 50) {
1719                                $title =~ s/^Automatic //;
1720                                $title =~ s/^merge (of|with) /Merge ... /i;
1721                                if (length($title) > 50) {
1722                                        $title =~ s/(http|rsync):\/\///;
1723                                }
1724                                if (length($title) > 50) {
1725                                        $title =~ s/(master|www|rsync)\.//;
1726                                }
1727                                if (length($title) > 50) {
1728                                        $title =~ s/kernel.org:?//;
1729                                }
1730                                if (length($title) > 50) {
1731                                        $title =~ s/\/pub\/scm//;
1732                                }
1733                        }
1734                        $co{'title_short'} = chop_str($title, 50, 5);
1735                        last;
1736                }
1737        }
1738        if ($co{'title'} eq "") {
1739                $co{'title'} = $co{'title_short'} = '(no commit message)';
1740        }
1741        # remove added spaces
1742        foreach my $line (@commit_lines) {
1743                $line =~ s/^    //;
1744        }
1745        $co{'comment'} = \@commit_lines;
1746
1747        my $age = time - $co{'committer_epoch'};
1748        $co{'age'} = $age;
1749        $co{'age_string'} = age_string($age);
1750        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1751        if ($age > 60*60*24*7*2) {
1752                $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1753                $co{'age_string_age'} = $co{'age_string'};
1754        } else {
1755                $co{'age_string_date'} = $co{'age_string'};
1756                $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1757        }
1758        return %co;
1759}
1760
1761sub parse_commit {
1762        my ($commit_id) = @_;
1763        my %co;
1764
1765        local $/ = "\0";
1766
1767        open my $fd, "-|", git_cmd(), "rev-list",
1768                "--parents",
1769                "--header",
1770                "--max-count=1",
1771                $commit_id,
1772                "--",
1773                or die_error(undef, "Open git-rev-list failed");
1774        %co = parse_commit_text(<$fd>, 1);
1775        close $fd;
1776
1777        return %co;
1778}
1779
1780sub parse_commits {
1781        my ($commit_id, $maxcount, $skip, $arg, $filename) = @_;
1782        my @cos;
1783
1784        $maxcount ||= 1;
1785        $skip ||= 0;
1786
1787        local $/ = "\0";
1788
1789        open my $fd, "-|", git_cmd(), "rev-list",
1790                "--header",
1791                ($arg ? ($arg) : ()),
1792                ("--max-count=" . $maxcount),
1793                ("--skip=" . $skip),
1794                @extra_options,
1795                $commit_id,
1796                "--",
1797                ($filename ? ($filename) : ())
1798                or die_error(undef, "Open git-rev-list failed");
1799        while (my $line = <$fd>) {
1800                my %co = parse_commit_text($line);
1801                push @cos, \%co;
1802        }
1803        close $fd;
1804
1805        return wantarray ? @cos : \@cos;
1806}
1807
1808# parse ref from ref_file, given by ref_id, with given type
1809sub parse_ref {
1810        my $ref_file = shift;
1811        my $ref_id = shift;
1812        my $type = shift || git_get_type($ref_id);
1813        my %ref_item;
1814
1815        $ref_item{'type'} = $type;
1816        $ref_item{'id'} = $ref_id;
1817        $ref_item{'epoch'} = 0;
1818        $ref_item{'age'} = "unknown";
1819        if ($type eq "tag") {
1820                my %tag = parse_tag($ref_id);
1821                $ref_item{'comment'} = $tag{'comment'};
1822                if ($tag{'type'} eq "commit") {
1823                        my %co = parse_commit($tag{'object'});
1824                        $ref_item{'epoch'} = $co{'committer_epoch'};
1825                        $ref_item{'age'} = $co{'age_string'};
1826                } elsif (defined($tag{'epoch'})) {
1827                        my $age = time - $tag{'epoch'};
1828                        $ref_item{'epoch'} = $tag{'epoch'};
1829                        $ref_item{'age'} = age_string($age);
1830                }
1831                $ref_item{'reftype'} = $tag{'type'};
1832                $ref_item{'name'} = $tag{'name'};
1833                $ref_item{'refid'} = $tag{'object'};
1834        } elsif ($type eq "commit"){
1835                my %co = parse_commit($ref_id);
1836                $ref_item{'reftype'} = "commit";
1837                $ref_item{'name'} = $ref_file;
1838                $ref_item{'title'} = $co{'title'};
1839                $ref_item{'refid'} = $ref_id;
1840                $ref_item{'epoch'} = $co{'committer_epoch'};
1841                $ref_item{'age'} = $co{'age_string'};
1842        } else {
1843                $ref_item{'reftype'} = $type;
1844                $ref_item{'name'} = $ref_file;
1845                $ref_item{'refid'} = $ref_id;
1846        }
1847
1848        return %ref_item;
1849}
1850
1851# parse line of git-diff-tree "raw" output
1852sub parse_difftree_raw_line {
1853        my $line = shift;
1854        my %res;
1855
1856        # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1857        # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1858        if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1859                $res{'from_mode'} = $1;
1860                $res{'to_mode'} = $2;
1861                $res{'from_id'} = $3;
1862                $res{'to_id'} = $4;
1863                $res{'status'} = $5;
1864                $res{'similarity'} = $6;
1865                if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1866                        ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1867                } else {
1868                        $res{'file'} = unquote($7);
1869                }
1870        }
1871        # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
1872        # combined diff (for merge commit)
1873        elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
1874                $res{'nparents'}  = length($1);
1875                $res{'from_mode'} = [ split(' ', $2) ];
1876                $res{'to_mode'} = pop @{$res{'from_mode'}};
1877                $res{'from_id'} = [ split(' ', $3) ];
1878                $res{'to_id'} = pop @{$res{'from_id'}};
1879                $res{'status'} = [ split('', $4) ];
1880                $res{'to_file'} = unquote($5);
1881        }
1882        # 'c512b523472485aef4fff9e57b229d9d243c967f'
1883        elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1884                $res{'commit'} = $1;
1885        }
1886
1887        return wantarray ? %res : \%res;
1888}
1889
1890# parse line of git-ls-tree output
1891sub parse_ls_tree_line ($;%) {
1892        my $line = shift;
1893        my %opts = @_;
1894        my %res;
1895
1896        #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1897        $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
1898
1899        $res{'mode'} = $1;
1900        $res{'type'} = $2;
1901        $res{'hash'} = $3;
1902        if ($opts{'-z'}) {
1903                $res{'name'} = $4;
1904        } else {
1905                $res{'name'} = unquote($4);
1906        }
1907
1908        return wantarray ? %res : \%res;
1909}
1910
1911# generates _two_ hashes, references to which are passed as 2 and 3 argument
1912sub parse_from_to_diffinfo {
1913        my ($diffinfo, $from, $to, @parents) = @_;
1914
1915        if ($diffinfo->{'nparents'}) {
1916                # combined diff
1917                $from->{'file'} = [];
1918                $from->{'href'} = [];
1919                fill_from_file_info($diffinfo, @parents)
1920                        unless exists $diffinfo->{'from_file'};
1921                for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1922                        $from->{'file'}[$i] = $diffinfo->{'from_file'}[$i] || $diffinfo->{'to_file'};
1923                        if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
1924                                $from->{'href'}[$i] = href(action=>"blob",
1925                                                           hash_base=>$parents[$i],
1926                                                           hash=>$diffinfo->{'from_id'}[$i],
1927                                                           file_name=>$from->{'file'}[$i]);
1928                        } else {
1929                                $from->{'href'}[$i] = undef;
1930                        }
1931                }
1932        } else {
1933                $from->{'file'} = $diffinfo->{'from_file'} || $diffinfo->{'file'};
1934                if ($diffinfo->{'status'} ne "A") { # not new (added) file
1935                        $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
1936                                               hash=>$diffinfo->{'from_id'},
1937                                               file_name=>$from->{'file'});
1938                } else {
1939                        delete $from->{'href'};
1940                }
1941        }
1942
1943        $to->{'file'} = $diffinfo->{'to_file'} || $diffinfo->{'file'};
1944        if (!is_deleted($diffinfo)) { # file exists in result
1945                $to->{'href'} = href(action=>"blob", hash_base=>$hash,
1946                                     hash=>$diffinfo->{'to_id'},
1947                                     file_name=>$to->{'file'});
1948        } else {
1949                delete $to->{'href'};
1950        }
1951}
1952
1953## ......................................................................
1954## parse to array of hashes functions
1955
1956sub git_get_heads_list {
1957        my $limit = shift;
1958        my @headslist;
1959
1960        open my $fd, '-|', git_cmd(), 'for-each-ref',
1961                ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
1962                '--format=%(objectname) %(refname) %(subject)%00%(committer)',
1963                'refs/heads'
1964                or return;
1965        while (my $line = <$fd>) {
1966                my %ref_item;
1967
1968                chomp $line;
1969                my ($refinfo, $committerinfo) = split(/\0/, $line);
1970                my ($hash, $name, $title) = split(' ', $refinfo, 3);
1971                my ($committer, $epoch, $tz) =
1972                        ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
1973                $name =~ s!^refs/heads/!!;
1974
1975                $ref_item{'name'}  = $name;
1976                $ref_item{'id'}    = $hash;
1977                $ref_item{'title'} = $title || '(no commit message)';
1978                $ref_item{'epoch'} = $epoch;
1979                if ($epoch) {
1980                        $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
1981                } else {
1982                        $ref_item{'age'} = "unknown";
1983                }
1984
1985                push @headslist, \%ref_item;
1986        }
1987        close $fd;
1988
1989        return wantarray ? @headslist : \@headslist;
1990}
1991
1992sub git_get_tags_list {
1993        my $limit = shift;
1994        my @tagslist;
1995
1996        open my $fd, '-|', git_cmd(), 'for-each-ref',
1997                ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
1998                '--format=%(objectname) %(objecttype) %(refname) '.
1999                '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2000                'refs/tags'
2001                or return;
2002        while (my $line = <$fd>) {
2003                my %ref_item;
2004
2005                chomp $line;
2006                my ($refinfo, $creatorinfo) = split(/\0/, $line);
2007                my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2008                my ($creator, $epoch, $tz) =
2009                        ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2010                $name =~ s!^refs/tags/!!;
2011
2012                $ref_item{'type'} = $type;
2013                $ref_item{'id'} = $id;
2014                $ref_item{'name'} = $name;
2015                if ($type eq "tag") {
2016                        $ref_item{'subject'} = $title;
2017                        $ref_item{'reftype'} = $reftype;
2018                        $ref_item{'refid'}   = $refid;
2019                } else {
2020                        $ref_item{'reftype'} = $type;
2021                        $ref_item{'refid'}   = $id;
2022                }
2023
2024                if ($type eq "tag" || $type eq "commit") {
2025                        $ref_item{'epoch'} = $epoch;
2026                        if ($epoch) {
2027                                $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2028                        } else {
2029                                $ref_item{'age'} = "unknown";
2030                        }
2031                }
2032
2033                push @tagslist, \%ref_item;
2034        }
2035        close $fd;
2036
2037        return wantarray ? @tagslist : \@tagslist;
2038}
2039
2040## ----------------------------------------------------------------------
2041## filesystem-related functions
2042
2043sub get_file_owner {
2044        my $path = shift;
2045
2046        my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2047        my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2048        if (!defined $gcos) {
2049                return undef;
2050        }
2051        my $owner = $gcos;
2052        $owner =~ s/[,;].*$//;
2053        return to_utf8($owner);
2054}
2055
2056## ......................................................................
2057## mimetype related functions
2058
2059sub mimetype_guess_file {
2060        my $filename = shift;
2061        my $mimemap = shift;
2062        -r $mimemap or return undef;
2063
2064        my %mimemap;
2065        open(MIME, $mimemap) or return undef;
2066        while (<MIME>) {
2067                next if m/^#/; # skip comments
2068                my ($mime, $exts) = split(/\t+/);
2069                if (defined $exts) {
2070                        my @exts = split(/\s+/, $exts);
2071                        foreach my $ext (@exts) {
2072                                $mimemap{$ext} = $mime;
2073                        }
2074                }
2075        }
2076        close(MIME);
2077
2078        $filename =~ /\.([^.]*)$/;
2079        return $mimemap{$1};
2080}
2081
2082sub mimetype_guess {
2083        my $filename = shift;
2084        my $mime;
2085        $filename =~ /\./ or return undef;
2086
2087        if ($mimetypes_file) {
2088                my $file = $mimetypes_file;
2089                if ($file !~ m!^/!) { # if it is relative path
2090                        # it is relative to project
2091                        $file = "$projectroot/$project/$file";
2092                }
2093                $mime = mimetype_guess_file($filename, $file);
2094        }
2095        $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
2096        return $mime;
2097}
2098
2099sub blob_mimetype {
2100        my $fd = shift;
2101        my $filename = shift;
2102
2103        if ($filename) {
2104                my $mime = mimetype_guess($filename);
2105                $mime and return $mime;
2106        }
2107
2108        # just in case
2109        return $default_blob_plain_mimetype unless $fd;
2110
2111        if (-T $fd) {
2112                return 'text/plain' .
2113                       ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
2114        } elsif (! $filename) {
2115                return 'application/octet-stream';
2116        } elsif ($filename =~ m/\.png$/i) {
2117                return 'image/png';
2118        } elsif ($filename =~ m/\.gif$/i) {
2119                return 'image/gif';
2120        } elsif ($filename =~ m/\.jpe?g$/i) {
2121                return 'image/jpeg';
2122        } else {
2123                return 'application/octet-stream';
2124        }
2125}
2126
2127## ======================================================================
2128## functions printing HTML: header, footer, error page
2129
2130sub git_header_html {
2131        my $status = shift || "200 OK";
2132        my $expires = shift;
2133
2134        my $title = "$site_name";
2135        if (defined $project) {
2136                $title .= " - " . to_utf8($project);
2137                if (defined $action) {
2138                        $title .= "/$action";
2139                        if (defined $file_name) {
2140                                $title .= " - " . esc_path($file_name);
2141                                if ($action eq "tree" && $file_name !~ m|/$|) {
2142                                        $title .= "/";
2143                                }
2144                        }
2145                }
2146        }
2147        my $content_type;
2148        # require explicit support from the UA if we are to send the page as
2149        # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
2150        # we have to do this because MSIE sometimes globs '*/*', pretending to
2151        # support xhtml+xml but choking when it gets what it asked for.
2152        if (defined $cgi->http('HTTP_ACCEPT') &&
2153            $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
2154            $cgi->Accept('application/xhtml+xml') != 0) {
2155                $content_type = 'application/xhtml+xml';
2156        } else {
2157                $content_type = 'text/html';
2158        }
2159        print $cgi->header(-type=>$content_type, -charset => 'utf-8',
2160                           -status=> $status, -expires => $expires);
2161        my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
2162        print <<EOF;
2163<?xml version="1.0" encoding="utf-8"?>
2164<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2165<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
2166<!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
2167<!-- git core binaries version $git_version -->
2168<head>
2169<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
2170<meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
2171<meta name="robots" content="index, nofollow"/>
2172<title>$title</title>
2173EOF
2174# print out each stylesheet that exist
2175        if (defined $stylesheet) {
2176#provides backwards capability for those people who define style sheet in a config file
2177                print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2178        } else {
2179                foreach my $stylesheet (@stylesheets) {
2180                        next unless $stylesheet;
2181                        print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2182                }
2183        }
2184        if (defined $project) {
2185                printf('<link rel="alternate" title="%s log RSS feed" '.
2186                       'href="%s" type="application/rss+xml" />'."\n",
2187                       esc_param($project), href(action=>"rss"));
2188                printf('<link rel="alternate" title="%s log Atom feed" '.
2189                       'href="%s" type="application/atom+xml" />'."\n",
2190                       esc_param($project), href(action=>"atom"));
2191        } else {
2192                printf('<link rel="alternate" title="%s projects list" '.
2193                       'href="%s" type="text/plain; charset=utf-8"/>'."\n",
2194                       $site_name, href(project=>undef, action=>"project_index"));
2195                printf('<link rel="alternate" title="%s projects feeds" '.
2196                       'href="%s" type="text/x-opml"/>'."\n",
2197                       $site_name, href(project=>undef, action=>"opml"));
2198        }
2199        if (defined $favicon) {
2200                print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
2201        }
2202
2203        print "</head>\n" .
2204              "<body>\n";
2205
2206        if (-f $site_header) {
2207                open (my $fd, $site_header);
2208                print <$fd>;
2209                close $fd;
2210        }
2211
2212        print "<div class=\"page_header\">\n" .
2213              $cgi->a({-href => esc_url($logo_url),
2214                       -title => $logo_label},
2215                      qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
2216        print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
2217        if (defined $project) {
2218                print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
2219                if (defined $action) {
2220                        print " / $action";
2221                }
2222                print "\n";
2223        }
2224        print "</div>\n";
2225
2226        my ($have_search) = gitweb_check_feature('search');
2227        if ((defined $project) && ($have_search)) {
2228                if (!defined $searchtext) {
2229                        $searchtext = "";
2230                }
2231                my $search_hash;
2232                if (defined $hash_base) {
2233                        $search_hash = $hash_base;
2234                } elsif (defined $hash) {
2235                        $search_hash = $hash;
2236                } else {
2237                        $search_hash = "HEAD";
2238                }
2239                my $action = $my_uri;
2240                my ($use_pathinfo) = gitweb_check_feature('pathinfo');
2241                if ($use_pathinfo) {
2242                        $action .= "/$project";
2243                } else {
2244                        $cgi->param("p", $project);
2245                }
2246                $cgi->param("a", "search");
2247                $cgi->param("h", $search_hash);
2248                print $cgi->startform(-method => "get", -action => $action) .
2249                      "<div class=\"search\">\n" .
2250                      (!$use_pathinfo && $cgi->hidden(-name => "p") . "\n") .
2251                      $cgi->hidden(-name => "a") . "\n" .
2252                      $cgi->hidden(-name => "h") . "\n" .
2253                      $cgi->popup_menu(-name => 'st', -default => 'commit',
2254                                       -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
2255                      $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
2256                      " search:\n",
2257                      $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
2258                      "</div>" .
2259                      $cgi->end_form() . "\n";
2260        }
2261}
2262
2263sub git_footer_html {
2264        print "<div class=\"page_footer\">\n";
2265        if (defined $project) {
2266                my $descr = git_get_project_description($project);
2267                if (defined $descr) {
2268                        print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
2269                }
2270                print $cgi->a({-href => href(action=>"rss"),
2271                              -class => "rss_logo"}, "RSS") . " ";
2272                print $cgi->a({-href => href(action=>"atom"),
2273                              -class => "rss_logo"}, "Atom") . "\n";
2274        } else {
2275                print $cgi->a({-href => href(project=>undef, action=>"opml"),
2276                              -class => "rss_logo"}, "OPML") . " ";
2277                print $cgi->a({-href => href(project=>undef, action=>"project_index"),
2278                              -class => "rss_logo"}, "TXT") . "\n";
2279        }
2280        print "</div>\n" ;
2281
2282        if (-f $site_footer) {
2283                open (my $fd, $site_footer);
2284                print <$fd>;
2285                close $fd;
2286        }
2287
2288        print "</body>\n" .
2289              "</html>";
2290}
2291
2292sub die_error {
2293        my $status = shift || "403 Forbidden";
2294        my $error = shift || "Malformed query, file missing or permission denied";
2295
2296        git_header_html($status);
2297        print <<EOF;
2298<div class="page_body">
2299<br /><br />
2300$status - $error
2301<br />
2302</div>
2303EOF
2304        git_footer_html();
2305        exit;
2306}
2307
2308## ----------------------------------------------------------------------
2309## functions printing or outputting HTML: navigation
2310
2311sub git_print_page_nav {
2312        my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
2313        $extra = '' if !defined $extra; # pager or formats
2314
2315        my @navs = qw(summary shortlog log commit commitdiff tree);
2316        if ($suppress) {
2317                @navs = grep { $_ ne $suppress } @navs;
2318        }
2319
2320        my %arg = map { $_ => {action=>$_} } @navs;
2321        if (defined $head) {
2322                for (qw(commit commitdiff)) {
2323                        $arg{$_}{'hash'} = $head;
2324                }
2325                if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
2326                        for (qw(shortlog log)) {
2327                                $arg{$_}{'hash'} = $head;
2328                        }
2329                }
2330        }
2331        $arg{'tree'}{'hash'} = $treehead if defined $treehead;
2332        $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
2333
2334        print "<div class=\"page_nav\">\n" .
2335                (join " | ",
2336                 map { $_ eq $current ?
2337                       $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
2338                 } @navs);
2339        print "<br/>\n$extra<br/>\n" .
2340              "</div>\n";
2341}
2342
2343sub format_paging_nav {
2344        my ($action, $hash, $head, $page, $nrevs) = @_;
2345        my $paging_nav;
2346
2347
2348        if ($hash ne $head || $page) {
2349                $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
2350        } else {
2351                $paging_nav .= "HEAD";
2352        }
2353
2354        if ($page > 0) {
2355                $paging_nav .= " &sdot; " .
2356                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
2357                                 -accesskey => "p", -title => "Alt-p"}, "prev");
2358        } else {
2359                $paging_nav .= " &sdot; prev";
2360        }
2361
2362        if ($nrevs >= (100 * ($page+1)-1)) {
2363                $paging_nav .= " &sdot; " .
2364                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
2365                                 -accesskey => "n", -title => "Alt-n"}, "next");
2366        } else {
2367                $paging_nav .= " &sdot; next";
2368        }
2369
2370        return $paging_nav;
2371}
2372
2373## ......................................................................
2374## functions printing or outputting HTML: div
2375
2376sub git_print_header_div {
2377        my ($action, $title, $hash, $hash_base) = @_;
2378        my %args = ();
2379
2380        $args{'action'} = $action;
2381        $args{'hash'} = $hash if $hash;
2382        $args{'hash_base'} = $hash_base if $hash_base;
2383
2384        print "<div class=\"header\">\n" .
2385              $cgi->a({-href => href(%args), -class => "title"},
2386              $title ? $title : $action) .
2387              "\n</div>\n";
2388}
2389
2390#sub git_print_authorship (\%) {
2391sub git_print_authorship {
2392        my $co = shift;
2393
2394        my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
2395        print "<div class=\"author_date\">" .
2396              esc_html($co->{'author_name'}) .
2397              " [$ad{'rfc2822'}";
2398        if ($ad{'hour_local'} < 6) {
2399                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2400                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2401        } else {
2402                printf(" (%02d:%02d %s)",
2403                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2404        }
2405        print "]</div>\n";
2406}
2407
2408sub git_print_page_path {
2409        my $name = shift;
2410        my $type = shift;
2411        my $hb = shift;
2412
2413
2414        print "<div class=\"page_path\">";
2415        print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
2416                      -title => 'tree root'}, to_utf8("[$project]"));
2417        print " / ";
2418        if (defined $name) {
2419                my @dirname = split '/', $name;
2420                my $basename = pop @dirname;
2421                my $fullname = '';
2422
2423                foreach my $dir (@dirname) {
2424                        $fullname .= ($fullname ? '/' : '') . $dir;
2425                        print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
2426                                                     hash_base=>$hb),
2427                                      -title => $fullname}, esc_path($dir));
2428                        print " / ";
2429                }
2430                if (defined $type && $type eq 'blob') {
2431                        print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
2432                                                     hash_base=>$hb),
2433                                      -title => $name}, esc_path($basename));
2434                } elsif (defined $type && $type eq 'tree') {
2435                        print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
2436                                                     hash_base=>$hb),
2437                                      -title => $name}, esc_path($basename));
2438                        print " / ";
2439                } else {
2440                        print esc_path($basename);
2441                }
2442        }
2443        print "<br/></div>\n";
2444}
2445
2446# sub git_print_log (\@;%) {
2447sub git_print_log ($;%) {
2448        my $log = shift;
2449        my %opts = @_;
2450
2451        if ($opts{'-remove_title'}) {
2452                # remove title, i.e. first line of log
2453                shift @$log;
2454        }
2455        # remove leading empty lines
2456        while (defined $log->[0] && $log->[0] eq "") {
2457                shift @$log;
2458        }
2459
2460        # print log
2461        my $signoff = 0;
2462        my $empty = 0;
2463        foreach my $line (@$log) {
2464                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2465                        $signoff = 1;
2466                        $empty = 0;
2467                        if (! $opts{'-remove_signoff'}) {
2468                                print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
2469                                next;
2470                        } else {
2471                                # remove signoff lines
2472                                next;
2473                        }
2474                } else {
2475                        $signoff = 0;
2476                }
2477
2478                # print only one empty line
2479                # do not print empty line after signoff
2480                if ($line eq "") {
2481                        next if ($empty || $signoff);
2482                        $empty = 1;
2483                } else {
2484                        $empty = 0;
2485                }
2486
2487                print format_log_line_html($line) . "<br/>\n";
2488        }
2489
2490        if ($opts{'-final_empty_line'}) {
2491                # end with single empty line
2492                print "<br/>\n" unless $empty;
2493        }
2494}
2495
2496# return link target (what link points to)
2497sub git_get_link_target {
2498        my $hash = shift;
2499        my $link_target;
2500
2501        # read link
2502        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2503                or return;
2504        {
2505                local $/;
2506                $link_target = <$fd>;
2507        }
2508        close $fd
2509                or return;
2510
2511        return $link_target;
2512}
2513
2514# given link target, and the directory (basedir) the link is in,
2515# return target of link relative to top directory (top tree);
2516# return undef if it is not possible (including absolute links).
2517sub normalize_link_target {
2518        my ($link_target, $basedir, $hash_base) = @_;
2519
2520        # we can normalize symlink target only if $hash_base is provided
2521        return unless $hash_base;
2522
2523        # absolute symlinks (beginning with '/') cannot be normalized
2524        return if (substr($link_target, 0, 1) eq '/');
2525
2526        # normalize link target to path from top (root) tree (dir)
2527        my $path;
2528        if ($basedir) {
2529                $path = $basedir . '/' . $link_target;
2530        } else {
2531                # we are in top (root) tree (dir)
2532                $path = $link_target;
2533        }
2534
2535        # remove //, /./, and /../
2536        my @path_parts;
2537        foreach my $part (split('/', $path)) {
2538                # discard '.' and ''
2539                next if (!$part || $part eq '.');
2540                # handle '..'
2541                if ($part eq '..') {
2542                        if (@path_parts) {
2543                                pop @path_parts;
2544                        } else {
2545                                # link leads outside repository (outside top dir)
2546                                return;
2547                        }
2548                } else {
2549                        push @path_parts, $part;
2550                }
2551        }
2552        $path = join('/', @path_parts);
2553
2554        return $path;
2555}
2556
2557# print tree entry (row of git_tree), but without encompassing <tr> element
2558sub git_print_tree_entry {
2559        my ($t, $basedir, $hash_base, $have_blame) = @_;
2560
2561        my %base_key = ();
2562        $base_key{'hash_base'} = $hash_base if defined $hash_base;
2563
2564        # The format of a table row is: mode list link.  Where mode is
2565        # the mode of the entry, list is the name of the entry, an href,
2566        # and link is the action links of the entry.
2567
2568        print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
2569        if ($t->{'type'} eq "blob") {
2570                print "<td class=\"list\">" .
2571                        $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2572                                               file_name=>"$basedir$t->{'name'}", %base_key),
2573                                -class => "list"}, esc_path($t->{'name'}));
2574                if (S_ISLNK(oct $t->{'mode'})) {
2575                        my $link_target = git_get_link_target($t->{'hash'});
2576                        if ($link_target) {
2577                                my $norm_target = normalize_link_target($link_target, $basedir, $hash_base);
2578                                if (defined $norm_target) {
2579                                        print " -> " .
2580                                              $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
2581                                                                     file_name=>$norm_target),
2582                                                       -title => $norm_target}, esc_path($link_target));
2583                                } else {
2584                                        print " -> " . esc_path($link_target);
2585                                }
2586                        }
2587                }
2588                print "</td>\n";
2589                print "<td class=\"link\">";
2590                print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2591                                             file_name=>"$basedir$t->{'name'}", %base_key)},
2592                              "blob");
2593                if ($have_blame) {
2594                        print " | " .
2595                              $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
2596                                                     file_name=>"$basedir$t->{'name'}", %base_key)},
2597                                      "blame");
2598                }
2599                if (defined $hash_base) {
2600                        print " | " .
2601                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2602                                                     hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
2603                                      "history");
2604                }
2605                print " | " .
2606                        $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
2607                                               file_name=>"$basedir$t->{'name'}")},
2608                                "raw");
2609                print "</td>\n";
2610
2611        } elsif ($t->{'type'} eq "tree") {
2612                print "<td class=\"list\">";
2613                print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2614                                             file_name=>"$basedir$t->{'name'}", %base_key)},
2615                              esc_path($t->{'name'}));
2616                print "</td>\n";
2617                print "<td class=\"link\">";
2618                print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2619                                             file_name=>"$basedir$t->{'name'}", %base_key)},
2620                              "tree");
2621                if (defined $hash_base) {
2622                        print " | " .
2623                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2624                                                     file_name=>"$basedir$t->{'name'}")},
2625                                      "history");
2626                }
2627                print "</td>\n";
2628        }
2629}
2630
2631## ......................................................................
2632## functions printing large fragments of HTML
2633
2634sub fill_from_file_info {
2635        my ($diff, @parents) = @_;
2636
2637        $diff->{'from_file'} = [ ];
2638        $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
2639        for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
2640                if ($diff->{'status'}[$i] eq 'R' ||
2641                    $diff->{'status'}[$i] eq 'C') {
2642                        $diff->{'from_file'}[$i] =
2643                                git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
2644                }
2645        }
2646
2647        return $diff;
2648}
2649
2650# parameters can be strings, or references to arrays of strings
2651sub from_ids_eq {
2652        my ($a, $b) = @_;
2653
2654        if (ref($a) eq "ARRAY" && ref($b) eq "ARRAY" && @$a == @$b) {
2655                for (my $i = 0; $i < @$a; ++$i) {
2656                        return 0 unless ($a->[$i] eq $b->[$i]);
2657                }
2658                return 1;
2659        } elsif (!ref($a) && !ref($b)) {
2660                return $a eq $b;
2661        } else {
2662                return 0;
2663        }
2664}
2665
2666sub is_deleted {
2667        my $diffinfo = shift;
2668
2669        return $diffinfo->{'to_id'} eq ('0' x 40);
2670}
2671
2672sub git_difftree_body {
2673        my ($difftree, $hash, @parents) = @_;
2674        my ($parent) = $parents[0];
2675        my ($have_blame) = gitweb_check_feature('blame');
2676        print "<div class=\"list_head\">\n";
2677        if ($#{$difftree} > 10) {
2678                print(($#{$difftree} + 1) . " files changed:\n");
2679        }
2680        print "</div>\n";
2681
2682        print "<table class=\"" .
2683              (@parents > 1 ? "combined " : "") .
2684              "diff_tree\">\n";
2685
2686        # header only for combined diff in 'commitdiff' view
2687        my $has_header = @parents > 1 && $action eq 'commitdiff';
2688        if ($has_header) {
2689                # table header
2690                print "<thead><tr>\n" .
2691                       "<th></th><th></th>\n"; # filename, patchN link
2692                for (my $i = 0; $i < @parents; $i++) {
2693                        my $par = $parents[$i];
2694                        print "<th>" .
2695                              $cgi->a({-href => href(action=>"commitdiff",
2696                                                     hash=>$hash, hash_parent=>$par),
2697                                       -title => 'commitdiff to parent number ' .
2698                                                  ($i+1) . ': ' . substr($par,0,7)},
2699                                      $i+1) .
2700                              "&nbsp;</th>\n";
2701                }
2702                print "</tr></thead>\n<tbody>\n";
2703        }
2704
2705        my $alternate = 1;
2706        my $patchno = 0;
2707        foreach my $line (@{$difftree}) {
2708                my $diff;
2709                if (ref($line) eq "HASH") {
2710                        # pre-parsed (or generated by hand)
2711                        $diff = $line;
2712                } else {
2713                        $diff = parse_difftree_raw_line($line);
2714                }
2715
2716                if ($alternate) {
2717                        print "<tr class=\"dark\">\n";
2718                } else {
2719                        print "<tr class=\"light\">\n";
2720                }
2721                $alternate ^= 1;
2722
2723                if (exists $diff->{'nparents'}) { # combined diff
2724
2725                        fill_from_file_info($diff, @parents)
2726                                unless exists $diff->{'from_file'};
2727
2728                        if (!is_deleted($diff)) {
2729                                # file exists in the result (child) commit
2730                                print "<td>" .
2731                                      $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2732                                                             file_name=>$diff->{'to_file'},
2733                                                             hash_base=>$hash),
2734                                              -class => "list"}, esc_path($diff->{'to_file'})) .
2735                                      "</td>\n";
2736                        } else {
2737                                print "<td>" .
2738                                      esc_path($diff->{'to_file'}) .
2739                                      "</td>\n";
2740                        }
2741
2742                        if ($action eq 'commitdiff') {
2743                                # link to patch
2744                                $patchno++;
2745                                print "<td class=\"link\">" .
2746                                      $cgi->a({-href => "#patch$patchno"}, "patch") .
2747                                      " | " .
2748                                      "</td>\n";
2749                        }
2750
2751                        my $has_history = 0;
2752                        my $not_deleted = 0;
2753                        for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
2754                                my $hash_parent = $parents[$i];
2755                                my $from_hash = $diff->{'from_id'}[$i];
2756                                my $from_path = $diff->{'from_file'}[$i];
2757                                my $status = $diff->{'status'}[$i];
2758
2759                                $has_history ||= ($status ne 'A');
2760                                $not_deleted ||= ($status ne 'D');
2761
2762                                if ($status eq 'A') {
2763                                        print "<td  class=\"link\" align=\"right\"> | </td>\n";
2764                                } elsif ($status eq 'D') {
2765                                        print "<td class=\"link\">" .
2766                                              $cgi->a({-href => href(action=>"blob",
2767                                                                     hash_base=>$hash,
2768                                                                     hash=>$from_hash,
2769                                                                     file_name=>$from_path)},
2770                                                      "blob" . ($i+1)) .
2771                                              " | </td>\n";
2772                                } else {
2773                                        if ($diff->{'to_id'} eq $from_hash) {
2774                                                print "<td class=\"link nochange\">";
2775                                        } else {
2776                                                print "<td class=\"link\">";
2777                                        }
2778                                        print $cgi->a({-href => href(action=>"blobdiff",
2779                                                                     hash=>$diff->{'to_id'},
2780                                                                     hash_parent=>$from_hash,
2781                                                                     hash_base=>$hash,
2782                                                                     hash_parent_base=>$hash_parent,
2783                                                                     file_name=>$diff->{'to_file'},
2784                                                                     file_parent=>$from_path)},
2785                                                      "diff" . ($i+1)) .
2786                                              " | </td>\n";
2787                                }
2788                        }
2789
2790                        print "<td class=\"link\">";
2791                        if ($not_deleted) {
2792                                print $cgi->a({-href => href(action=>"blob",
2793                                                             hash=>$diff->{'to_id'},
2794                                                             file_name=>$diff->{'to_file'},
2795                                                             hash_base=>$hash)},
2796                                              "blob");
2797                                print " | " if ($has_history);
2798                        }
2799                        if ($has_history) {
2800                                print $cgi->a({-href => href(action=>"history",
2801                                                             file_name=>$diff->{'to_file'},
2802                                                             hash_base=>$hash)},
2803                                              "history");
2804                        }
2805                        print "</td>\n";
2806
2807                        print "</tr>\n";
2808                        next; # instead of 'else' clause, to avoid extra indent
2809                }
2810                # else ordinary diff
2811
2812                my ($to_mode_oct, $to_mode_str, $to_file_type);
2813                my ($from_mode_oct, $from_mode_str, $from_file_type);
2814                if ($diff->{'to_mode'} ne ('0' x 6)) {
2815                        $to_mode_oct = oct $diff->{'to_mode'};
2816                        if (S_ISREG($to_mode_oct)) { # only for regular file
2817                                $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
2818                        }
2819                        $to_file_type = file_type($diff->{'to_mode'});
2820                }
2821                if ($diff->{'from_mode'} ne ('0' x 6)) {
2822                        $from_mode_oct = oct $diff->{'from_mode'};
2823                        if (S_ISREG($to_mode_oct)) { # only for regular file
2824                                $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
2825                        }
2826                        $from_file_type = file_type($diff->{'from_mode'});
2827                }
2828
2829                if ($diff->{'status'} eq "A") { # created
2830                        my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
2831                        $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
2832                        $mode_chng   .= "]</span>";
2833                        print "<td>";
2834                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2835                                                     hash_base=>$hash, file_name=>$diff->{'file'}),
2836                                      -class => "list"}, esc_path($diff->{'file'}));
2837                        print "</td>\n";
2838                        print "<td>$mode_chng</td>\n";
2839                        print "<td class=\"link\">";
2840                        if ($action eq 'commitdiff') {
2841                                # link to patch
2842                                $patchno++;
2843                                print $cgi->a({-href => "#patch$patchno"}, "patch");
2844                                print " | ";
2845                        }
2846                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2847                                                     hash_base=>$hash, file_name=>$diff->{'file'})},
2848                                      "blob");
2849                        print "</td>\n";
2850
2851                } elsif ($diff->{'status'} eq "D") { # deleted
2852                        my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
2853                        print "<td>";
2854                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
2855                                                     hash_base=>$parent, file_name=>$diff->{'file'}),
2856                                       -class => "list"}, esc_path($diff->{'file'}));
2857                        print "</td>\n";
2858                        print "<td>$mode_chng</td>\n";
2859                        print "<td class=\"link\">";
2860                        if ($action eq 'commitdiff') {
2861                                # link to patch
2862                                $patchno++;
2863                                print $cgi->a({-href => "#patch$patchno"}, "patch");
2864                                print " | ";
2865                        }
2866                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
2867                                                     hash_base=>$parent, file_name=>$diff->{'file'})},
2868                                      "blob") . " | ";
2869                        if ($have_blame) {
2870                                print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
2871                                                             file_name=>$diff->{'file'})},
2872                                              "blame") . " | ";
2873                        }
2874                        print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
2875                                                     file_name=>$diff->{'file'})},
2876                                      "history");
2877                        print "</td>\n";
2878
2879                } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
2880                        my $mode_chnge = "";
2881                        if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
2882                                $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
2883                                if ($from_file_type ne $to_file_type) {
2884                                        $mode_chnge .= " from $from_file_type to $to_file_type";
2885                                }
2886                                if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
2887                                        if ($from_mode_str && $to_mode_str) {
2888                                                $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
2889                                        } elsif ($to_mode_str) {
2890                                                $mode_chnge .= " mode: $to_mode_str";
2891                                        }
2892                                }
2893                                $mode_chnge .= "]</span>\n";
2894                        }
2895                        print "<td>";
2896                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2897                                                     hash_base=>$hash, file_name=>$diff->{'file'}),
2898                                      -class => "list"}, esc_path($diff->{'file'}));
2899                        print "</td>\n";
2900                        print "<td>$mode_chnge</td>\n";
2901                        print "<td class=\"link\">";
2902                        if ($action eq 'commitdiff') {
2903                                # link to patch
2904                                $patchno++;
2905                                print $cgi->a({-href => "#patch$patchno"}, "patch") .
2906                                      " | ";
2907                        } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
2908                                # "commit" view and modified file (not onlu mode changed)
2909                                print $cgi->a({-href => href(action=>"blobdiff",
2910                                                             hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
2911                                                             hash_base=>$hash, hash_parent_base=>$parent,
2912                                                             file_name=>$diff->{'file'})},
2913                                              "diff") .
2914                                      " | ";
2915                        }
2916                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2917                                                     hash_base=>$hash, file_name=>$diff->{'file'})},
2918                                       "blob") . " | ";
2919                        if ($have_blame) {
2920                                print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
2921                                                             file_name=>$diff->{'file'})},
2922                                              "blame") . " | ";
2923                        }
2924                        print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
2925                                                     file_name=>$diff->{'file'})},
2926                                      "history");
2927                        print "</td>\n";
2928
2929                } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
2930                        my %status_name = ('R' => 'moved', 'C' => 'copied');
2931                        my $nstatus = $status_name{$diff->{'status'}};
2932                        my $mode_chng = "";
2933                        if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
2934                                # mode also for directories, so we cannot use $to_mode_str
2935                                $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
2936                        }
2937                        print "<td>" .
2938                              $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2939                                                     hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
2940                                      -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
2941                              "<td><span class=\"file_status $nstatus\">[$nstatus from " .
2942                              $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
2943                                                     hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
2944                                      -class => "list"}, esc_path($diff->{'from_file'})) .
2945                              " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
2946                              "<td class=\"link\">";
2947                        if ($action eq 'commitdiff') {
2948                                # link to patch
2949                                $patchno++;
2950                                print $cgi->a({-href => "#patch$patchno"}, "patch") .
2951                                      " | ";
2952                        } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
2953                                # "commit" view and modified file (not only pure rename or copy)
2954                                print $cgi->a({-href => href(action=>"blobdiff",
2955                                                             hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
2956                                                             hash_base=>$hash, hash_parent_base=>$parent,
2957                                                             file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
2958                                              "diff") .
2959                                      " | ";
2960                        }
2961                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2962                                                     hash_base=>$parent, file_name=>$diff->{'to_file'})},
2963                                      "blob") . " | ";
2964                        if ($have_blame) {
2965                                print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
2966                                                             file_name=>$diff->{'to_file'})},
2967                                              "blame") . " | ";
2968                        }
2969                        print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
2970                                                    file_name=>$diff->{'to_file'})},
2971                                      "history");
2972                        print "</td>\n";
2973
2974                } # we should not encounter Unmerged (U) or Unknown (X) status
2975                print "</tr>\n";
2976        }
2977        print "</tbody>" if $has_header;
2978        print "</table>\n";
2979}
2980
2981sub git_patchset_body {
2982        my ($fd, $difftree, $hash, @hash_parents) = @_;
2983        my ($hash_parent) = $hash_parents[0];
2984
2985        my $patch_idx = 0;
2986        my $patch_number = 0;
2987        my $patch_line;
2988        my $diffinfo;
2989        my (%from, %to);
2990
2991        print "<div class=\"patchset\">\n";
2992
2993        # skip to first patch
2994        while ($patch_line = <$fd>) {
2995                chomp $patch_line;
2996
2997                last if ($patch_line =~ m/^diff /);
2998        }
2999
3000 PATCH:
3001        while ($patch_line) {
3002                my @diff_header;
3003                my ($from_id, $to_id);
3004
3005                # git diff header
3006                #assert($patch_line =~ m/^diff /) if DEBUG;
3007                #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
3008                $patch_number++;
3009                push @diff_header, $patch_line;
3010
3011                # extended diff header
3012        EXTENDED_HEADER:
3013                while ($patch_line = <$fd>) {
3014                        chomp $patch_line;
3015
3016                        last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
3017
3018                        if ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
3019                                $from_id = $1;
3020                                $to_id   = $2;
3021                        } elsif ($patch_line =~ m/^index ((?:[0-9a-fA-F]{40},)+[0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
3022                                $from_id = [ split(',', $1) ];
3023                                $to_id   = $2;
3024                        }
3025
3026                        push @diff_header, $patch_line;
3027                }
3028                my $last_patch_line = $patch_line;
3029
3030                # check if current patch belong to current raw line
3031                # and parse raw git-diff line if needed
3032                if (defined $diffinfo &&
3033                    defined $from_id && defined $to_id &&
3034                    from_ids_eq($diffinfo->{'from_id'}, $from_id) &&
3035                    $diffinfo->{'to_id'} eq $to_id) {
3036                        # this is continuation of a split patch
3037                        print "<div class=\"patch cont\">\n";
3038                } else {
3039                        # advance raw git-diff output if needed
3040                        $patch_idx++ if defined $diffinfo;
3041
3042                        # compact combined diff output can have some patches skipped
3043                        # find which patch (using pathname of result) we are at now
3044                        my $to_name;
3045                        if ($diff_header[0] =~ m!^diff --cc "?(.*)"?$!) {
3046                                $to_name = $1;
3047                        }
3048
3049                        do {
3050                                # read and prepare patch information
3051                                if (ref($difftree->[$patch_idx]) eq "HASH") {
3052                                        # pre-parsed (or generated by hand)
3053                                        $diffinfo = $difftree->[$patch_idx];
3054                                } else {
3055                                        $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
3056                                }
3057
3058                                # check if current raw line has no patch (it got simplified)
3059                                if (defined $to_name && $to_name ne $diffinfo->{'to_file'}) {
3060                                        print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3061                                              format_diff_cc_simplified($diffinfo, @hash_parents) .
3062                                              "</div>\n";  # class="patch"
3063
3064                                        $patch_idx++;
3065                                        $patch_number++;
3066                                }
3067                        } until (!defined $to_name || $to_name eq $diffinfo->{'to_file'} ||
3068                                 $patch_idx > $#$difftree);
3069                        # modifies %from, %to hashes
3070                        parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
3071                        if ($diffinfo->{'nparents'}) {
3072                                # combined diff
3073                                $from{'file'} = [];
3074                                $from{'href'} = [];
3075                                fill_from_file_info($diffinfo, @hash_parents)
3076                                        unless exists $diffinfo->{'from_file'};
3077                                for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3078                                        $from{'file'}[$i] = $diffinfo->{'from_file'}[$i] || $diffinfo->{'to_file'};
3079                                        if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3080                                                $from{'href'}[$i] = href(action=>"blob",
3081                                                                         hash_base=>$hash_parents[$i],
3082                                                                         hash=>$diffinfo->{'from_id'}[$i],
3083                                                                         file_name=>$from{'file'}[$i]);
3084                                        } else {
3085                                                $from{'href'}[$i] = undef;
3086                                        }
3087                                }
3088                        } else {
3089                                $from{'file'} = $diffinfo->{'from_file'} || $diffinfo->{'file'};
3090                                if ($diffinfo->{'status'} ne "A") { # not new (added) file
3091                                        $from{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3092                                                             hash=>$diffinfo->{'from_id'},
3093                                                             file_name=>$from{'file'});
3094                                } else {
3095                                        delete $from{'href'};
3096                                }
3097                        }
3098
3099                        $to{'file'} = $diffinfo->{'to_file'} || $diffinfo->{'file'};
3100                        if (!is_deleted($diffinfo)) { # file exists in result
3101                                $to{'href'} = href(action=>"blob", hash_base=>$hash,
3102                                                   hash=>$diffinfo->{'to_id'},
3103                                                   file_name=>$to{'file'});
3104                        } else {
3105                                delete $to{'href'};
3106                        }
3107                        # this is first patch for raw difftree line with $patch_idx index
3108                        # we index @$difftree array from 0, but number patches from 1
3109                        print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
3110                }
3111
3112                # print "git diff" header
3113                $patch_line = shift @diff_header;
3114                print format_git_diff_header_line($patch_line, $diffinfo,
3115                                                  \%from, \%to);
3116
3117                # print extended diff header
3118                print "<div class=\"diff extended_header\">\n" if (@diff_header > 0);
3119        EXTENDED_HEADER:
3120                foreach $patch_line (@diff_header) {
3121                        print format_extended_diff_header_line($patch_line, $diffinfo,
3122                                                               \%from, \%to);
3123                }
3124                print "</div>\n"  if (@diff_header > 0); # class="diff extended_header"
3125
3126                # from-file/to-file diff header
3127                $patch_line = $last_patch_line;
3128                if (! $patch_line) {
3129                        print "</div>\n"; # class="patch"
3130                        last PATCH;
3131                }
3132                next PATCH if ($patch_line =~ m/^diff /);
3133                #assert($patch_line =~ m/^---/) if DEBUG;
3134                #assert($patch_line eq $last_patch_line) if DEBUG;
3135
3136                $patch_line = <$fd>;
3137                chomp $patch_line;
3138                #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
3139
3140                print format_diff_from_to_header($last_patch_line, $patch_line,
3141                                                 $diffinfo, \%from, \%to,
3142                                                 @hash_parents);
3143
3144                # the patch itself
3145        LINE:
3146                while ($patch_line = <$fd>) {
3147                        chomp $patch_line;
3148
3149                        next PATCH if ($patch_line =~ m/^diff /);
3150
3151                        print format_diff_line($patch_line, \%from, \%to);
3152                }
3153
3154        } continue {
3155                print "</div>\n"; # class="patch"
3156        }
3157
3158        # for compact combined (--cc) format, with chunk and patch simpliciaction
3159        # patchset might be empty, but there might be unprocessed raw lines
3160        for ($patch_idx++ if $patch_number > 0;
3161             $patch_idx < @$difftree;
3162             $patch_idx++) {
3163                # read and prepare patch information
3164                if (ref($difftree->[$patch_idx]) eq "HASH") {
3165                        # pre-parsed (or generated by hand)
3166                        $diffinfo = $difftree->[$patch_idx];
3167                } else {
3168                        $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
3169                }
3170
3171                # generate anchor for "patch" links in difftree / whatchanged part
3172                print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3173                      format_diff_cc_simplified($diffinfo, @hash_parents) .
3174                      "</div>\n";  # class="patch"
3175
3176                $patch_number++;
3177        }
3178
3179        if ($patch_number == 0) {
3180                if (@hash_parents > 1) {
3181                        print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
3182                } else {
3183                        print "<div class=\"diff nodifferences\">No differences found</div>\n";
3184                }
3185        }
3186
3187        print "</div>\n"; # class="patchset"
3188}
3189
3190# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3191
3192sub git_project_list_body {
3193        my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
3194
3195        my ($check_forks) = gitweb_check_feature('forks');
3196
3197        my @projects;
3198        foreach my $pr (@$projlist) {
3199                my (@aa) = git_get_last_activity($pr->{'path'});
3200                unless (@aa) {
3201                        next;
3202                }
3203                ($pr->{'age'}, $pr->{'age_string'}) = @aa;
3204                if (!defined $pr->{'descr'}) {
3205                        my $descr = git_get_project_description($pr->{'path'}) || "";
3206                        $pr->{'descr_long'} = to_utf8($descr);
3207                        $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
3208                }
3209                if (!defined $pr->{'owner'}) {
3210                        $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
3211                }
3212                if ($check_forks) {
3213                        my $pname = $pr->{'path'};
3214                        if (($pname =~ s/\.git$//) &&
3215                            ($pname !~ /\/$/) &&
3216                            (-d "$projectroot/$pname")) {
3217                                $pr->{'forks'} = "-d $projectroot/$pname";
3218                        }
3219                        else {
3220                                $pr->{'forks'} = 0;
3221                        }
3222                }
3223                push @projects, $pr;
3224        }
3225
3226        $order ||= $default_projects_order;
3227        $from = 0 unless defined $from;
3228        $to = $#projects if (!defined $to || $#projects < $to);
3229
3230        print "<table class=\"project_list\">\n";
3231        unless ($no_header) {
3232                print "<tr>\n";
3233                if ($check_forks) {
3234                        print "<th></th>\n";
3235                }
3236                if ($order eq "project") {
3237                        @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
3238                        print "<th>Project</th>\n";
3239                } else {
3240                        print "<th>" .
3241                              $cgi->a({-href => href(project=>undef, order=>'project'),
3242                                       -class => "header"}, "Project") .
3243                              "</th>\n";
3244                }
3245                if ($order eq "descr") {
3246                        @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
3247                        print "<th>Description</th>\n";
3248                } else {
3249                        print "<th>" .
3250                              $cgi->a({-href => href(project=>undef, order=>'descr'),
3251                                       -class => "header"}, "Description") .
3252                              "</th>\n";
3253                }
3254                if ($order eq "owner") {
3255                        @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
3256                        print "<th>Owner</th>\n";
3257                } else {
3258                        print "<th>" .
3259                              $cgi->a({-href => href(project=>undef, order=>'owner'),
3260                                       -class => "header"}, "Owner") .
3261                              "</th>\n";
3262                }
3263                if ($order eq "age") {
3264                        @projects = sort {$a->{'age'} <=> $b->{'age'}} @projects;
3265                        print "<th>Last Change</th>\n";
3266                } else {
3267                        print "<th>" .
3268                              $cgi->a({-href => href(project=>undef, order=>'age'),
3269                                       -class => "header"}, "Last Change") .
3270                              "</th>\n";
3271                }
3272                print "<th></th>\n" .
3273                      "</tr>\n";
3274        }
3275        my $alternate = 1;
3276        for (my $i = $from; $i <= $to; $i++) {
3277                my $pr = $projects[$i];
3278                if ($alternate) {
3279                        print "<tr class=\"dark\">\n";
3280                } else {
3281                        print "<tr class=\"light\">\n";
3282                }
3283                $alternate ^= 1;
3284                if ($check_forks) {
3285                        print "<td>";
3286                        if ($pr->{'forks'}) {
3287                                print "<!-- $pr->{'forks'} -->\n";
3288                                print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
3289                        }
3290                        print "</td>\n";
3291                }
3292                print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3293                                        -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
3294                      "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3295                                        -class => "list", -title => $pr->{'descr_long'}},
3296                                        esc_html($pr->{'descr'})) . "</td>\n" .
3297                      "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
3298                print "<td class=\"". age_class($pr->{'age'}) . "\">" .
3299                      (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
3300                      "<td class=\"link\">" .
3301                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
3302                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
3303                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
3304                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
3305                      ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
3306                      "</td>\n" .
3307                      "</tr>\n";
3308        }
3309        if (defined $extra) {
3310                print "<tr>\n";
3311                if ($check_forks) {
3312                        print "<td></td>\n";
3313                }
3314                print "<td colspan=\"5\">$extra</td>\n" .
3315                      "</tr>\n";
3316        }
3317        print "</table>\n";
3318}
3319
3320sub git_shortlog_body {
3321        # uses global variable $project
3322        my ($commitlist, $from, $to, $refs, $extra) = @_;
3323
3324        my $have_snapshot = gitweb_have_snapshot();
3325
3326        $from = 0 unless defined $from;
3327        $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3328
3329        print "<table class=\"shortlog\" cellspacing=\"0\">\n";
3330        my $alternate = 1;
3331        for (my $i = $from; $i <= $to; $i++) {
3332                my %co = %{$commitlist->[$i]};
3333                my $commit = $co{'id'};
3334                my $ref = format_ref_marker($refs, $commit);
3335                if ($alternate) {
3336                        print "<tr class=\"dark\">\n";
3337                } else {
3338                        print "<tr class=\"light\">\n";
3339                }
3340                $alternate ^= 1;
3341                # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
3342                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3343                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
3344                      "<td>";
3345                print format_subject_html($co{'title'}, $co{'title_short'},
3346                                          href(action=>"commit", hash=>$commit), $ref);
3347                print "</td>\n" .
3348                      "<td class=\"link\">" .
3349                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
3350                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
3351                      $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
3352                if ($have_snapshot) {
3353                        print " | " . $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
3354                }
3355                print "</td>\n" .
3356                      "</tr>\n";
3357        }
3358        if (defined $extra) {
3359                print "<tr>\n" .
3360                      "<td colspan=\"4\">$extra</td>\n" .
3361                      "</tr>\n";
3362        }
3363        print "</table>\n";
3364}
3365
3366sub git_history_body {
3367        # Warning: assumes constant type (blob or tree) during history
3368        my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
3369
3370        $from = 0 unless defined $from;
3371        $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
3372
3373        print "<table class=\"history\" cellspacing=\"0\">\n";
3374        my $alternate = 1;
3375        for (my $i = $from; $i <= $to; $i++) {
3376                my %co = %{$commitlist->[$i]};
3377                if (!%co) {
3378                        next;
3379                }
3380                my $commit = $co{'id'};
3381
3382                my $ref = format_ref_marker($refs, $commit);
3383
3384                if ($alternate) {
3385                        print "<tr class=\"dark\">\n";
3386                } else {
3387                        print "<tr class=\"light\">\n";
3388                }
3389                $alternate ^= 1;
3390                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3391                      # shortlog uses      chop_str($co{'author_name'}, 10)
3392                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
3393                      "<td>";
3394                # originally git_history used chop_str($co{'title'}, 50)
3395                print format_subject_html($co{'title'}, $co{'title_short'},
3396                                          href(action=>"commit", hash=>$commit), $ref);
3397                print "</td>\n" .
3398                      "<td class=\"link\">" .
3399                      $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
3400                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
3401
3402                if ($ftype eq 'blob') {
3403                        my $blob_current = git_get_hash_by_path($hash_base, $file_name);
3404                        my $blob_parent  = git_get_hash_by_path($commit, $file_name);
3405                        if (defined $blob_current && defined $blob_parent &&
3406                                        $blob_current ne $blob_parent) {
3407                                print " | " .
3408                                        $cgi->a({-href => href(action=>"blobdiff",
3409                                                               hash=>$blob_current, hash_parent=>$blob_parent,
3410                                                               hash_base=>$hash_base, hash_parent_base=>$commit,
3411                                                               file_name=>$file_name)},
3412                                                "diff to current");
3413                        }
3414                }
3415                print "</td>\n" .
3416                      "</tr>\n";
3417        }
3418        if (defined $extra) {
3419                print "<tr>\n" .
3420                      "<td colspan=\"4\">$extra</td>\n" .
3421                      "</tr>\n";
3422        }
3423        print "</table>\n";
3424}
3425
3426sub git_tags_body {
3427        # uses global variable $project
3428        my ($taglist, $from, $to, $extra) = @_;
3429        $from = 0 unless defined $from;
3430        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
3431
3432        print "<table class=\"tags\" cellspacing=\"0\">\n";
3433        my $alternate = 1;
3434        for (my $i = $from; $i <= $to; $i++) {
3435                my $entry = $taglist->[$i];
3436                my %tag = %$entry;
3437                my $comment = $tag{'subject'};
3438                my $comment_short;
3439                if (defined $comment) {
3440                        $comment_short = chop_str($comment, 30, 5);
3441                }
3442                if ($alternate) {
3443                        print "<tr class=\"dark\">\n";
3444                } else {
3445                        print "<tr class=\"light\">\n";
3446                }
3447                $alternate ^= 1;
3448                if (defined $tag{'age'}) {
3449                        print "<td><i>$tag{'age'}</i></td>\n";
3450                } else {
3451                        print "<td></td>\n";
3452                }
3453                print "<td>" .
3454                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
3455                               -class => "list name"}, esc_html($tag{'name'})) .
3456                      "</td>\n" .
3457                      "<td>";
3458                if (defined $comment) {
3459                        print format_subject_html($comment, $comment_short,
3460                                                  href(action=>"tag", hash=>$tag{'id'}));
3461                }
3462                print "</td>\n" .
3463                      "<td class=\"selflink\">";
3464                if ($tag{'type'} eq "tag") {
3465                        print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
3466                } else {
3467                        print "&nbsp;";
3468                }
3469                print "</td>\n" .
3470                      "<td class=\"link\">" . " | " .
3471                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
3472                if ($tag{'reftype'} eq "commit") {
3473                        print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
3474                              " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log");
3475                } elsif ($tag{'reftype'} eq "blob") {
3476                        print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
3477                }
3478                print "</td>\n" .
3479                      "</tr>";
3480        }
3481        if (defined $extra) {
3482                print "<tr>\n" .
3483                      "<td colspan=\"5\">$extra</td>\n" .
3484                      "</tr>\n";
3485        }
3486        print "</table>\n";
3487}
3488
3489sub git_heads_body {
3490        # uses global variable $project
3491        my ($headlist, $head, $from, $to, $extra) = @_;
3492        $from = 0 unless defined $from;
3493        $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
3494
3495        print "<table class=\"heads\" cellspacing=\"0\">\n";
3496        my $alternate = 1;
3497        for (my $i = $from; $i <= $to; $i++) {
3498                my $entry = $headlist->[$i];
3499                my %ref = %$entry;
3500                my $curr = $ref{'id'} eq $head;
3501                if ($alternate) {
3502                        print "<tr class=\"dark\">\n";
3503                } else {
3504                        print "<tr class=\"light\">\n";
3505                }
3506                $alternate ^= 1;
3507                print "<td><i>$ref{'age'}</i></td>\n" .
3508                      ($curr ? "<td class=\"current_head\">" : "<td>") .
3509                      $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'}),
3510                               -class => "list name"},esc_html($ref{'name'})) .
3511                      "</td>\n" .
3512                      "<td class=\"link\">" .
3513                      $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'})}, "shortlog") . " | " .
3514                      $cgi->a({-href => href(action=>"log", hash=>$ref{'name'})}, "log") . " | " .
3515                      $cgi->a({-href => href(action=>"tree", hash=>$ref{'name'}, hash_base=>$ref{'name'})}, "tree") .
3516                      "</td>\n" .
3517                      "</tr>";
3518        }
3519        if (defined $extra) {
3520                print "<tr>\n" .
3521                      "<td colspan=\"3\">$extra</td>\n" .
3522                      "</tr>\n";
3523        }
3524        print "</table>\n";
3525}
3526
3527sub git_search_grep_body {
3528        my ($commitlist, $from, $to, $extra) = @_;
3529        $from = 0 unless defined $from;
3530        $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3531
3532        print "<table class=\"grep\" cellspacing=\"0\">\n";
3533        my $alternate = 1;
3534        for (my $i = $from; $i <= $to; $i++) {
3535                my %co = %{$commitlist->[$i]};
3536                if (!%co) {
3537                        next;
3538                }
3539                my $commit = $co{'id'};
3540                if ($alternate) {
3541                        print "<tr class=\"dark\">\n";
3542                } else {
3543                        print "<tr class=\"light\">\n";
3544                }
3545                $alternate ^= 1;
3546                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3547                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3548                      "<td>" .
3549                      $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3550                               esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3551                my $comment = $co{'comment'};
3552                foreach my $line (@$comment) {
3553                        if ($line =~ m/^(.*)($search_regexp)(.*)$/i) {
3554                                my $lead = esc_html($1) || "";
3555                                $lead = chop_str($lead, 30, 10);
3556                                my $match = esc_html($2) || "";
3557                                my $trail = esc_html($3) || "";
3558                                $trail = chop_str($trail, 30, 10);
3559                                my $text = "$lead<span class=\"match\">$match</span>$trail";
3560                                print chop_str($text, 80, 5) . "<br/>\n";
3561                        }
3562                }
3563                print "</td>\n" .
3564                      "<td class=\"link\">" .
3565                      $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3566                      " | " .
3567                      $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3568                print "</td>\n" .
3569                      "</tr>\n";
3570        }
3571        if (defined $extra) {
3572                print "<tr>\n" .
3573                      "<td colspan=\"3\">$extra</td>\n" .
3574                      "</tr>\n";
3575        }
3576        print "</table>\n";
3577}
3578
3579## ======================================================================
3580## ======================================================================
3581## actions
3582
3583sub git_project_list {
3584        my $order = $cgi->param('o');
3585        if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3586                die_error(undef, "Unknown order parameter");
3587        }
3588
3589        my @list = git_get_projects_list();
3590        if (!@list) {
3591                die_error(undef, "No projects found");
3592        }
3593
3594        git_header_html();
3595        if (-f $home_text) {
3596                print "<div class=\"index_include\">\n";
3597                open (my $fd, $home_text);
3598                print <$fd>;
3599                close $fd;
3600                print "</div>\n";
3601        }
3602        git_project_list_body(\@list, $order);
3603        git_footer_html();
3604}
3605
3606sub git_forks {
3607        my $order = $cgi->param('o');
3608        if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3609                die_error(undef, "Unknown order parameter");
3610        }
3611
3612        my @list = git_get_projects_list($project);
3613        if (!@list) {
3614                die_error(undef, "No forks found");
3615        }
3616
3617        git_header_html();
3618        git_print_page_nav('','');
3619        git_print_header_div('summary', "$project forks");
3620        git_project_list_body(\@list, $order);
3621        git_footer_html();
3622}
3623
3624sub git_project_index {
3625        my @projects = git_get_projects_list($project);
3626
3627        print $cgi->header(
3628                -type => 'text/plain',
3629                -charset => 'utf-8',
3630                -content_disposition => 'inline; filename="index.aux"');
3631
3632        foreach my $pr (@projects) {
3633                if (!exists $pr->{'owner'}) {
3634                        $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
3635                }
3636
3637                my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
3638                # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
3639                $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3640                $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3641                $path  =~ s/ /\+/g;
3642                $owner =~ s/ /\+/g;
3643
3644                print "$path $owner\n";
3645        }
3646}
3647
3648sub git_summary {
3649        my $descr = git_get_project_description($project) || "none";
3650        my %co = parse_commit("HEAD");
3651        my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
3652        my $head = $co{'id'};
3653
3654        my $owner = git_get_project_owner($project);
3655
3656        my $refs = git_get_references();
3657        # These get_*_list functions return one more to allow us to see if
3658        # there are more ...
3659        my @taglist  = git_get_tags_list(16);
3660        my @headlist = git_get_heads_list(16);
3661        my @forklist;
3662        my ($check_forks) = gitweb_check_feature('forks');
3663
3664        if ($check_forks) {
3665                @forklist = git_get_projects_list($project);
3666        }
3667
3668        git_header_html();
3669        git_print_page_nav('summary','', $head);
3670
3671        print "<div class=\"title\">&nbsp;</div>\n";
3672        print "<table cellspacing=\"0\">\n" .
3673              "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
3674              "<tr><td>owner</td><td>$owner</td></tr>\n";
3675        if (defined $cd{'rfc2822'}) {
3676                print "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
3677        }
3678
3679        # use per project git URL list in $projectroot/$project/cloneurl
3680        # or make project git URL from git base URL and project name
3681        my $url_tag = "URL";
3682        my @url_list = git_get_project_url_list($project);
3683        @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
3684        foreach my $git_url (@url_list) {
3685                next unless $git_url;
3686                print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
3687                $url_tag = "";
3688        }
3689        print "</table>\n";
3690
3691        if (-s "$projectroot/$project/README.html") {
3692                if (open my $fd, "$projectroot/$project/README.html") {
3693                        print "<div class=\"title\">readme</div>\n";
3694                        print $_ while (<$fd>);
3695                        close $fd;
3696                }
3697        }
3698
3699        # we need to request one more than 16 (0..15) to check if
3700        # those 16 are all
3701        my @commitlist = $head ? parse_commits($head, 17) : ();
3702        if (@commitlist) {
3703                git_print_header_div('shortlog');
3704                git_shortlog_body(\@commitlist, 0, 15, $refs,
3705                                  $#commitlist <=  15 ? undef :
3706                                  $cgi->a({-href => href(action=>"shortlog")}, "..."));
3707        }
3708
3709        if (@taglist) {
3710                git_print_header_div('tags');
3711                git_tags_body(\@taglist, 0, 15,
3712                              $#taglist <=  15 ? undef :
3713                              $cgi->a({-href => href(action=>"tags")}, "..."));
3714        }
3715
3716        if (@headlist) {
3717                git_print_header_div('heads');
3718                git_heads_body(\@headlist, $head, 0, 15,
3719                               $#headlist <= 15 ? undef :
3720                               $cgi->a({-href => href(action=>"heads")}, "..."));
3721        }
3722
3723        if (@forklist) {
3724                git_print_header_div('forks');
3725                git_project_list_body(\@forklist, undef, 0, 15,
3726                                      $#forklist <= 15 ? undef :
3727                                      $cgi->a({-href => href(action=>"forks")}, "..."),
3728                                      'noheader');
3729        }
3730
3731        git_footer_html();
3732}
3733
3734sub git_tag {
3735        my $head = git_get_head_hash($project);
3736        git_header_html();
3737        git_print_page_nav('','', $head,undef,$head);
3738        my %tag = parse_tag($hash);
3739
3740        if (! %tag) {
3741                die_error(undef, "Unknown tag object");
3742        }
3743
3744        git_print_header_div('commit', esc_html($tag{'name'}), $hash);
3745        print "<div class=\"title_text\">\n" .
3746              "<table cellspacing=\"0\">\n" .
3747              "<tr>\n" .
3748              "<td>object</td>\n" .
3749              "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3750                               $tag{'object'}) . "</td>\n" .
3751              "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3752                                              $tag{'type'}) . "</td>\n" .
3753              "</tr>\n";
3754        if (defined($tag{'author'})) {
3755                my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
3756                print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
3757                print "<tr><td></td><td>" . $ad{'rfc2822'} .
3758                        sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
3759                        "</td></tr>\n";
3760        }
3761        print "</table>\n\n" .
3762              "</div>\n";
3763        print "<div class=\"page_body\">";
3764        my $comment = $tag{'comment'};
3765        foreach my $line (@$comment) {
3766                chomp $line;
3767                print esc_html($line, -nbsp=>1) . "<br/>\n";
3768        }
3769        print "</div>\n";
3770        git_footer_html();
3771}
3772
3773sub git_blame2 {
3774        my $fd;
3775        my $ftype;
3776
3777        my ($have_blame) = gitweb_check_feature('blame');
3778        if (!$have_blame) {
3779                die_error('403 Permission denied', "Permission denied");
3780        }
3781        die_error('404 Not Found', "File name not defined") if (!$file_name);
3782        $hash_base ||= git_get_head_hash($project);
3783        die_error(undef, "Couldn't find base commit") unless ($hash_base);
3784        my %co = parse_commit($hash_base)
3785                or die_error(undef, "Reading commit failed");
3786        if (!defined $hash) {
3787                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3788                        or die_error(undef, "Error looking up file");
3789        }
3790        $ftype = git_get_type($hash);
3791        if ($ftype !~ "blob") {
3792                die_error('400 Bad Request', "Object is not a blob");
3793        }
3794        open ($fd, "-|", git_cmd(), "blame", '-p', '--',
3795              $file_name, $hash_base)
3796                or die_error(undef, "Open git-blame failed");
3797        git_header_html();
3798        my $formats_nav =
3799                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3800                        "blob") .
3801                " | " .
3802                $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3803                        "history") .
3804                " | " .
3805                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3806                        "HEAD");
3807        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3808        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3809        git_print_page_path($file_name, $ftype, $hash_base);
3810        my @rev_color = (qw(light2 dark2));
3811        my $num_colors = scalar(@rev_color);
3812        my $current_color = 0;
3813        my $last_rev;
3814        print <<HTML;
3815<div class="page_body">
3816<table class="blame">
3817<tr><th>Commit</th><th>Line</th><th>Data</th></tr>
3818HTML
3819        my %metainfo = ();
3820        while (1) {
3821                $_ = <$fd>;
3822                last unless defined $_;
3823                my ($full_rev, $orig_lineno, $lineno, $group_size) =
3824                    /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
3825                if (!exists $metainfo{$full_rev}) {
3826                        $metainfo{$full_rev} = {};
3827                }
3828                my $meta = $metainfo{$full_rev};
3829                while (<$fd>) {
3830                        last if (s/^\t//);
3831                        if (/^(\S+) (.*)$/) {
3832                                $meta->{$1} = $2;
3833                        }
3834                }
3835                my $data = $_;
3836                chomp $data;
3837                my $rev = substr($full_rev, 0, 8);
3838                my $author = $meta->{'author'};
3839                my %date = parse_date($meta->{'author-time'},
3840                                      $meta->{'author-tz'});
3841                my $date = $date{'iso-tz'};
3842                if ($group_size) {
3843                        $current_color = ++$current_color % $num_colors;
3844                }
3845                print "<tr class=\"$rev_color[$current_color]\">\n";
3846                if ($group_size) {
3847                        print "<td class=\"sha1\"";
3848                        print " title=\"". esc_html($author) . ", $date\"";
3849                        print " rowspan=\"$group_size\"" if ($group_size > 1);
3850                        print ">";
3851                        print $cgi->a({-href => href(action=>"commit",
3852                                                     hash=>$full_rev,
3853                                                     file_name=>$file_name)},
3854                                      esc_html($rev));
3855                        print "</td>\n";
3856                }
3857                open (my $dd, "-|", git_cmd(), "rev-parse", "$full_rev^")
3858                        or die_error(undef, "Open git-rev-parse failed");
3859                my $parent_commit = <$dd>;
3860                close $dd;
3861                chomp($parent_commit);
3862                my $blamed = href(action => 'blame',
3863                                  file_name => $meta->{'filename'},
3864                                  hash_base => $parent_commit);
3865                print "<td class=\"linenr\">";
3866                print $cgi->a({ -href => "$blamed#l$orig_lineno",
3867                                -id => "l$lineno",
3868                                -class => "linenr" },
3869                              esc_html($lineno));
3870                print "</td>";
3871                print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
3872                print "</tr>\n";
3873        }
3874        print "</table>\n";
3875        print "</div>";
3876        close $fd
3877                or print "Reading blob failed\n";
3878        git_footer_html();
3879}
3880
3881sub git_blame {
3882        my $fd;
3883
3884        my ($have_blame) = gitweb_check_feature('blame');
3885        if (!$have_blame) {
3886                die_error('403 Permission denied', "Permission denied");
3887        }
3888        die_error('404 Not Found', "File name not defined") if (!$file_name);
3889        $hash_base ||= git_get_head_hash($project);
3890        die_error(undef, "Couldn't find base commit") unless ($hash_base);
3891        my %co = parse_commit($hash_base)
3892                or die_error(undef, "Reading commit failed");
3893        if (!defined $hash) {
3894                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3895                        or die_error(undef, "Error lookup file");
3896        }
3897        open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
3898                or die_error(undef, "Open git-annotate failed");
3899        git_header_html();
3900        my $formats_nav =
3901                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3902                        "blob") .
3903                " | " .
3904                $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3905                        "history") .
3906                " | " .
3907                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3908                        "HEAD");
3909        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3910        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3911        git_print_page_path($file_name, 'blob', $hash_base);
3912        print "<div class=\"page_body\">\n";
3913        print <<HTML;
3914<table class="blame">
3915  <tr>
3916    <th>Commit</th>
3917    <th>Age</th>
3918    <th>Author</th>
3919    <th>Line</th>
3920    <th>Data</th>
3921  </tr>
3922HTML
3923        my @line_class = (qw(light dark));
3924        my $line_class_len = scalar (@line_class);
3925        my $line_class_num = $#line_class;
3926        while (my $line = <$fd>) {
3927                my $long_rev;
3928                my $short_rev;
3929                my $author;
3930                my $time;
3931                my $lineno;
3932                my $data;
3933                my $age;
3934                my $age_str;
3935                my $age_class;
3936
3937                chomp $line;
3938                $line_class_num = ($line_class_num + 1) % $line_class_len;
3939
3940                if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
3941                        $long_rev = $1;
3942                        $author   = $2;
3943                        $time     = $3;
3944                        $lineno   = $4;
3945                        $data     = $5;
3946                } else {
3947                        print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
3948                        next;
3949                }
3950                $short_rev  = substr ($long_rev, 0, 8);
3951                $age        = time () - $time;
3952                $age_str    = age_string ($age);
3953                $age_str    =~ s/ /&nbsp;/g;
3954                $age_class  = age_class($age);
3955                $author     = esc_html ($author);
3956                $author     =~ s/ /&nbsp;/g;
3957
3958                $data = untabify($data);
3959                $data = esc_html ($data);
3960
3961                print <<HTML;
3962  <tr class="$line_class[$line_class_num]">
3963    <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
3964    <td class="$age_class">$age_str</td>
3965    <td>$author</td>
3966    <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
3967    <td class="pre">$data</td>
3968  </tr>
3969HTML
3970        } # while (my $line = <$fd>)
3971        print "</table>\n\n";
3972        close $fd
3973                or print "Reading blob failed.\n";
3974        print "</div>";
3975        git_footer_html();
3976}
3977
3978sub git_tags {
3979        my $head = git_get_head_hash($project);
3980        git_header_html();
3981        git_print_page_nav('','', $head,undef,$head);
3982        git_print_header_div('summary', $project);
3983
3984        my @tagslist = git_get_tags_list();
3985        if (@tagslist) {
3986                git_tags_body(\@tagslist);
3987        }
3988        git_footer_html();
3989}
3990
3991sub git_heads {
3992        my $head = git_get_head_hash($project);
3993        git_header_html();
3994        git_print_page_nav('','', $head,undef,$head);
3995        git_print_header_div('summary', $project);
3996
3997        my @headslist = git_get_heads_list();
3998        if (@headslist) {
3999                git_heads_body(\@headslist, $head);
4000        }
4001        git_footer_html();
4002}
4003
4004sub git_blob_plain {
4005        my $expires;
4006
4007        if (!defined $hash) {
4008                if (defined $file_name) {
4009                        my $base = $hash_base || git_get_head_hash($project);
4010                        $hash = git_get_hash_by_path($base, $file_name, "blob")
4011                                or die_error(undef, "Error lookup file");
4012                } else {
4013                        die_error(undef, "No file name defined");
4014                }
4015        } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4016                # blobs defined by non-textual hash id's can be cached
4017                $expires = "+1d";
4018        }
4019
4020        my $type = shift;
4021        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4022                or die_error(undef, "Couldn't cat $file_name, $hash");
4023
4024        $type ||= blob_mimetype($fd, $file_name);
4025
4026        # save as filename, even when no $file_name is given
4027        my $save_as = "$hash";
4028        if (defined $file_name) {
4029                $save_as = $file_name;
4030        } elsif ($type =~ m/^text\//) {
4031                $save_as .= '.txt';
4032        }
4033
4034        print $cgi->header(
4035                -type => "$type",
4036                -expires=>$expires,
4037                -content_disposition => 'inline; filename="' . "$save_as" . '"');
4038        undef $/;
4039        binmode STDOUT, ':raw';
4040        print <$fd>;
4041        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4042        $/ = "\n";
4043        close $fd;
4044}
4045
4046sub git_blob {
4047        my $expires;
4048
4049        if (!defined $hash) {
4050                if (defined $file_name) {
4051                        my $base = $hash_base || git_get_head_hash($project);
4052                        $hash = git_get_hash_by_path($base, $file_name, "blob")
4053                                or die_error(undef, "Error lookup file");
4054                } else {
4055                        die_error(undef, "No file name defined");
4056                }
4057        } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4058                # blobs defined by non-textual hash id's can be cached
4059                $expires = "+1d";
4060        }
4061
4062        my ($have_blame) = gitweb_check_feature('blame');
4063        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4064                or die_error(undef, "Couldn't cat $file_name, $hash");
4065        my $mimetype = blob_mimetype($fd, $file_name);
4066        if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)!) {
4067                close $fd;
4068                return git_blob_plain($mimetype);
4069        }
4070        # we can have blame only for text/* mimetype
4071        $have_blame &&= ($mimetype =~ m!^text/!);
4072
4073        git_header_html(undef, $expires);
4074        my $formats_nav = '';
4075        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4076                if (defined $file_name) {
4077                        if ($have_blame) {
4078                                $formats_nav .=
4079                                        $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
4080                                                               hash=>$hash, file_name=>$file_name)},
4081                                                "blame") .
4082                                        " | ";
4083                        }
4084                        $formats_nav .=
4085                                $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4086                                                       hash=>$hash, file_name=>$file_name)},
4087                                        "history") .
4088                                " | " .
4089                                $cgi->a({-href => href(action=>"blob_plain",
4090                                                       hash=>$hash, file_name=>$file_name)},
4091                                        "raw") .
4092                                " | " .
4093                                $cgi->a({-href => href(action=>"blob",
4094                                                       hash_base=>"HEAD", file_name=>$file_name)},
4095                                        "HEAD");
4096                } else {
4097                        $formats_nav .=
4098                                $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
4099                }
4100                git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4101                git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4102        } else {
4103                print "<div class=\"page_nav\">\n" .
4104                      "<br/><br/></div>\n" .
4105                      "<div class=\"title\">$hash</div>\n";
4106        }
4107        git_print_page_path($file_name, "blob", $hash_base);
4108        print "<div class=\"page_body\">\n";
4109        if ($mimetype =~ m!^text/!) {
4110                my $nr;
4111                while (my $line = <$fd>) {
4112                        chomp $line;
4113                        $nr++;
4114                        $line = untabify($line);
4115                        printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
4116                               $nr, $nr, $nr, esc_html($line, -nbsp=>1);
4117                }
4118        } elsif ($mimetype =~ m!^image/!) {
4119                print qq!<img type="$mimetype"!;
4120                if ($file_name) {
4121                        print qq! alt="$file_name" title="$file_name"!;
4122                }
4123                print qq! src="! .
4124                      href(action=>"blob_plain", hash=>$hash,
4125                           hash_base=>$hash_base, file_name=>$file_name) .
4126                      qq!" />\n!;
4127        }
4128        close $fd
4129                or print "Reading blob failed.\n";
4130        print "</div>";
4131        git_footer_html();
4132}
4133
4134sub git_tree {
4135        my $have_snapshot = gitweb_have_snapshot();
4136
4137        if (!defined $hash_base) {
4138                $hash_base = "HEAD";
4139        }
4140        if (!defined $hash) {
4141                if (defined $file_name) {
4142                        $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
4143                } else {
4144                        $hash = $hash_base;
4145                }
4146        }
4147        $/ = "\0";
4148        open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
4149                or die_error(undef, "Open git-ls-tree failed");
4150        my @entries = map { chomp; $_ } <$fd>;
4151        close $fd or die_error(undef, "Reading tree failed");
4152        $/ = "\n";
4153
4154        my $refs = git_get_references();
4155        my $ref = format_ref_marker($refs, $hash_base);
4156        git_header_html();
4157        my $basedir = '';
4158        my ($have_blame) = gitweb_check_feature('blame');
4159        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4160                my @views_nav = ();
4161                if (defined $file_name) {
4162                        push @views_nav,
4163                                $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4164                                                       hash=>$hash, file_name=>$file_name)},
4165                                        "history"),
4166                                $cgi->a({-href => href(action=>"tree",
4167                                                       hash_base=>"HEAD", file_name=>$file_name)},
4168                                        "HEAD"),
4169                }
4170                if ($have_snapshot) {
4171                        # FIXME: Should be available when we have no hash base as well.
4172                        push @views_nav,
4173                                $cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
4174                                        "snapshot");
4175                }
4176                git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
4177                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
4178        } else {
4179                undef $hash_base;
4180                print "<div class=\"page_nav\">\n";
4181                print "<br/><br/></div>\n";
4182                print "<div class=\"title\">$hash</div>\n";
4183        }
4184        if (defined $file_name) {
4185                $basedir = $file_name;
4186                if ($basedir ne '' && substr($basedir, -1) ne '/') {
4187                        $basedir .= '/';
4188                }
4189        }
4190        git_print_page_path($file_name, 'tree', $hash_base);
4191        print "<div class=\"page_body\">\n";
4192        print "<table cellspacing=\"0\">\n";
4193        my $alternate = 1;
4194        # '..' (top directory) link if possible
4195        if (defined $hash_base &&
4196            defined $file_name && $file_name =~ m![^/]+$!) {
4197                if ($alternate) {
4198                        print "<tr class=\"dark\">\n";
4199                } else {
4200                        print "<tr class=\"light\">\n";
4201                }
4202                $alternate ^= 1;
4203
4204                my $up = $file_name;
4205                $up =~ s!/?[^/]+$!!;
4206                undef $up unless $up;
4207                # based on git_print_tree_entry
4208                print '<td class="mode">' . mode_str('040000') . "</td>\n";
4209                print '<td class="list">';
4210                print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
4211                                             file_name=>$up)},
4212                              "..");
4213                print "</td>\n";
4214                print "<td class=\"link\"></td>\n";
4215
4216                print "</tr>\n";
4217        }
4218        foreach my $line (@entries) {
4219                my %t = parse_ls_tree_line($line, -z => 1);
4220
4221                if ($alternate) {
4222                        print "<tr class=\"dark\">\n";
4223                } else {
4224                        print "<tr class=\"light\">\n";
4225                }
4226                $alternate ^= 1;
4227
4228                git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
4229
4230                print "</tr>\n";
4231        }
4232        print "</table>\n" .
4233              "</div>";
4234        git_footer_html();
4235}
4236
4237sub git_snapshot {
4238        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
4239        my $have_snapshot = (defined $ctype && defined $suffix);
4240        if (!$have_snapshot) {
4241                die_error('403 Permission denied', "Permission denied");
4242        }
4243
4244        if (!defined $hash) {
4245                $hash = git_get_head_hash($project);
4246        }
4247
4248        my $git = git_cmd_str();
4249        my $name = $project;
4250        $name =~ s,([^/])/*\.git$,$1,;
4251        $name = basename($name);
4252        my $filename = to_utf8($name);
4253        $name =~ s/\047/\047\\\047\047/g;
4254        my $cmd;
4255        if ($suffix eq 'zip') {
4256                $filename .= "-$hash.$suffix";
4257                $cmd = "$git archive --format=zip --prefix=\'$name\'/ $hash";
4258        } else {
4259                $filename .= "-$hash.tar.$suffix";
4260                $cmd = "$git archive --format=tar --prefix=\'$name\'/ $hash | $command";
4261        }
4262
4263        print $cgi->header(
4264                -type => "application/$ctype",
4265                -content_disposition => 'inline; filename="' . "$filename" . '"',
4266                -status => '200 OK');
4267
4268        open my $fd, "-|", $cmd
4269                or die_error(undef, "Execute git-archive failed");
4270        binmode STDOUT, ':raw';
4271        print <$fd>;
4272        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4273        close $fd;
4274
4275}
4276
4277sub git_log {
4278        my $head = git_get_head_hash($project);
4279        if (!defined $hash) {
4280                $hash = $head;
4281        }
4282        if (!defined $page) {
4283                $page = 0;
4284        }
4285        my $refs = git_get_references();
4286
4287        my @commitlist = parse_commits($hash, 101, (100 * $page));
4288
4289        my $paging_nav = format_paging_nav('log', $hash, $head, $page, (100 * ($page+1)));
4290
4291        git_header_html();
4292        git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
4293
4294        if (!@commitlist) {
4295                my %co = parse_commit($hash);
4296
4297                git_print_header_div('summary', $project);
4298                print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
4299        }
4300        my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
4301        for (my $i = 0; $i <= $to; $i++) {
4302                my %co = %{$commitlist[$i]};
4303                next if !%co;
4304                my $commit = $co{'id'};
4305                my $ref = format_ref_marker($refs, $commit);
4306                my %ad = parse_date($co{'author_epoch'});
4307                git_print_header_div('commit',
4308                               "<span class=\"age\">$co{'age_string'}</span>" .
4309                               esc_html($co{'title'}) . $ref,
4310                               $commit);
4311                print "<div class=\"title_text\">\n" .
4312                      "<div class=\"log_link\">\n" .
4313                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4314                      " | " .
4315                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4316                      " | " .
4317                      $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4318                      "<br/>\n" .
4319                      "</div>\n" .
4320                      "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
4321                      "</div>\n";
4322
4323                print "<div class=\"log_body\">\n";
4324                git_print_log($co{'comment'}, -final_empty_line=> 1);
4325                print "</div>\n";
4326        }
4327        if ($#commitlist >= 100) {
4328                print "<div class=\"page_nav\">\n";
4329                print $cgi->a({-href => href(action=>"log", hash=>$hash, page=>$page+1),
4330                               -accesskey => "n", -title => "Alt-n"}, "next");
4331                print "</div>\n";
4332        }
4333        git_footer_html();
4334}
4335
4336sub git_commit {
4337        $hash ||= $hash_base || "HEAD";
4338        my %co = parse_commit($hash);
4339        if (!%co) {
4340                die_error(undef, "Unknown commit object");
4341        }
4342        my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4343        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
4344
4345        my $parent  = $co{'parent'};
4346        my $parents = $co{'parents'}; # listref
4347
4348        # we need to prepare $formats_nav before any parameter munging
4349        my $formats_nav;
4350        if (!defined $parent) {
4351                # --root commitdiff
4352                $formats_nav .= '(initial)';
4353        } elsif (@$parents == 1) {
4354                # single parent commit
4355                $formats_nav .=
4356                        '(parent: ' .
4357                        $cgi->a({-href => href(action=>"commit",
4358                                               hash=>$parent)},
4359                                esc_html(substr($parent, 0, 7))) .
4360                        ')';
4361        } else {
4362                # merge commit
4363                $formats_nav .=
4364                        '(merge: ' .
4365                        join(' ', map {
4366                                $cgi->a({-href => href(action=>"commit",
4367                                                       hash=>$_)},
4368                                        esc_html(substr($_, 0, 7)));
4369                        } @$parents ) .
4370                        ')';
4371        }
4372
4373        if (!defined $parent) {
4374                $parent = "--root";
4375        }
4376        my @difftree;
4377        open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
4378                @diff_opts,
4379                (@$parents <= 1 ? $parent : '-c'),
4380                $hash, "--"
4381                or die_error(undef, "Open git-diff-tree failed");
4382        @difftree = map { chomp; $_ } <$fd>;
4383        close $fd or die_error(undef, "Reading git-diff-tree failed");
4384
4385        # non-textual hash id's can be cached
4386        my $expires;
4387        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4388                $expires = "+1d";
4389        }
4390        my $refs = git_get_references();
4391        my $ref = format_ref_marker($refs, $co{'id'});
4392
4393        my $have_snapshot = gitweb_have_snapshot();
4394
4395        git_header_html(undef, $expires);
4396        git_print_page_nav('commit', '',
4397                           $hash, $co{'tree'}, $hash,
4398                           $formats_nav);
4399
4400        if (defined $co{'parent'}) {
4401                git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
4402        } else {
4403                git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
4404        }
4405        print "<div class=\"title_text\">\n" .
4406              "<table cellspacing=\"0\">\n";
4407        print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
4408              "<tr>" .
4409              "<td></td><td> $ad{'rfc2822'}";
4410        if ($ad{'hour_local'} < 6) {
4411                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4412                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4413        } else {
4414                printf(" (%02d:%02d %s)",
4415                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4416        }
4417        print "</td>" .
4418              "</tr>\n";
4419        print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
4420        print "<tr><td></td><td> $cd{'rfc2822'}" .
4421              sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
4422              "</td></tr>\n";
4423        print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
4424        print "<tr>" .
4425              "<td>tree</td>" .
4426              "<td class=\"sha1\">" .
4427              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
4428                       class => "list"}, $co{'tree'}) .
4429              "</td>" .
4430              "<td class=\"link\">" .
4431              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
4432                      "tree");
4433        if ($have_snapshot) {
4434                print " | " .
4435                      $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
4436        }
4437        print "</td>" .
4438              "</tr>\n";
4439
4440        foreach my $par (@$parents) {
4441                print "<tr>" .
4442                      "<td>parent</td>" .
4443                      "<td class=\"sha1\">" .
4444                      $cgi->a({-href => href(action=>"commit", hash=>$par),
4445                               class => "list"}, $par) .
4446                      "</td>" .
4447                      "<td class=\"link\">" .
4448                      $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
4449                      " | " .
4450                      $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
4451                      "</td>" .
4452                      "</tr>\n";
4453        }
4454        print "</table>".
4455              "</div>\n";
4456
4457        print "<div class=\"page_body\">\n";
4458        git_print_log($co{'comment'});
4459        print "</div>\n";
4460
4461        git_difftree_body(\@difftree, $hash, @$parents);
4462
4463        git_footer_html();
4464}
4465
4466sub git_object {
4467        # object is defined by:
4468        # - hash or hash_base alone
4469        # - hash_base and file_name
4470        my $type;
4471
4472        # - hash or hash_base alone
4473        if ($hash || ($hash_base && !defined $file_name)) {
4474                my $object_id = $hash || $hash_base;
4475
4476                my $git_command = git_cmd_str();
4477                open my $fd, "-|", "$git_command cat-file -t $object_id 2>/dev/null"
4478                        or die_error('404 Not Found', "Object does not exist");
4479                $type = <$fd>;
4480                chomp $type;
4481                close $fd
4482                        or die_error('404 Not Found', "Object does not exist");
4483
4484        # - hash_base and file_name
4485        } elsif ($hash_base && defined $file_name) {
4486                $file_name =~ s,/+$,,;
4487
4488                system(git_cmd(), "cat-file", '-e', $hash_base) == 0
4489                        or die_error('404 Not Found', "Base object does not exist");
4490
4491                # here errors should not hapen
4492                open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
4493                        or die_error(undef, "Open git-ls-tree failed");
4494                my $line = <$fd>;
4495                close $fd;
4496
4497                #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
4498                unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
4499                        die_error('404 Not Found', "File or directory for given base does not exist");
4500                }
4501                $type = $2;
4502                $hash = $3;
4503        } else {
4504                die_error('404 Not Found', "Not enough information to find object");
4505        }
4506
4507        print $cgi->redirect(-uri => href(action=>$type, -full=>1,
4508                                          hash=>$hash, hash_base=>$hash_base,
4509                                          file_name=>$file_name),
4510                             -status => '302 Found');
4511}
4512
4513sub git_blobdiff {
4514        my $format = shift || 'html';
4515
4516        my $fd;
4517        my @difftree;
4518        my %diffinfo;
4519        my $expires;
4520
4521        # preparing $fd and %diffinfo for git_patchset_body
4522        # new style URI
4523        if (defined $hash_base && defined $hash_parent_base) {
4524                if (defined $file_name) {
4525                        # read raw output
4526                        open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4527                                $hash_parent_base, $hash_base,
4528                                "--", (defined $file_parent ? $file_parent : ()), $file_name
4529                                or die_error(undef, "Open git-diff-tree failed");
4530                        @difftree = map { chomp; $_ } <$fd>;
4531                        close $fd
4532                                or die_error(undef, "Reading git-diff-tree failed");
4533                        @difftree
4534                                or die_error('404 Not Found', "Blob diff not found");
4535
4536                } elsif (defined $hash &&
4537                         $hash =~ /[0-9a-fA-F]{40}/) {
4538                        # try to find filename from $hash
4539
4540                        # read filtered raw output
4541                        open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4542                                $hash_parent_base, $hash_base, "--"
4543                                or die_error(undef, "Open git-diff-tree failed");
4544                        @difftree =
4545                                # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
4546                                # $hash == to_id
4547                                grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
4548                                map { chomp; $_ } <$fd>;
4549                        close $fd
4550                                or die_error(undef, "Reading git-diff-tree failed");
4551                        @difftree
4552                                or die_error('404 Not Found', "Blob diff not found");
4553
4554                } else {
4555                        die_error('404 Not Found', "Missing one of the blob diff parameters");
4556                }
4557
4558                if (@difftree > 1) {
4559                        die_error('404 Not Found', "Ambiguous blob diff specification");
4560                }
4561
4562                %diffinfo = parse_difftree_raw_line($difftree[0]);
4563                $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
4564                $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
4565
4566                $hash_parent ||= $diffinfo{'from_id'};
4567                $hash        ||= $diffinfo{'to_id'};
4568
4569                # non-textual hash id's can be cached
4570                if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
4571                    $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
4572                        $expires = '+1d';
4573                }
4574
4575                # open patch output
4576                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4577                        '-p', ($format eq 'html' ? "--full-index" : ()),
4578                        $hash_parent_base, $hash_base,
4579                        "--", (defined $file_parent ? $file_parent : ()), $file_name
4580                        or die_error(undef, "Open git-diff-tree failed");
4581        }
4582
4583        # old/legacy style URI
4584        if (!%diffinfo && # if new style URI failed
4585            defined $hash && defined $hash_parent) {
4586                # fake git-diff-tree raw output
4587                $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
4588                $diffinfo{'from_id'} = $hash_parent;
4589                $diffinfo{'to_id'}   = $hash;
4590                if (defined $file_name) {
4591                        if (defined $file_parent) {
4592                                $diffinfo{'status'} = '2';
4593                                $diffinfo{'from_file'} = $file_parent;
4594                                $diffinfo{'to_file'}   = $file_name;
4595                        } else { # assume not renamed
4596                                $diffinfo{'status'} = '1';
4597                                $diffinfo{'from_file'} = $file_name;
4598                                $diffinfo{'to_file'}   = $file_name;
4599                        }
4600                } else { # no filename given
4601                        $diffinfo{'status'} = '2';
4602                        $diffinfo{'from_file'} = $hash_parent;
4603                        $diffinfo{'to_file'}   = $hash;
4604                }
4605
4606                # non-textual hash id's can be cached
4607                if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
4608                    $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4609                        $expires = '+1d';
4610                }
4611
4612                # open patch output
4613                open $fd, "-|", git_cmd(), "diff", @diff_opts,
4614                        '-p', ($format eq 'html' ? "--full-index" : ()),
4615                        $hash_parent, $hash, "--"
4616                        or die_error(undef, "Open git-diff failed");
4617        } else  {
4618                die_error('404 Not Found', "Missing one of the blob diff parameters")
4619                        unless %diffinfo;
4620        }
4621
4622        # header
4623        if ($format eq 'html') {
4624                my $formats_nav =
4625                        $cgi->a({-href => href(action=>"blobdiff_plain",
4626                                               hash=>$hash, hash_parent=>$hash_parent,
4627                                               hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
4628                                               file_name=>$file_name, file_parent=>$file_parent)},
4629                                "raw");
4630                git_header_html(undef, $expires);
4631                if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4632                        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4633                        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4634                } else {
4635                        print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
4636                        print "<div class=\"title\">$hash vs $hash_parent</div>\n";
4637                }
4638                if (defined $file_name) {
4639                        git_print_page_path($file_name, "blob", $hash_base);
4640                } else {
4641                        print "<div class=\"page_path\"></div>\n";
4642                }
4643
4644        } elsif ($format eq 'plain') {
4645                print $cgi->header(
4646                        -type => 'text/plain',
4647                        -charset => 'utf-8',
4648                        -expires => $expires,
4649                        -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
4650
4651                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4652
4653        } else {
4654                die_error(undef, "Unknown blobdiff format");
4655        }
4656
4657        # patch
4658        if ($format eq 'html') {
4659                print "<div class=\"page_body\">\n";
4660
4661                git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
4662                close $fd;
4663
4664                print "</div>\n"; # class="page_body"
4665                git_footer_html();
4666
4667        } else {
4668                while (my $line = <$fd>) {
4669                        $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
4670                        $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
4671
4672                        print $line;
4673
4674                        last if $line =~ m!^\+\+\+!;
4675                }
4676                local $/ = undef;
4677                print <$fd>;
4678                close $fd;
4679        }
4680}
4681
4682sub git_blobdiff_plain {
4683        git_blobdiff('plain');
4684}
4685
4686sub git_commitdiff {
4687        my $format = shift || 'html';
4688        $hash ||= $hash_base || "HEAD";
4689        my %co = parse_commit($hash);
4690        if (!%co) {
4691                die_error(undef, "Unknown commit object");
4692        }
4693
4694        # choose format for commitdiff for merge
4695        if (! defined $hash_parent && @{$co{'parents'}} > 1) {
4696                $hash_parent = '--cc';
4697        }
4698        # we need to prepare $formats_nav before almost any parameter munging
4699        my $formats_nav;
4700        if ($format eq 'html') {
4701                $formats_nav =
4702                        $cgi->a({-href => href(action=>"commitdiff_plain",
4703                                               hash=>$hash, hash_parent=>$hash_parent)},
4704                                "raw");
4705
4706                if (defined $hash_parent &&
4707                    $hash_parent ne '-c' && $hash_parent ne '--cc') {
4708                        # commitdiff with two commits given
4709                        my $hash_parent_short = $hash_parent;
4710                        if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4711                                $hash_parent_short = substr($hash_parent, 0, 7);
4712                        }
4713                        $formats_nav .=
4714                                ' (from';
4715                        for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
4716                                if ($co{'parents'}[$i] eq $hash_parent) {
4717                                        $formats_nav .= ' parent ' . ($i+1);
4718                                        last;
4719                                }
4720                        }
4721                        $formats_nav .= ': ' .
4722                                $cgi->a({-href => href(action=>"commitdiff",
4723                                                       hash=>$hash_parent)},
4724                                        esc_html($hash_parent_short)) .
4725                                ')';
4726                } elsif (!$co{'parent'}) {
4727                        # --root commitdiff
4728                        $formats_nav .= ' (initial)';
4729                } elsif (scalar @{$co{'parents'}} == 1) {
4730                        # single parent commit
4731                        $formats_nav .=
4732                                ' (parent: ' .
4733                                $cgi->a({-href => href(action=>"commitdiff",
4734                                                       hash=>$co{'parent'})},
4735                                        esc_html(substr($co{'parent'}, 0, 7))) .
4736                                ')';
4737                } else {
4738                        # merge commit
4739                        if ($hash_parent eq '--cc') {
4740                                $formats_nav .= ' | ' .
4741                                        $cgi->a({-href => href(action=>"commitdiff",
4742                                                               hash=>$hash, hash_parent=>'-c')},
4743                                                'combined');
4744                        } else { # $hash_parent eq '-c'
4745                                $formats_nav .= ' | ' .
4746                                        $cgi->a({-href => href(action=>"commitdiff",
4747                                                               hash=>$hash, hash_parent=>'--cc')},
4748                                                'compact');
4749                        }
4750                        $formats_nav .=
4751                                ' (merge: ' .
4752                                join(' ', map {
4753                                        $cgi->a({-href => href(action=>"commitdiff",
4754                                                               hash=>$_)},
4755                                                esc_html(substr($_, 0, 7)));
4756                                } @{$co{'parents'}} ) .
4757                                ')';
4758                }
4759        }
4760
4761        my $hash_parent_param = $hash_parent;
4762        if (!defined $hash_parent_param) {
4763                # --cc for multiple parents, --root for parentless
4764                $hash_parent_param =
4765                        @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
4766        }
4767
4768        # read commitdiff
4769        my $fd;
4770        my @difftree;
4771        if ($format eq 'html') {
4772                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4773                        "--no-commit-id", "--patch-with-raw", "--full-index",
4774                        $hash_parent_param, $hash, "--"
4775                        or die_error(undef, "Open git-diff-tree failed");
4776
4777                while (my $line = <$fd>) {
4778                        chomp $line;
4779                        # empty line ends raw part of diff-tree output
4780                        last unless $line;
4781                        push @difftree, scalar parse_difftree_raw_line($line);
4782                }
4783
4784        } elsif ($format eq 'plain') {
4785                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4786                        '-p', $hash_parent_param, $hash, "--"
4787                        or die_error(undef, "Open git-diff-tree failed");
4788
4789        } else {
4790                die_error(undef, "Unknown commitdiff format");
4791        }
4792
4793        # non-textual hash id's can be cached
4794        my $expires;
4795        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4796                $expires = "+1d";
4797        }
4798
4799        # write commit message
4800        if ($format eq 'html') {
4801                my $refs = git_get_references();
4802                my $ref = format_ref_marker($refs, $co{'id'});
4803
4804                git_header_html(undef, $expires);
4805                git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
4806                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
4807                git_print_authorship(\%co);
4808                print "<div class=\"page_body\">\n";
4809                if (@{$co{'comment'}} > 1) {
4810                        print "<div class=\"log\">\n";
4811                        git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
4812                        print "</div>\n"; # class="log"
4813                }
4814
4815        } elsif ($format eq 'plain') {
4816                my $refs = git_get_references("tags");
4817                my $tagname = git_get_rev_name_tags($hash);
4818                my $filename = basename($project) . "-$hash.patch";
4819
4820                print $cgi->header(
4821                        -type => 'text/plain',
4822                        -charset => 'utf-8',
4823                        -expires => $expires,
4824                        -content_disposition => 'inline; filename="' . "$filename" . '"');
4825                my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4826                print <<TEXT;
4827From: $co{'author'}
4828Date: $ad{'rfc2822'} ($ad{'tz_local'})
4829Subject: $co{'title'}
4830TEXT
4831                print "X-Git-Tag: $tagname\n" if $tagname;
4832                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4833
4834                foreach my $line (@{$co{'comment'}}) {
4835                        print "$line\n";
4836                }
4837                print "---\n\n";
4838        }
4839
4840        # write patch
4841        if ($format eq 'html') {
4842                my $use_parents = !defined $hash_parent ||
4843                        $hash_parent eq '-c' || $hash_parent eq '--cc';
4844                git_difftree_body(\@difftree, $hash,
4845                                  $use_parents ? @{$co{'parents'}} : $hash_parent);
4846                print "<br/>\n";
4847
4848                git_patchset_body($fd, \@difftree, $hash,
4849                                  $use_parents ? @{$co{'parents'}} : $hash_parent);
4850                close $fd;
4851                print "</div>\n"; # class="page_body"
4852                git_footer_html();
4853
4854        } elsif ($format eq 'plain') {
4855                local $/ = undef;
4856                print <$fd>;
4857                close $fd
4858                        or print "Reading git-diff-tree failed\n";
4859        }
4860}
4861
4862sub git_commitdiff_plain {
4863        git_commitdiff('plain');
4864}
4865
4866sub git_history {
4867        if (!defined $hash_base) {
4868                $hash_base = git_get_head_hash($project);
4869        }
4870        if (!defined $page) {
4871                $page = 0;
4872        }
4873        my $ftype;
4874        my %co = parse_commit($hash_base);
4875        if (!%co) {
4876                die_error(undef, "Unknown commit object");
4877        }
4878
4879        my $refs = git_get_references();
4880        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
4881
4882        if (!defined $hash && defined $file_name) {
4883                $hash = git_get_hash_by_path($hash_base, $file_name);
4884        }
4885        if (defined $hash) {
4886                $ftype = git_get_type($hash);
4887        }
4888
4889        my @commitlist = parse_commits($hash_base, 101, (100 * $page), "--full-history", $file_name);
4890
4891        my $paging_nav = '';
4892        if ($page > 0) {
4893                $paging_nav .=
4894                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4895                                               file_name=>$file_name)},
4896                                "first");
4897                $paging_nav .= " &sdot; " .
4898                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4899                                               file_name=>$file_name, page=>$page-1),
4900                                 -accesskey => "p", -title => "Alt-p"}, "prev");
4901        } else {
4902                $paging_nav .= "first";
4903                $paging_nav .= " &sdot; prev";
4904        }
4905        if ($#commitlist >= 100) {
4906                $paging_nav .= " &sdot; " .
4907                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4908                                               file_name=>$file_name, page=>$page+1),
4909                                 -accesskey => "n", -title => "Alt-n"}, "next");
4910        } else {
4911                $paging_nav .= " &sdot; next";
4912        }
4913        my $next_link = '';
4914        if ($#commitlist >= 100) {
4915                $next_link =
4916                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4917                                               file_name=>$file_name, page=>$page+1),
4918                                 -accesskey => "n", -title => "Alt-n"}, "next");
4919        }
4920
4921        git_header_html();
4922        git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
4923        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4924        git_print_page_path($file_name, $ftype, $hash_base);
4925
4926        git_history_body(\@commitlist, 0, 99,
4927                         $refs, $hash_base, $ftype, $next_link);
4928
4929        git_footer_html();
4930}
4931
4932sub git_search {
4933        my ($have_search) = gitweb_check_feature('search');
4934        if (!$have_search) {
4935                die_error('403 Permission denied', "Permission denied");
4936        }
4937        if (!defined $searchtext) {
4938                die_error(undef, "Text field empty");
4939        }
4940        if (!defined $hash) {
4941                $hash = git_get_head_hash($project);
4942        }
4943        my %co = parse_commit($hash);
4944        if (!%co) {
4945                die_error(undef, "Unknown commit object");
4946        }
4947        if (!defined $page) {
4948                $page = 0;
4949        }
4950
4951        $searchtype ||= 'commit';
4952        if ($searchtype eq 'pickaxe') {
4953                # pickaxe may take all resources of your box and run for several minutes
4954                # with every query - so decide by yourself how public you make this feature
4955                my ($have_pickaxe) = gitweb_check_feature('pickaxe');
4956                if (!$have_pickaxe) {
4957                        die_error('403 Permission denied', "Permission denied");
4958                }
4959        }
4960        if ($searchtype eq 'grep') {
4961                my ($have_grep) = gitweb_check_feature('grep');
4962                if (!$have_grep) {
4963                        die_error('403 Permission denied', "Permission denied");
4964                }
4965        }
4966
4967        git_header_html();
4968
4969        if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
4970                my $greptype;
4971                if ($searchtype eq 'commit') {
4972                        $greptype = "--grep=";
4973                } elsif ($searchtype eq 'author') {
4974                        $greptype = "--author=";
4975                } elsif ($searchtype eq 'committer') {
4976                        $greptype = "--committer=";
4977                }
4978                $greptype .= $search_regexp;
4979                my @commitlist = parse_commits($hash, 101, (100 * $page), $greptype);
4980
4981                my $paging_nav = '';
4982                if ($page > 0) {
4983                        $paging_nav .=
4984                                $cgi->a({-href => href(action=>"search", hash=>$hash,
4985                                                       searchtext=>$searchtext, searchtype=>$searchtype)},
4986                                        "first");
4987                        $paging_nav .= " &sdot; " .
4988                                $cgi->a({-href => href(action=>"search", hash=>$hash,
4989                                                       searchtext=>$searchtext, searchtype=>$searchtype,
4990                                                       page=>$page-1),
4991                                         -accesskey => "p", -title => "Alt-p"}, "prev");
4992                } else {
4993                        $paging_nav .= "first";
4994                        $paging_nav .= " &sdot; prev";
4995                }
4996                if ($#commitlist >= 100) {
4997                        $paging_nav .= " &sdot; " .
4998                                $cgi->a({-href => href(action=>"search", hash=>$hash,
4999                                                       searchtext=>$searchtext, searchtype=>$searchtype,
5000                                                       page=>$page+1),
5001                                         -accesskey => "n", -title => "Alt-n"}, "next");
5002                } else {
5003                        $paging_nav .= " &sdot; next";
5004                }
5005                my $next_link = '';
5006                if ($#commitlist >= 100) {
5007                        $next_link =
5008                                $cgi->a({-href => href(action=>"search", hash=>$hash,
5009                                                       searchtext=>$searchtext, searchtype=>$searchtype,
5010                                                       page=>$page+1),
5011                                         -accesskey => "n", -title => "Alt-n"}, "next");
5012                }
5013
5014                git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
5015                git_print_header_div('commit', esc_html($co{'title'}), $hash);
5016                git_search_grep_body(\@commitlist, 0, 99, $next_link);
5017        }
5018
5019        if ($searchtype eq 'pickaxe') {
5020                git_print_page_nav('','', $hash,$co{'tree'},$hash);
5021                git_print_header_div('commit', esc_html($co{'title'}), $hash);
5022
5023                print "<table cellspacing=\"0\">\n";
5024                my $alternate = 1;
5025                $/ = "\n";
5026                my $git_command = git_cmd_str();
5027                my $searchqtext = $searchtext;
5028                $searchqtext =~ s/'/'\\''/;
5029                open my $fd, "-|", "$git_command rev-list $hash | " .
5030                        "$git_command diff-tree -r --stdin -S\'$searchqtext\'";
5031                undef %co;
5032                my @files;
5033                while (my $line = <$fd>) {
5034                        if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
5035                                my %set;
5036                                $set{'file'} = $6;
5037                                $set{'from_id'} = $3;
5038                                $set{'to_id'} = $4;
5039                                $set{'id'} = $set{'to_id'};
5040                                if ($set{'id'} =~ m/0{40}/) {
5041                                        $set{'id'} = $set{'from_id'};
5042                                }
5043                                if ($set{'id'} =~ m/0{40}/) {
5044                                        next;
5045                                }
5046                                push @files, \%set;
5047                        } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
5048                                if (%co) {
5049                                        if ($alternate) {
5050                                                print "<tr class=\"dark\">\n";
5051                                        } else {
5052                                                print "<tr class=\"light\">\n";
5053                                        }
5054                                        $alternate ^= 1;
5055                                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5056                                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
5057                                              "<td>" .
5058                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5059                                                      -class => "list subject"},
5060                                                      esc_html(chop_str($co{'title'}, 50)) . "<br/>");
5061                                        while (my $setref = shift @files) {
5062                                                my %set = %$setref;
5063                                                print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
5064                                                                             hash=>$set{'id'}, file_name=>$set{'file'}),
5065                                                              -class => "list"},
5066                                                              "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
5067                                                      "<br/>\n";
5068                                        }
5069                                        print "</td>\n" .
5070                                              "<td class=\"link\">" .
5071                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5072                                              " | " .
5073                                              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5074                                        print "</td>\n" .
5075                                              "</tr>\n";
5076                                }
5077                                %co = parse_commit($1);
5078                        }
5079                }
5080                close $fd;
5081
5082                print "</table>\n";
5083        }
5084
5085        if ($searchtype eq 'grep') {
5086                git_print_page_nav('','', $hash,$co{'tree'},$hash);
5087                git_print_header_div('commit', esc_html($co{'title'}), $hash);
5088
5089                print "<table cellspacing=\"0\">\n";
5090                my $alternate = 1;
5091                my $matches = 0;
5092                $/ = "\n";
5093                open my $fd, "-|", git_cmd(), 'grep', '-n', '-i', '-E', $searchtext, $co{'tree'};
5094                my $lastfile = '';
5095                while (my $line = <$fd>) {
5096                        chomp $line;
5097                        my ($file, $lno, $ltext, $binary);
5098                        last if ($matches++ > 1000);
5099                        if ($line =~ /^Binary file (.+) matches$/) {
5100                                $file = $1;
5101                                $binary = 1;
5102                        } else {
5103                                (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
5104                        }
5105                        if ($file ne $lastfile) {
5106                                $lastfile and print "</td></tr>\n";
5107                                if ($alternate++) {
5108                                        print "<tr class=\"dark\">\n";
5109                                } else {
5110                                        print "<tr class=\"light\">\n";
5111                                }
5112                                print "<td class=\"list\">".
5113                                        $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5114                                                               file_name=>"$file"),
5115                                                -class => "list"}, esc_path($file));
5116                                print "</td><td>\n";
5117                                $lastfile = $file;
5118                        }
5119                        if ($binary) {
5120                                print "<div class=\"binary\">Binary file</div>\n";
5121                        } else {
5122                                $ltext = untabify($ltext);
5123                                if ($ltext =~ m/^(.*)($searchtext)(.*)$/i) {
5124                                        $ltext = esc_html($1, -nbsp=>1);
5125                                        $ltext .= '<span class="match">';
5126                                        $ltext .= esc_html($2, -nbsp=>1);
5127                                        $ltext .= '</span>';
5128                                        $ltext .= esc_html($3, -nbsp=>1);
5129                                } else {
5130                                        $ltext = esc_html($ltext, -nbsp=>1);
5131                                }
5132                                print "<div class=\"pre\">" .
5133                                        $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5134                                                               file_name=>"$file").'#l'.$lno,
5135                                                -class => "linenr"}, sprintf('%4i', $lno))
5136                                        . ' ' .  $ltext . "</div>\n";
5137                        }
5138                }
5139                if ($lastfile) {
5140                        print "</td></tr>\n";
5141                        if ($matches > 1000) {
5142                                print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
5143                        }
5144                } else {
5145                        print "<div class=\"diff nodifferences\">No matches found</div>\n";
5146                }
5147                close $fd;
5148
5149                print "</table>\n";
5150        }
5151        git_footer_html();
5152}
5153
5154sub git_search_help {
5155        git_header_html();
5156        git_print_page_nav('','', $hash,$hash,$hash);
5157        print <<EOT;
5158<dl>
5159<dt><b>commit</b></dt>
5160<dd>The commit messages and authorship information will be scanned for the given string.</dd>
5161EOT
5162        my ($have_grep) = gitweb_check_feature('grep');
5163        if ($have_grep) {
5164                print <<EOT;
5165<dt><b>grep</b></dt>
5166<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
5167    a different one) are searched for the given
5168<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a>
5169(POSIX extended) and the matches are listed. On large
5170trees, this search can take a while and put some strain on the server, so please use it with
5171some consideration.</dd>
5172EOT
5173        }
5174        print <<EOT;
5175<dt><b>author</b></dt>
5176<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given string.</dd>
5177<dt><b>committer</b></dt>
5178<dd>Name and e-mail of the committer and date of commit will be scanned for the given string.</dd>
5179EOT
5180        my ($have_pickaxe) = gitweb_check_feature('pickaxe');
5181        if ($have_pickaxe) {
5182                print <<EOT;
5183<dt><b>pickaxe</b></dt>
5184<dd>All commits that caused the string to appear or disappear from any file (changes that
5185added, removed or "modified" the string) will be listed. This search can take a while and
5186takes a lot of strain on the server, so please use it wisely.</dd>
5187EOT
5188        }
5189        print "</dl>\n";
5190        git_footer_html();
5191}
5192
5193sub git_shortlog {
5194        my $head = git_get_head_hash($project);
5195        if (!defined $hash) {
5196                $hash = $head;
5197        }
5198        if (!defined $page) {
5199                $page = 0;
5200        }
5201        my $refs = git_get_references();
5202
5203        my @commitlist = parse_commits($hash, 101, (100 * $page));
5204
5205        my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, (100 * ($page+1)));
5206        my $next_link = '';
5207        if ($#commitlist >= 100) {
5208                $next_link =
5209                        $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
5210                                 -accesskey => "n", -title => "Alt-n"}, "next");
5211        }
5212
5213        git_header_html();
5214        git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
5215        git_print_header_div('summary', $project);
5216
5217        git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
5218
5219        git_footer_html();
5220}
5221
5222## ......................................................................
5223## feeds (RSS, Atom; OPML)
5224
5225sub git_feed {
5226        my $format = shift || 'atom';
5227        my ($have_blame) = gitweb_check_feature('blame');
5228
5229        # Atom: http://www.atomenabled.org/developers/syndication/
5230        # RSS:  http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
5231        if ($format ne 'rss' && $format ne 'atom') {
5232                die_error(undef, "Unknown web feed format");
5233        }
5234
5235        # log/feed of current (HEAD) branch, log of given branch, history of file/directory
5236        my $head = $hash || 'HEAD';
5237        my @commitlist = parse_commits($head, 150);
5238
5239        my %latest_commit;
5240        my %latest_date;
5241        my $content_type = "application/$format+xml";
5242        if (defined $cgi->http('HTTP_ACCEPT') &&
5243                 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
5244                # browser (feed reader) prefers text/xml
5245                $content_type = 'text/xml';
5246        }
5247        if (defined($commitlist[0])) {
5248                %latest_commit = %{$commitlist[0]};
5249                %latest_date   = parse_date($latest_commit{'author_epoch'});
5250                print $cgi->header(
5251                        -type => $content_type,
5252                        -charset => 'utf-8',
5253                        -last_modified => $latest_date{'rfc2822'});
5254        } else {
5255                print $cgi->header(
5256                        -type => $content_type,
5257                        -charset => 'utf-8');
5258        }
5259
5260        # Optimization: skip generating the body if client asks only
5261        # for Last-Modified date.
5262        return if ($cgi->request_method() eq 'HEAD');
5263
5264        # header variables
5265        my $title = "$site_name - $project/$action";
5266        my $feed_type = 'log';
5267        if (defined $hash) {
5268                $title .= " - '$hash'";
5269                $feed_type = 'branch log';
5270                if (defined $file_name) {
5271                        $title .= " :: $file_name";
5272                        $feed_type = 'history';
5273                }
5274        } elsif (defined $file_name) {
5275                $title .= " - $file_name";
5276                $feed_type = 'history';
5277        }
5278        $title .= " $feed_type";
5279        my $descr = git_get_project_description($project);
5280        if (defined $descr) {
5281                $descr = esc_html($descr);
5282        } else {
5283                $descr = "$project " .
5284                         ($format eq 'rss' ? 'RSS' : 'Atom') .
5285                         " feed";
5286        }
5287        my $owner = git_get_project_owner($project);
5288        $owner = esc_html($owner);
5289
5290        #header
5291        my $alt_url;
5292        if (defined $file_name) {
5293                $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
5294        } elsif (defined $hash) {
5295                $alt_url = href(-full=>1, action=>"log", hash=>$hash);
5296        } else {
5297                $alt_url = href(-full=>1, action=>"summary");
5298        }
5299        print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
5300        if ($format eq 'rss') {
5301                print <<XML;
5302<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
5303<channel>
5304XML
5305                print "<title>$title</title>\n" .
5306                      "<link>$alt_url</link>\n" .
5307                      "<description>$descr</description>\n" .
5308                      "<language>en</language>\n";
5309        } elsif ($format eq 'atom') {
5310                print <<XML;
5311<feed xmlns="http://www.w3.org/2005/Atom">
5312XML
5313                print "<title>$title</title>\n" .
5314                      "<subtitle>$descr</subtitle>\n" .
5315                      '<link rel="alternate" type="text/html" href="' .
5316                      $alt_url . '" />' . "\n" .
5317                      '<link rel="self" type="' . $content_type . '" href="' .
5318                      $cgi->self_url() . '" />' . "\n" .
5319                      "<id>" . href(-full=>1) . "</id>\n" .
5320                      # use project owner for feed author
5321                      "<author><name>$owner</name></author>\n";
5322                if (defined $favicon) {
5323                        print "<icon>" . esc_url($favicon) . "</icon>\n";
5324                }
5325                if (defined $logo_url) {
5326                        # not twice as wide as tall: 72 x 27 pixels
5327                        print "<logo>" . esc_url($logo) . "</logo>\n";
5328                }
5329                if (! %latest_date) {
5330                        # dummy date to keep the feed valid until commits trickle in:
5331                        print "<updated>1970-01-01T00:00:00Z</updated>\n";
5332                } else {
5333                        print "<updated>$latest_date{'iso-8601'}</updated>\n";
5334                }
5335        }
5336
5337        # contents
5338        for (my $i = 0; $i <= $#commitlist; $i++) {
5339                my %co = %{$commitlist[$i]};
5340                my $commit = $co{'id'};
5341                # we read 150, we always show 30 and the ones more recent than 48 hours
5342                if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
5343                        last;
5344                }
5345                my %cd = parse_date($co{'author_epoch'});
5346
5347                # get list of changed files
5348                open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5349                        $co{'parent'} || "--root",
5350                        $co{'id'}, "--", (defined $file_name ? $file_name : ())
5351                        or next;
5352                my @difftree = map { chomp; $_ } <$fd>;
5353                close $fd
5354                        or next;
5355
5356                # print element (entry, item)
5357                my $co_url = href(-full=>1, action=>"commit", hash=>$commit);
5358                if ($format eq 'rss') {
5359                        print "<item>\n" .
5360                              "<title>" . esc_html($co{'title'}) . "</title>\n" .
5361                              "<author>" . esc_html($co{'author'}) . "</author>\n" .
5362                              "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
5363                              "<guid isPermaLink=\"true\">$co_url</guid>\n" .
5364                              "<link>$co_url</link>\n" .
5365                              "<description>" . esc_html($co{'title'}) . "</description>\n" .
5366                              "<content:encoded>" .
5367                              "<![CDATA[\n";
5368                } elsif ($format eq 'atom') {
5369                        print "<entry>\n" .
5370                              "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
5371                              "<updated>$cd{'iso-8601'}</updated>\n" .
5372                              "<author>\n" .
5373                              "  <name>" . esc_html($co{'author_name'}) . "</name>\n";
5374                        if ($co{'author_email'}) {
5375                                print "  <email>" . esc_html($co{'author_email'}) . "</email>\n";
5376                        }
5377                        print "</author>\n" .
5378                              # use committer for contributor
5379                              "<contributor>\n" .
5380                              "  <name>" . esc_html($co{'committer_name'}) . "</name>\n";
5381                        if ($co{'committer_email'}) {
5382                                print "  <email>" . esc_html($co{'committer_email'}) . "</email>\n";
5383                        }
5384                        print "</contributor>\n" .
5385                              "<published>$cd{'iso-8601'}</published>\n" .
5386                              "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
5387                              "<id>$co_url</id>\n" .
5388                              "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
5389                              "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
5390                }
5391                my $comment = $co{'comment'};
5392                print "<pre>\n";
5393                foreach my $line (@$comment) {
5394                        $line = esc_html($line);
5395                        print "$line\n";
5396                }
5397                print "</pre><ul>\n";
5398                foreach my $difftree_line (@difftree) {
5399                        my %difftree = parse_difftree_raw_line($difftree_line);
5400                        next if !$difftree{'from_id'};
5401
5402                        my $file = $difftree{'file'} || $difftree{'to_file'};
5403
5404                        print "<li>" .
5405                              "[" .
5406                              $cgi->a({-href => href(-full=>1, action=>"blobdiff",
5407                                                     hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
5408                                                     hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
5409                                                     file_name=>$file, file_parent=>$difftree{'from_file'}),
5410                                      -title => "diff"}, 'D');
5411                        if ($have_blame) {
5412                                print $cgi->a({-href => href(-full=>1, action=>"blame",
5413                                                             file_name=>$file, hash_base=>$commit),
5414                                              -title => "blame"}, 'B');
5415                        }
5416                        # if this is not a feed of a file history
5417                        if (!defined $file_name || $file_name ne $file) {
5418                                print $cgi->a({-href => href(-full=>1, action=>"history",
5419                                                             file_name=>$file, hash=>$commit),
5420                                              -title => "history"}, 'H');
5421                        }
5422                        $file = esc_path($file);
5423                        print "] ".
5424                              "$file</li>\n";
5425                }
5426                if ($format eq 'rss') {
5427                        print "</ul>]]>\n" .
5428                              "</content:encoded>\n" .
5429                              "</item>\n";
5430                } elsif ($format eq 'atom') {
5431                        print "</ul>\n</div>\n" .
5432                              "</content>\n" .
5433                              "</entry>\n";
5434                }
5435        }
5436
5437        # end of feed
5438        if ($format eq 'rss') {
5439                print "</channel>\n</rss>\n";
5440        }       elsif ($format eq 'atom') {
5441                print "</feed>\n";
5442        }
5443}
5444
5445sub git_rss {
5446        git_feed('rss');
5447}
5448
5449sub git_atom {
5450        git_feed('atom');
5451}
5452
5453sub git_opml {
5454        my @list = git_get_projects_list();
5455
5456        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
5457        print <<XML;
5458<?xml version="1.0" encoding="utf-8"?>
5459<opml version="1.0">
5460<head>
5461  <title>$site_name OPML Export</title>
5462</head>
5463<body>
5464<outline text="git RSS feeds">
5465XML
5466
5467        foreach my $pr (@list) {
5468                my %proj = %$pr;
5469                my $head = git_get_head_hash($proj{'path'});
5470                if (!defined $head) {
5471                        next;
5472                }
5473                $git_dir = "$projectroot/$proj{'path'}";
5474                my %co = parse_commit($head);
5475                if (!%co) {
5476                        next;
5477                }
5478
5479                my $path = esc_html(chop_str($proj{'path'}, 25, 5));
5480                my $rss  = "$my_url?p=$proj{'path'};a=rss";
5481                my $html = "$my_url?p=$proj{'path'};a=summary";
5482                print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
5483        }
5484        print <<XML;
5485</outline>
5486</body>
5487</opml>
5488XML
5489}