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