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