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