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