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