gitweb / gitweb.perlon commit Merge branch 'master' into lj/refs (2958d9b)
   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
  21our $cgi = new CGI;
  22our $version = "++GIT_VERSION++";
  23our $my_url = $cgi->url();
  24our $my_uri = $cgi->url(-absolute => 1);
  25
  26# core git executable to use
  27# this can just be "git" if your webserver has a sensible PATH
  28our $GIT = "++GIT_BINDIR++/git";
  29
  30# absolute fs-path which will be prepended to the project path
  31#our $projectroot = "/pub/scm";
  32our $projectroot = "++GITWEB_PROJECTROOT++";
  33
  34# target of the home link on top of all pages
  35our $home_link = $my_uri || "/";
  36
  37# string of the home link on top of all pages
  38our $home_link_str = "++GITWEB_HOME_LINK_STR++";
  39
  40# name of your site or organization to appear in page titles
  41# replace this with something more descriptive for clearer bookmarks
  42our $site_name = "++GITWEB_SITENAME++" || $ENV{'SERVER_NAME'} || "Untitled";
  43
  44# html text to include at home page
  45our $home_text = "++GITWEB_HOMETEXT++";
  46
  47# URI of default stylesheet
  48our $stylesheet = "++GITWEB_CSS++";
  49# URI of GIT logo
  50our $logo = "++GITWEB_LOGO++";
  51# URI of GIT favicon, assumed to be image/png type
  52our $favicon = "++GITWEB_FAVICON++";
  53
  54# source of projects list
  55our $projects_list = "++GITWEB_LIST++";
  56
  57# show repository only if this file exists
  58# (only effective if this variable evaluates to true)
  59our $export_ok = "++GITWEB_EXPORT_OK++";
  60
  61# only allow viewing of repositories also shown on the overview page
  62our $strict_export = "++GITWEB_STRICT_EXPORT++";
  63
  64# list of git base URLs used for URL to where fetch project from,
  65# i.e. full URL is "$git_base_url/$project"
  66our @git_base_url_list = ("++GITWEB_BASE_URL++");
  67
  68# default blob_plain mimetype and default charset for text/plain blob
  69our $default_blob_plain_mimetype = 'text/plain';
  70our $default_text_plain_charset  = undef;
  71
  72# file to use for guessing MIME types before trying /etc/mime.types
  73# (relative to the current git repository)
  74our $mimetypes_file = undef;
  75
  76# You define site-wide feature defaults here; override them with
  77# $GITWEB_CONFIG as necessary.
  78our %feature = (
  79        # feature => {
  80        #       'sub' => feature-sub (subroutine),
  81        #       'override' => allow-override (boolean),
  82        #       'default' => [ default options...] (array reference)}
  83        #
  84        # if feature is overridable (it means that allow-override has true value,
  85        # then feature-sub will be called with default options as parameters;
  86        # return value of feature-sub indicates if to enable specified feature
  87        #
  88        # use gitweb_check_feature(<feature>) to check if <feature> is enabled
  89
  90        'blame' => {
  91                'sub' => \&feature_blame,
  92                'override' => 0,
  93                'default' => [0]},
  94
  95        'snapshot' => {
  96                'sub' => \&feature_snapshot,
  97                'override' => 0,
  98                #         => [content-encoding, suffix, program]
  99                'default' => ['x-gzip', 'gz', 'gzip']},
 100
 101        'pickaxe' => {
 102                'sub' => \&feature_pickaxe,
 103                'override' => 0,
 104                'default' => [1]},
 105);
 106
 107sub gitweb_check_feature {
 108        my ($name) = @_;
 109        return undef unless exists $feature{$name};
 110        my ($sub, $override, @defaults) = (
 111                $feature{$name}{'sub'},
 112                $feature{$name}{'override'},
 113                @{$feature{$name}{'default'}});
 114        if (!$override) { return @defaults; }
 115        return $sub->(@defaults);
 116}
 117
 118# To enable system wide have in $GITWEB_CONFIG
 119# $feature{'blame'}{'default'} = [1];
 120# To have project specific config enable override in $GITWEB_CONFIG
 121# $feature{'blame'}{'override'} = 1;
 122# and in project config gitweb.blame = 0|1;
 123
 124sub feature_blame {
 125        my ($val) = git_get_project_config('blame', '--bool');
 126
 127        if ($val eq 'true') {
 128                return 1;
 129        } elsif ($val eq 'false') {
 130                return 0;
 131        }
 132
 133        return $_[0];
 134}
 135
 136# To disable system wide have in $GITWEB_CONFIG
 137# $feature{'snapshot'}{'default'} = [undef];
 138# To have project specific config enable override in $GITWEB_CONFIG
 139# $feature{'blame'}{'override'} = 1;
 140# and in project config  gitweb.snapshot = none|gzip|bzip2
 141
 142sub feature_snapshot {
 143        my ($ctype, $suffix, $command) = @_;
 144
 145        my ($val) = git_get_project_config('snapshot');
 146
 147        if ($val eq 'gzip') {
 148                return ('x-gzip', 'gz', 'gzip');
 149        } elsif ($val eq 'bzip2') {
 150                return ('x-bzip2', 'bz2', 'bzip2');
 151        } elsif ($val eq 'none') {
 152                return ();
 153        }
 154
 155        return ($ctype, $suffix, $command);
 156}
 157
 158# To enable system wide have in $GITWEB_CONFIG
 159# $feature{'pickaxe'}{'default'} = [1];
 160# To have project specific config enable override in $GITWEB_CONFIG
 161# $feature{'pickaxe'}{'override'} = 1;
 162# and in project config gitweb.pickaxe = 0|1;
 163
 164sub feature_pickaxe {
 165        my ($val) = git_get_project_config('pickaxe', '--bool');
 166
 167        if ($val eq 'true') {
 168                return (1);
 169        } elsif ($val eq 'false') {
 170                return (0);
 171        }
 172
 173        return ($_[0]);
 174}
 175
 176# rename detection options for git-diff and git-diff-tree
 177# - default is '-M', with the cost proportional to
 178#   (number of removed files) * (number of new files).
 179# - more costly is '-C' (or '-C', '-M'), with the cost proportional to
 180#   (number of changed files + number of removed files) * (number of new files)
 181# - even more costly is '-C', '--find-copies-harder' with cost
 182#   (number of files in the original tree) * (number of new files)
 183# - one might want to include '-B' option, e.g. '-B', '-M'
 184our @diff_opts = ('-M'); # taken from git_commit
 185
 186our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
 187do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
 188
 189# version of the core git binary
 190our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
 191
 192$projects_list ||= $projectroot;
 193
 194# ======================================================================
 195# input validation and dispatch
 196our $action = $cgi->param('a');
 197if (defined $action) {
 198        if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
 199                die_error(undef, "Invalid action parameter");
 200        }
 201}
 202
 203our $project = $cgi->param('p');
 204if (defined $project) {
 205        if (!validate_input($project) ||
 206            !(-d "$projectroot/$project") ||
 207            !(-e "$projectroot/$project/HEAD") ||
 208            ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
 209            ($strict_export && !project_in_list($project))) {
 210                undef $project;
 211                die_error(undef, "No such project");
 212        }
 213}
 214
 215# We have to handle those containing any characters:
 216our $file_name = $cgi->param('f');
 217our $file_parent = $cgi->param('fp');
 218
 219our $hash = $cgi->param('h');
 220if (defined $hash) {
 221        if (!validate_input($hash)) {
 222                die_error(undef, "Invalid hash parameter");
 223        }
 224}
 225
 226our $hash_parent = $cgi->param('hp');
 227if (defined $hash_parent) {
 228        if (!validate_input($hash_parent)) {
 229                die_error(undef, "Invalid hash parent parameter");
 230        }
 231}
 232
 233our $hash_base = $cgi->param('hb');
 234if (defined $hash_base) {
 235        if (!validate_input($hash_base)) {
 236                die_error(undef, "Invalid hash base parameter");
 237        }
 238}
 239
 240our $hash_parent_base = $cgi->param('hpb');
 241if (defined $hash_parent_base) {
 242        if (!validate_input($hash_parent_base)) {
 243                die_error(undef, "Invalid hash parent base parameter");
 244        }
 245}
 246
 247our $page = $cgi->param('pg');
 248if (defined $page) {
 249        if ($page =~ m/[^0-9]/) {
 250                die_error(undef, "Invalid page parameter");
 251        }
 252}
 253
 254our $searchtext = $cgi->param('s');
 255if (defined $searchtext) {
 256        if ($searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
 257                die_error(undef, "Invalid search parameter");
 258        }
 259        $searchtext = quotemeta $searchtext;
 260}
 261
 262# now read PATH_INFO and use it as alternative to parameters
 263sub evaluate_path_info {
 264        return if defined $project;
 265        my $path_info = $ENV{"PATH_INFO"};
 266        return if !$path_info;
 267        $path_info =~ s,^/+,,;
 268        return if !$path_info;
 269        # find which part of PATH_INFO is project
 270        $project = $path_info;
 271        $project =~ s,/+$,,;
 272        while ($project && !-e "$projectroot/$project/HEAD") {
 273                $project =~ s,/*[^/]*$,,;
 274        }
 275        # validate project
 276        $project = validate_input($project);
 277        if (!$project ||
 278            ($export_ok && !-e "$projectroot/$project/$export_ok") ||
 279            ($strict_export && !project_in_list($project))) {
 280                undef $project;
 281                return;
 282        }
 283        # do not change any parameters if an action is given using the query string
 284        return if $action;
 285        $path_info =~ s,^$project/*,,;
 286        my ($refname, $pathname) = split(/:/, $path_info, 2);
 287        if (defined $pathname) {
 288                # we got "project.git/branch:filename" or "project.git/branch:dir/"
 289                # we could use git_get_type(branch:pathname), but it needs $git_dir
 290                $pathname =~ s,^/+,,;
 291                if (!$pathname || substr($pathname, -1) eq "/") {
 292                        $action  ||= "tree";
 293                        $pathname =~ s,/$,,;
 294                } else {
 295                        $action  ||= "blob_plain";
 296                }
 297                $hash_base ||= validate_input($refname);
 298                $file_name ||= $pathname;
 299        } elsif (defined $refname) {
 300                # we got "project.git/branch"
 301                $action ||= "shortlog";
 302                $hash   ||= validate_input($refname);
 303        }
 304}
 305evaluate_path_info();
 306
 307# path to the current git repository
 308our $git_dir;
 309$git_dir = "$projectroot/$project" if $project;
 310
 311# dispatch
 312my %actions = (
 313        "blame" => \&git_blame2,
 314        "blobdiff" => \&git_blobdiff,
 315        "blobdiff_plain" => \&git_blobdiff_plain,
 316        "blob" => \&git_blob,
 317        "blob_plain" => \&git_blob_plain,
 318        "commitdiff" => \&git_commitdiff,
 319        "commitdiff_plain" => \&git_commitdiff_plain,
 320        "commit" => \&git_commit,
 321        "heads" => \&git_heads,
 322        "history" => \&git_history,
 323        "log" => \&git_log,
 324        "rss" => \&git_rss,
 325        "search" => \&git_search,
 326        "shortlog" => \&git_shortlog,
 327        "summary" => \&git_summary,
 328        "tag" => \&git_tag,
 329        "tags" => \&git_tags,
 330        "tree" => \&git_tree,
 331        "snapshot" => \&git_snapshot,
 332        # those below don't need $project
 333        "opml" => \&git_opml,
 334        "project_list" => \&git_project_list,
 335        "project_index" => \&git_project_index,
 336);
 337
 338if (defined $project) {
 339        $action ||= 'summary';
 340} else {
 341        $action ||= 'project_list';
 342}
 343if (!defined($actions{$action})) {
 344        die_error(undef, "Unknown action");
 345}
 346if ($action !~ m/^(opml|project_list|project_index)$/ &&
 347    !$project) {
 348        die_error(undef, "Project needed");
 349}
 350$actions{$action}->();
 351exit;
 352
 353## ======================================================================
 354## action links
 355
 356sub href(%) {
 357        my %params = @_;
 358
 359        my @mapping = (
 360                project => "p",
 361                action => "a",
 362                file_name => "f",
 363                file_parent => "fp",
 364                hash => "h",
 365                hash_parent => "hp",
 366                hash_base => "hb",
 367                hash_parent_base => "hpb",
 368                page => "pg",
 369                order => "o",
 370                searchtext => "s",
 371        );
 372        my %mapping = @mapping;
 373
 374        $params{'project'} = $project unless exists $params{'project'};
 375
 376        my @result = ();
 377        for (my $i = 0; $i < @mapping; $i += 2) {
 378                my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
 379                if (defined $params{$name}) {
 380                        push @result, $symbol . "=" . esc_param($params{$name});
 381                }
 382        }
 383        return "$my_uri?" . join(';', @result);
 384}
 385
 386
 387## ======================================================================
 388## validation, quoting/unquoting and escaping
 389
 390sub validate_input {
 391        my $input = shift;
 392
 393        if ($input =~ m/^[0-9a-fA-F]{40}$/) {
 394                return $input;
 395        }
 396        if ($input =~ m/(^|\/)(|\.|\.\.)($|\/)/) {
 397                return undef;
 398        }
 399        if ($input =~ m/[^a-zA-Z0-9_\x80-\xff\ \t\.\/\-\+\#\~\%]/) {
 400                return undef;
 401        }
 402        return $input;
 403}
 404
 405# quote unsafe chars, but keep the slash, even when it's not
 406# correct, but quoted slashes look too horrible in bookmarks
 407sub esc_param {
 408        my $str = shift;
 409        $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
 410        $str =~ s/\+/%2B/g;
 411        $str =~ s/ /\+/g;
 412        return $str;
 413}
 414
 415# replace invalid utf8 character with SUBSTITUTION sequence
 416sub esc_html {
 417        my $str = shift;
 418        $str = decode("utf8", $str, Encode::FB_DEFAULT);
 419        $str = escapeHTML($str);
 420        $str =~ s/\014/^L/g; # escape FORM FEED (FF) character (e.g. in COPYING file)
 421        return $str;
 422}
 423
 424# git may return quoted and escaped filenames
 425sub unquote {
 426        my $str = shift;
 427        if ($str =~ m/^"(.*)"$/) {
 428                $str = $1;
 429                $str =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
 430        }
 431        return $str;
 432}
 433
 434# escape tabs (convert tabs to spaces)
 435sub untabify {
 436        my $line = shift;
 437
 438        while ((my $pos = index($line, "\t")) != -1) {
 439                if (my $count = (8 - ($pos % 8))) {
 440                        my $spaces = ' ' x $count;
 441                        $line =~ s/\t/$spaces/;
 442                }
 443        }
 444
 445        return $line;
 446}
 447
 448sub project_in_list {
 449        my $project = shift;
 450        my @list = git_get_projects_list();
 451        return @list && scalar(grep { $_->{'path'} eq $project } @list);
 452}
 453
 454## ----------------------------------------------------------------------
 455## HTML aware string manipulation
 456
 457sub chop_str {
 458        my $str = shift;
 459        my $len = shift;
 460        my $add_len = shift || 10;
 461
 462        # allow only $len chars, but don't cut a word if it would fit in $add_len
 463        # if it doesn't fit, cut it if it's still longer than the dots we would add
 464        $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
 465        my $body = $1;
 466        my $tail = $2;
 467        if (length($tail) > 4) {
 468                $tail = " ...";
 469                $body =~ s/&[^;]*$//; # remove chopped character entities
 470        }
 471        return "$body$tail";
 472}
 473
 474## ----------------------------------------------------------------------
 475## functions returning short strings
 476
 477# CSS class for given age value (in seconds)
 478sub age_class {
 479        my $age = shift;
 480
 481        if ($age < 60*60*2) {
 482                return "age0";
 483        } elsif ($age < 60*60*24*2) {
 484                return "age1";
 485        } else {
 486                return "age2";
 487        }
 488}
 489
 490# convert age in seconds to "nn units ago" string
 491sub age_string {
 492        my $age = shift;
 493        my $age_str;
 494
 495        if ($age > 60*60*24*365*2) {
 496                $age_str = (int $age/60/60/24/365);
 497                $age_str .= " years ago";
 498        } elsif ($age > 60*60*24*(365/12)*2) {
 499                $age_str = int $age/60/60/24/(365/12);
 500                $age_str .= " months ago";
 501        } elsif ($age > 60*60*24*7*2) {
 502                $age_str = int $age/60/60/24/7;
 503                $age_str .= " weeks ago";
 504        } elsif ($age > 60*60*24*2) {
 505                $age_str = int $age/60/60/24;
 506                $age_str .= " days ago";
 507        } elsif ($age > 60*60*2) {
 508                $age_str = int $age/60/60;
 509                $age_str .= " hours ago";
 510        } elsif ($age > 60*2) {
 511                $age_str = int $age/60;
 512                $age_str .= " min ago";
 513        } elsif ($age > 2) {
 514                $age_str = int $age;
 515                $age_str .= " sec ago";
 516        } else {
 517                $age_str .= " right now";
 518        }
 519        return $age_str;
 520}
 521
 522# convert file mode in octal to symbolic file mode string
 523sub mode_str {
 524        my $mode = oct shift;
 525
 526        if (S_ISDIR($mode & S_IFMT)) {
 527                return 'drwxr-xr-x';
 528        } elsif (S_ISLNK($mode)) {
 529                return 'lrwxrwxrwx';
 530        } elsif (S_ISREG($mode)) {
 531                # git cares only about the executable bit
 532                if ($mode & S_IXUSR) {
 533                        return '-rwxr-xr-x';
 534                } else {
 535                        return '-rw-r--r--';
 536                };
 537        } else {
 538                return '----------';
 539        }
 540}
 541
 542# convert file mode in octal to file type string
 543sub file_type {
 544        my $mode = shift;
 545
 546        if ($mode !~ m/^[0-7]+$/) {
 547                return $mode;
 548        } else {
 549                $mode = oct $mode;
 550        }
 551
 552        if (S_ISDIR($mode & S_IFMT)) {
 553                return "directory";
 554        } elsif (S_ISLNK($mode)) {
 555                return "symlink";
 556        } elsif (S_ISREG($mode)) {
 557                return "file";
 558        } else {
 559                return "unknown";
 560        }
 561}
 562
 563## ----------------------------------------------------------------------
 564## functions returning short HTML fragments, or transforming HTML fragments
 565## which don't beling to other sections
 566
 567# format line of commit message or tag comment
 568sub format_log_line_html {
 569        my $line = shift;
 570
 571        $line = esc_html($line);
 572        $line =~ s/ /&nbsp;/g;
 573        if ($line =~ m/([0-9a-fA-F]{40})/) {
 574                my $hash_text = $1;
 575                if (git_get_type($hash_text) eq "commit") {
 576                        my $link =
 577                                $cgi->a({-href => href(action=>"commit", hash=>$hash_text),
 578                                        -class => "text"}, $hash_text);
 579                        $line =~ s/$hash_text/$link/;
 580                }
 581        }
 582        return $line;
 583}
 584
 585# format marker of refs pointing to given object
 586sub format_ref_marker {
 587        my ($refs, $id) = @_;
 588        my $markers = '';
 589
 590        if (defined $refs->{$id}) {
 591                foreach my $ref (@{$refs->{$id}}) {
 592                        my ($type, $name) = qw();
 593                        # e.g. tags/v2.6.11 or heads/next
 594                        if ($ref =~ m!^(.*?)s?/(.*)$!) {
 595                                $type = $1;
 596                                $name = $2;
 597                        } else {
 598                                $type = "ref";
 599                                $name = $ref;
 600                        }
 601
 602                        $markers .= " <span class=\"$type\">" . esc_html($name) . "</span>";
 603                }
 604        }
 605
 606        if ($markers) {
 607                return ' <span class="refs">'. $markers . '</span>';
 608        } else {
 609                return "";
 610        }
 611}
 612
 613# format, perhaps shortened and with markers, title line
 614sub format_subject_html {
 615        my ($long, $short, $href, $extra) = @_;
 616        $extra = '' unless defined($extra);
 617
 618        if (length($short) < length($long)) {
 619                return $cgi->a({-href => $href, -class => "list subject",
 620                                -title => decode("utf8", $long, Encode::FB_DEFAULT)},
 621                       esc_html($short) . $extra);
 622        } else {
 623                return $cgi->a({-href => $href, -class => "list subject"},
 624                       esc_html($long)  . $extra);
 625        }
 626}
 627
 628sub format_diff_line {
 629        my $line = shift;
 630        my $char = substr($line, 0, 1);
 631        my $diff_class = "";
 632
 633        chomp $line;
 634
 635        if ($char eq '+') {
 636                $diff_class = " add";
 637        } elsif ($char eq "-") {
 638                $diff_class = " rem";
 639        } elsif ($char eq "@") {
 640                $diff_class = " chunk_header";
 641        } elsif ($char eq "\\") {
 642                $diff_class = " incomplete";
 643        }
 644        $line = untabify($line);
 645        return "<div class=\"diff$diff_class\">" . esc_html($line) . "</div>\n";
 646}
 647
 648## ----------------------------------------------------------------------
 649## git utility subroutines, invoking git commands
 650
 651# returns path to the core git executable and the --git-dir parameter as list
 652sub git_cmd {
 653        return $GIT, '--git-dir='.$git_dir;
 654}
 655
 656# returns path to the core git executable and the --git-dir parameter as string
 657sub git_cmd_str {
 658        return join(' ', git_cmd());
 659}
 660
 661# get HEAD ref of given project as hash
 662sub git_get_head_hash {
 663        my $project = shift;
 664        my $o_git_dir = $git_dir;
 665        my $retval = undef;
 666        $git_dir = "$projectroot/$project";
 667        if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
 668                my $head = <$fd>;
 669                close $fd;
 670                if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
 671                        $retval = $1;
 672                }
 673        }
 674        if (defined $o_git_dir) {
 675                $git_dir = $o_git_dir;
 676        }
 677        return $retval;
 678}
 679
 680# get type of given object
 681sub git_get_type {
 682        my $hash = shift;
 683
 684        open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
 685        my $type = <$fd>;
 686        close $fd or return;
 687        chomp $type;
 688        return $type;
 689}
 690
 691sub git_get_project_config {
 692        my ($key, $type) = @_;
 693
 694        return unless ($key);
 695        $key =~ s/^gitweb\.//;
 696        return if ($key =~ m/\W/);
 697
 698        my @x = (git_cmd(), 'repo-config');
 699        if (defined $type) { push @x, $type; }
 700        push @x, "--get";
 701        push @x, "gitweb.$key";
 702        my $val = qx(@x);
 703        chomp $val;
 704        return ($val);
 705}
 706
 707# get hash of given path at given ref
 708sub git_get_hash_by_path {
 709        my $base = shift;
 710        my $path = shift || return undef;
 711        my $type = shift;
 712
 713        my $tree = $base;
 714
 715        open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
 716                or die_error(undef, "Open git-ls-tree failed");
 717        my $line = <$fd>;
 718        close $fd or return undef;
 719
 720        #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
 721        $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
 722        if (defined $type && $type ne $2) {
 723                # type doesn't match
 724                return undef;
 725        }
 726        return $3;
 727}
 728
 729## ......................................................................
 730## git utility functions, directly accessing git repository
 731
 732sub git_get_project_description {
 733        my $path = shift;
 734
 735        open my $fd, "$projectroot/$path/description" or return undef;
 736        my $descr = <$fd>;
 737        close $fd;
 738        chomp $descr;
 739        return $descr;
 740}
 741
 742sub git_get_project_url_list {
 743        my $path = shift;
 744
 745        open my $fd, "$projectroot/$path/cloneurl" or return;
 746        my @git_project_url_list = map { chomp; $_ } <$fd>;
 747        close $fd;
 748
 749        return wantarray ? @git_project_url_list : \@git_project_url_list;
 750}
 751
 752sub git_get_projects_list {
 753        my @list;
 754
 755        if (-d $projects_list) {
 756                # search in directory
 757                my $dir = $projects_list;
 758                my $pfxlen = length("$dir");
 759
 760                File::Find::find({
 761                        follow_fast => 1, # follow symbolic links
 762                        dangling_symlinks => 0, # ignore dangling symlinks, silently
 763                        wanted => sub {
 764                                # skip project-list toplevel, if we get it.
 765                                return if (m!^[/.]$!);
 766                                # only directories can be git repositories
 767                                return unless (-d $_);
 768
 769                                my $subdir = substr($File::Find::name, $pfxlen + 1);
 770                                # we check related file in $projectroot
 771                                if (-e "$projectroot/$subdir/HEAD" && (!$export_ok ||
 772                                    -e "$projectroot/$subdir/$export_ok")) {
 773                                        push @list, { path => $subdir };
 774                                        $File::Find::prune = 1;
 775                                }
 776                        },
 777                }, "$dir");
 778
 779        } elsif (-f $projects_list) {
 780                # read from file(url-encoded):
 781                # 'git%2Fgit.git Linus+Torvalds'
 782                # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
 783                # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
 784                open my ($fd), $projects_list or return undef;
 785                while (my $line = <$fd>) {
 786                        chomp $line;
 787                        my ($path, $owner) = split ' ', $line;
 788                        $path = unescape($path);
 789                        $owner = unescape($owner);
 790                        if (!defined $path) {
 791                                next;
 792                        }
 793                        if (-e "$projectroot/$path/HEAD" && (!$export_ok ||
 794                            -e "$projectroot/$path/$export_ok")) {
 795                                my $pr = {
 796                                        path => $path,
 797                                        owner => decode("utf8", $owner, Encode::FB_DEFAULT),
 798                                };
 799                                push @list, $pr
 800                        }
 801                }
 802                close $fd;
 803        }
 804        @list = sort {$a->{'path'} cmp $b->{'path'}} @list;
 805        return @list;
 806}
 807
 808sub git_get_project_owner {
 809        my $project = shift;
 810        my $owner;
 811
 812        return undef unless $project;
 813
 814        # read from file (url-encoded):
 815        # 'git%2Fgit.git Linus+Torvalds'
 816        # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
 817        # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
 818        if (-f $projects_list) {
 819                open (my $fd , $projects_list);
 820                while (my $line = <$fd>) {
 821                        chomp $line;
 822                        my ($pr, $ow) = split ' ', $line;
 823                        $pr = unescape($pr);
 824                        $ow = unescape($ow);
 825                        if ($pr eq $project) {
 826                                $owner = decode("utf8", $ow, Encode::FB_DEFAULT);
 827                                last;
 828                        }
 829                }
 830                close $fd;
 831        }
 832        if (!defined $owner) {
 833                $owner = get_file_owner("$projectroot/$project");
 834        }
 835
 836        return $owner;
 837}
 838
 839sub git_get_references {
 840        my $type = shift || "";
 841        my %refs;
 842        # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c      refs/tags/v2.6.11
 843        # c39ae07f393806ccf406ef966e9a15afc43cc36a      refs/tags/v2.6.11^{}
 844        open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
 845                or return;
 846
 847        while (my $line = <$fd>) {
 848                chomp $line;
 849                if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?[^\^]+)/) {
 850                        if (defined $refs{$1}) {
 851                                push @{$refs{$1}}, $2;
 852                        } else {
 853                                $refs{$1} = [ $2 ];
 854                        }
 855                }
 856        }
 857        close $fd or return;
 858        return \%refs;
 859}
 860
 861sub git_get_rev_name_tags {
 862        my $hash = shift || return undef;
 863
 864        open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
 865                or return;
 866        my $name_rev = <$fd>;
 867        close $fd;
 868
 869        if ($name_rev =~ m|^$hash tags/(.*)$|) {
 870                return $1;
 871        } else {
 872                # catches also '$hash undefined' output
 873                return undef;
 874        }
 875}
 876
 877## ----------------------------------------------------------------------
 878## parse to hash functions
 879
 880sub parse_date {
 881        my $epoch = shift;
 882        my $tz = shift || "-0000";
 883
 884        my %date;
 885        my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
 886        my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
 887        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
 888        $date{'hour'} = $hour;
 889        $date{'minute'} = $min;
 890        $date{'mday'} = $mday;
 891        $date{'day'} = $days[$wday];
 892        $date{'month'} = $months[$mon];
 893        $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
 894                           $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
 895        $date{'mday-time'} = sprintf "%d %s %02d:%02d",
 896                             $mday, $months[$mon], $hour ,$min;
 897
 898        $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
 899        my $local = $epoch + ((int $1 + ($2/60)) * 3600);
 900        ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
 901        $date{'hour_local'} = $hour;
 902        $date{'minute_local'} = $min;
 903        $date{'tz_local'} = $tz;
 904        return %date;
 905}
 906
 907sub parse_tag {
 908        my $tag_id = shift;
 909        my %tag;
 910        my @comment;
 911
 912        open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
 913        $tag{'id'} = $tag_id;
 914        while (my $line = <$fd>) {
 915                chomp $line;
 916                if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
 917                        $tag{'object'} = $1;
 918                } elsif ($line =~ m/^type (.+)$/) {
 919                        $tag{'type'} = $1;
 920                } elsif ($line =~ m/^tag (.+)$/) {
 921                        $tag{'name'} = $1;
 922                } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
 923                        $tag{'author'} = $1;
 924                        $tag{'epoch'} = $2;
 925                        $tag{'tz'} = $3;
 926                } elsif ($line =~ m/--BEGIN/) {
 927                        push @comment, $line;
 928                        last;
 929                } elsif ($line eq "") {
 930                        last;
 931                }
 932        }
 933        push @comment, <$fd>;
 934        $tag{'comment'} = \@comment;
 935        close $fd or return;
 936        if (!defined $tag{'name'}) {
 937                return
 938        };
 939        return %tag
 940}
 941
 942sub parse_commit {
 943        my $commit_id = shift;
 944        my $commit_text = shift;
 945
 946        my @commit_lines;
 947        my %co;
 948
 949        if (defined $commit_text) {
 950                @commit_lines = @$commit_text;
 951        } else {
 952                $/ = "\0";
 953                open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", "--max-count=1", $commit_id
 954                        or return;
 955                @commit_lines = split '\n', <$fd>;
 956                close $fd or return;
 957                $/ = "\n";
 958                pop @commit_lines;
 959        }
 960        my $header = shift @commit_lines;
 961        if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
 962                return;
 963        }
 964        ($co{'id'}, my @parents) = split ' ', $header;
 965        $co{'parents'} = \@parents;
 966        $co{'parent'} = $parents[0];
 967        while (my $line = shift @commit_lines) {
 968                last if $line eq "\n";
 969                if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
 970                        $co{'tree'} = $1;
 971                } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
 972                        $co{'author'} = $1;
 973                        $co{'author_epoch'} = $2;
 974                        $co{'author_tz'} = $3;
 975                        if ($co{'author'} =~ m/^([^<]+) </) {
 976                                $co{'author_name'} = $1;
 977                        } else {
 978                                $co{'author_name'} = $co{'author'};
 979                        }
 980                } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
 981                        $co{'committer'} = $1;
 982                        $co{'committer_epoch'} = $2;
 983                        $co{'committer_tz'} = $3;
 984                        $co{'committer_name'} = $co{'committer'};
 985                        $co{'committer_name'} =~ s/ <.*//;
 986                }
 987        }
 988        if (!defined $co{'tree'}) {
 989                return;
 990        };
 991
 992        foreach my $title (@commit_lines) {
 993                $title =~ s/^    //;
 994                if ($title ne "") {
 995                        $co{'title'} = chop_str($title, 80, 5);
 996                        # remove leading stuff of merges to make the interesting part visible
 997                        if (length($title) > 50) {
 998                                $title =~ s/^Automatic //;
 999                                $title =~ s/^merge (of|with) /Merge ... /i;
1000                                if (length($title) > 50) {
1001                                        $title =~ s/(http|rsync):\/\///;
1002                                }
1003                                if (length($title) > 50) {
1004                                        $title =~ s/(master|www|rsync)\.//;
1005                                }
1006                                if (length($title) > 50) {
1007                                        $title =~ s/kernel.org:?//;
1008                                }
1009                                if (length($title) > 50) {
1010                                        $title =~ s/\/pub\/scm//;
1011                                }
1012                        }
1013                        $co{'title_short'} = chop_str($title, 50, 5);
1014                        last;
1015                }
1016        }
1017        # remove added spaces
1018        foreach my $line (@commit_lines) {
1019                $line =~ s/^    //;
1020        }
1021        $co{'comment'} = \@commit_lines;
1022
1023        my $age = time - $co{'committer_epoch'};
1024        $co{'age'} = $age;
1025        $co{'age_string'} = age_string($age);
1026        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1027        if ($age > 60*60*24*7*2) {
1028                $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1029                $co{'age_string_age'} = $co{'age_string'};
1030        } else {
1031                $co{'age_string_date'} = $co{'age_string'};
1032                $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1033        }
1034        return %co;
1035}
1036
1037# parse ref from ref_file, given by ref_id, with given type
1038sub parse_ref {
1039        my $ref_file = shift;
1040        my $ref_id = shift;
1041        my $type = shift || git_get_type($ref_id);
1042        my %ref_item;
1043
1044        $ref_item{'type'} = $type;
1045        $ref_item{'id'} = $ref_id;
1046        $ref_item{'epoch'} = 0;
1047        $ref_item{'age'} = "unknown";
1048        if ($type eq "tag") {
1049                my %tag = parse_tag($ref_id);
1050                $ref_item{'comment'} = $tag{'comment'};
1051                if ($tag{'type'} eq "commit") {
1052                        my %co = parse_commit($tag{'object'});
1053                        $ref_item{'epoch'} = $co{'committer_epoch'};
1054                        $ref_item{'age'} = $co{'age_string'};
1055                } elsif (defined($tag{'epoch'})) {
1056                        my $age = time - $tag{'epoch'};
1057                        $ref_item{'epoch'} = $tag{'epoch'};
1058                        $ref_item{'age'} = age_string($age);
1059                }
1060                $ref_item{'reftype'} = $tag{'type'};
1061                $ref_item{'name'} = $tag{'name'};
1062                $ref_item{'refid'} = $tag{'object'};
1063        } elsif ($type eq "commit"){
1064                my %co = parse_commit($ref_id);
1065                $ref_item{'reftype'} = "commit";
1066                $ref_item{'name'} = $ref_file;
1067                $ref_item{'title'} = $co{'title'};
1068                $ref_item{'refid'} = $ref_id;
1069                $ref_item{'epoch'} = $co{'committer_epoch'};
1070                $ref_item{'age'} = $co{'age_string'};
1071        } else {
1072                $ref_item{'reftype'} = $type;
1073                $ref_item{'name'} = $ref_file;
1074                $ref_item{'refid'} = $ref_id;
1075        }
1076
1077        return %ref_item;
1078}
1079
1080# parse line of git-diff-tree "raw" output
1081sub parse_difftree_raw_line {
1082        my $line = shift;
1083        my %res;
1084
1085        # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1086        # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1087        if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1088                $res{'from_mode'} = $1;
1089                $res{'to_mode'} = $2;
1090                $res{'from_id'} = $3;
1091                $res{'to_id'} = $4;
1092                $res{'status'} = $5;
1093                $res{'similarity'} = $6;
1094                if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1095                        ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1096                } else {
1097                        $res{'file'} = unquote($7);
1098                }
1099        }
1100        # 'c512b523472485aef4fff9e57b229d9d243c967f'
1101        elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1102                $res{'commit'} = $1;
1103        }
1104
1105        return wantarray ? %res : \%res;
1106}
1107
1108# parse line of git-ls-tree output
1109sub parse_ls_tree_line ($;%) {
1110        my $line = shift;
1111        my %opts = @_;
1112        my %res;
1113
1114        #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1115        $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
1116
1117        $res{'mode'} = $1;
1118        $res{'type'} = $2;
1119        $res{'hash'} = $3;
1120        if ($opts{'-z'}) {
1121                $res{'name'} = $4;
1122        } else {
1123                $res{'name'} = unquote($4);
1124        }
1125
1126        return wantarray ? %res : \%res;
1127}
1128
1129## ......................................................................
1130## parse to array of hashes functions
1131
1132sub git_get_refs_list {
1133        my $type = shift || "";
1134        my %refs;
1135        my @reflist;
1136
1137        my @refs;
1138        open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
1139                or return;
1140        while (my $line = <$fd>) {
1141                chomp $line;
1142                if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?([^\^]+))(\^\{\})?$/) {
1143                        if (defined $refs{$1}) {
1144                                push @{$refs{$1}}, $2;
1145                        } else {
1146                                $refs{$1} = [ $2 ];
1147                        }
1148
1149                        if (! $4) { # unpeeled, direct reference
1150                                push @refs, { hash => $1, name => $3 }; # without type
1151                        } elsif ($3 eq $refs[-1]{'name'}) {
1152                                # most likely a tag is followed by its peeled
1153                                # (deref) one, and when that happens we know the
1154                                # previous one was of type 'tag'.
1155                                $refs[-1]{'type'} = "tag";
1156                        }
1157                }
1158        }
1159        close $fd;
1160
1161        foreach my $ref (@refs) {
1162                my $ref_file = $ref->{'name'};
1163                my $ref_id   = $ref->{'hash'};
1164
1165                my $type = $ref->{'type'} || git_get_type($ref_id) || next;
1166                my %ref_item = parse_ref($ref_file, $ref_id, $type);
1167
1168                push @reflist, \%ref_item;
1169        }
1170        # sort refs by age
1171        @reflist = sort {$b->{'epoch'} <=> $a->{'epoch'}} @reflist;
1172        return (\@reflist, \%refs);
1173}
1174
1175## ----------------------------------------------------------------------
1176## filesystem-related functions
1177
1178sub get_file_owner {
1179        my $path = shift;
1180
1181        my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1182        my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1183        if (!defined $gcos) {
1184                return undef;
1185        }
1186        my $owner = $gcos;
1187        $owner =~ s/[,;].*$//;
1188        return decode("utf8", $owner, Encode::FB_DEFAULT);
1189}
1190
1191## ......................................................................
1192## mimetype related functions
1193
1194sub mimetype_guess_file {
1195        my $filename = shift;
1196        my $mimemap = shift;
1197        -r $mimemap or return undef;
1198
1199        my %mimemap;
1200        open(MIME, $mimemap) or return undef;
1201        while (<MIME>) {
1202                next if m/^#/; # skip comments
1203                my ($mime, $exts) = split(/\t+/);
1204                if (defined $exts) {
1205                        my @exts = split(/\s+/, $exts);
1206                        foreach my $ext (@exts) {
1207                                $mimemap{$ext} = $mime;
1208                        }
1209                }
1210        }
1211        close(MIME);
1212
1213        $filename =~ /\.([^.]*)$/;
1214        return $mimemap{$1};
1215}
1216
1217sub mimetype_guess {
1218        my $filename = shift;
1219        my $mime;
1220        $filename =~ /\./ or return undef;
1221
1222        if ($mimetypes_file) {
1223                my $file = $mimetypes_file;
1224                if ($file !~ m!^/!) { # if it is relative path
1225                        # it is relative to project
1226                        $file = "$projectroot/$project/$file";
1227                }
1228                $mime = mimetype_guess_file($filename, $file);
1229        }
1230        $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1231        return $mime;
1232}
1233
1234sub blob_mimetype {
1235        my $fd = shift;
1236        my $filename = shift;
1237
1238        if ($filename) {
1239                my $mime = mimetype_guess($filename);
1240                $mime and return $mime;
1241        }
1242
1243        # just in case
1244        return $default_blob_plain_mimetype unless $fd;
1245
1246        if (-T $fd) {
1247                return 'text/plain' .
1248                       ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1249        } elsif (! $filename) {
1250                return 'application/octet-stream';
1251        } elsif ($filename =~ m/\.png$/i) {
1252                return 'image/png';
1253        } elsif ($filename =~ m/\.gif$/i) {
1254                return 'image/gif';
1255        } elsif ($filename =~ m/\.jpe?g$/i) {
1256                return 'image/jpeg';
1257        } else {
1258                return 'application/octet-stream';
1259        }
1260}
1261
1262## ======================================================================
1263## functions printing HTML: header, footer, error page
1264
1265sub git_header_html {
1266        my $status = shift || "200 OK";
1267        my $expires = shift;
1268
1269        my $title = "$site_name git";
1270        if (defined $project) {
1271                $title .= " - $project";
1272                if (defined $action) {
1273                        $title .= "/$action";
1274                        if (defined $file_name) {
1275                                $title .= " - " . esc_html($file_name);
1276                                if ($action eq "tree" && $file_name !~ m|/$|) {
1277                                        $title .= "/";
1278                                }
1279                        }
1280                }
1281        }
1282        my $content_type;
1283        # require explicit support from the UA if we are to send the page as
1284        # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1285        # we have to do this because MSIE sometimes globs '*/*', pretending to
1286        # support xhtml+xml but choking when it gets what it asked for.
1287        if (defined $cgi->http('HTTP_ACCEPT') &&
1288            $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1289            $cgi->Accept('application/xhtml+xml') != 0) {
1290                $content_type = 'application/xhtml+xml';
1291        } else {
1292                $content_type = 'text/html';
1293        }
1294        print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1295                           -status=> $status, -expires => $expires);
1296        print <<EOF;
1297<?xml version="1.0" encoding="utf-8"?>
1298<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1299<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1300<!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1301<!-- git core binaries version $git_version -->
1302<head>
1303<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1304<meta name="generator" content="gitweb/$version git/$git_version"/>
1305<meta name="robots" content="index, nofollow"/>
1306<title>$title</title>
1307<link rel="stylesheet" type="text/css" href="$stylesheet"/>
1308EOF
1309        if (defined $project) {
1310                printf('<link rel="alternate" title="%s log" '.
1311                       'href="%s" type="application/rss+xml"/>'."\n",
1312                       esc_param($project), href(action=>"rss"));
1313        } else {
1314                printf('<link rel="alternate" title="%s projects list" '.
1315                       'href="%s" type="text/plain; charset=utf-8"/>'."\n",
1316                       $site_name, href(project=>undef, action=>"project_index"));
1317                printf('<link rel="alternate" title="%s projects logs" '.
1318                       'href="%s" type="text/x-opml"/>'."\n",
1319                       $site_name, href(project=>undef, action=>"opml"));
1320        }
1321        if (defined $favicon) {
1322                print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1323        }
1324
1325        print "</head>\n" .
1326              "<body>\n" .
1327              "<div class=\"page_header\">\n" .
1328              "<a href=\"http://www.kernel.org/pub/software/scm/git/docs/\" title=\"git documentation\">" .
1329              "<img src=\"$logo\" width=\"72\" height=\"27\" alt=\"git\" style=\"float:right; border-width:0px;\"/>" .
1330              "</a>\n";
1331        print $cgi->a({-href => esc_param($home_link)}, $home_link_str) . " / ";
1332        if (defined $project) {
1333                print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1334                if (defined $action) {
1335                        print " / $action";
1336                }
1337                print "\n";
1338                if (!defined $searchtext) {
1339                        $searchtext = "";
1340                }
1341                my $search_hash;
1342                if (defined $hash_base) {
1343                        $search_hash = $hash_base;
1344                } elsif (defined $hash) {
1345                        $search_hash = $hash;
1346                } else {
1347                        $search_hash = "HEAD";
1348                }
1349                $cgi->param("a", "search");
1350                $cgi->param("h", $search_hash);
1351                print $cgi->startform(-method => "get", -action => $my_uri) .
1352                      "<div class=\"search\">\n" .
1353                      $cgi->hidden(-name => "p") . "\n" .
1354                      $cgi->hidden(-name => "a") . "\n" .
1355                      $cgi->hidden(-name => "h") . "\n" .
1356                      $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1357                      "</div>" .
1358                      $cgi->end_form() . "\n";
1359        }
1360        print "</div>\n";
1361}
1362
1363sub git_footer_html {
1364        print "<div class=\"page_footer\">\n";
1365        if (defined $project) {
1366                my $descr = git_get_project_description($project);
1367                if (defined $descr) {
1368                        print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1369                }
1370                print $cgi->a({-href => href(action=>"rss"),
1371                              -class => "rss_logo"}, "RSS") . "\n";
1372        } else {
1373                print $cgi->a({-href => href(project=>undef, action=>"opml"),
1374                              -class => "rss_logo"}, "OPML") . " ";
1375                print $cgi->a({-href => href(project=>undef, action=>"project_index"),
1376                              -class => "rss_logo"}, "TXT") . "\n";
1377        }
1378        print "</div>\n" .
1379              "</body>\n" .
1380              "</html>";
1381}
1382
1383sub die_error {
1384        my $status = shift || "403 Forbidden";
1385        my $error = shift || "Malformed query, file missing or permission denied";
1386
1387        git_header_html($status);
1388        print <<EOF;
1389<div class="page_body">
1390<br /><br />
1391$status - $error
1392<br />
1393</div>
1394EOF
1395        git_footer_html();
1396        exit;
1397}
1398
1399## ----------------------------------------------------------------------
1400## functions printing or outputting HTML: navigation
1401
1402sub git_print_page_nav {
1403        my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1404        $extra = '' if !defined $extra; # pager or formats
1405
1406        my @navs = qw(summary shortlog log commit commitdiff tree);
1407        if ($suppress) {
1408                @navs = grep { $_ ne $suppress } @navs;
1409        }
1410
1411        my %arg = map { $_ => {action=>$_} } @navs;
1412        if (defined $head) {
1413                for (qw(commit commitdiff)) {
1414                        $arg{$_}{hash} = $head;
1415                }
1416                if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1417                        for (qw(shortlog log)) {
1418                                $arg{$_}{hash} = $head;
1419                        }
1420                }
1421        }
1422        $arg{tree}{hash} = $treehead if defined $treehead;
1423        $arg{tree}{hash_base} = $treebase if defined $treebase;
1424
1425        print "<div class=\"page_nav\">\n" .
1426                (join " | ",
1427                 map { $_ eq $current ?
1428                       $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1429                 } @navs);
1430        print "<br/>\n$extra<br/>\n" .
1431              "</div>\n";
1432}
1433
1434sub format_paging_nav {
1435        my ($action, $hash, $head, $page, $nrevs) = @_;
1436        my $paging_nav;
1437
1438
1439        if ($hash ne $head || $page) {
1440                $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1441        } else {
1442                $paging_nav .= "HEAD";
1443        }
1444
1445        if ($page > 0) {
1446                $paging_nav .= " &sdot; " .
1447                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1448                                 -accesskey => "p", -title => "Alt-p"}, "prev");
1449        } else {
1450                $paging_nav .= " &sdot; prev";
1451        }
1452
1453        if ($nrevs >= (100 * ($page+1)-1)) {
1454                $paging_nav .= " &sdot; " .
1455                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1456                                 -accesskey => "n", -title => "Alt-n"}, "next");
1457        } else {
1458                $paging_nav .= " &sdot; next";
1459        }
1460
1461        return $paging_nav;
1462}
1463
1464## ......................................................................
1465## functions printing or outputting HTML: div
1466
1467sub git_print_header_div {
1468        my ($action, $title, $hash, $hash_base) = @_;
1469        my %args = ();
1470
1471        $args{action} = $action;
1472        $args{hash} = $hash if $hash;
1473        $args{hash_base} = $hash_base if $hash_base;
1474
1475        print "<div class=\"header\">\n" .
1476              $cgi->a({-href => href(%args), -class => "title"},
1477              $title ? $title : $action) .
1478              "\n</div>\n";
1479}
1480
1481#sub git_print_authorship (\%) {
1482sub git_print_authorship {
1483        my $co = shift;
1484
1485        my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
1486        print "<div class=\"author_date\">" .
1487              esc_html($co->{'author_name'}) .
1488              " [$ad{'rfc2822'}";
1489        if ($ad{'hour_local'} < 6) {
1490                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
1491                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1492        } else {
1493                printf(" (%02d:%02d %s)",
1494                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1495        }
1496        print "]</div>\n";
1497}
1498
1499sub git_print_page_path {
1500        my $name = shift;
1501        my $type = shift;
1502        my $hb = shift;
1503
1504        if (!defined $name) {
1505                print "<div class=\"page_path\">/</div>\n";
1506        } else {
1507                my @dirname = split '/', $name;
1508                my $basename = pop @dirname;
1509                my $fullname = '';
1510
1511                print "<div class=\"page_path\">";
1512                print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
1513                              -title => 'tree root'}, "[$project]");
1514                print " / ";
1515                foreach my $dir (@dirname) {
1516                        $fullname .= ($fullname ? '/' : '') . $dir;
1517                        print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
1518                                                     hash_base=>$hb),
1519                                      -title => $fullname}, esc_html($dir));
1520                        print " / ";
1521                }
1522                if (defined $type && $type eq 'blob') {
1523                        print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1524                                                     hash_base=>$hb),
1525                                      -title => $name}, esc_html($basename));
1526                } elsif (defined $type && $type eq 'tree') {
1527                        print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
1528                                                     hash_base=>$hb),
1529                                      -title => $name}, esc_html($basename));
1530                } else {
1531                        print esc_html($basename);
1532                }
1533                print "<br/></div>\n";
1534        }
1535}
1536
1537# sub git_print_log (\@;%) {
1538sub git_print_log ($;%) {
1539        my $log = shift;
1540        my %opts = @_;
1541
1542        if ($opts{'-remove_title'}) {
1543                # remove title, i.e. first line of log
1544                shift @$log;
1545        }
1546        # remove leading empty lines
1547        while (defined $log->[0] && $log->[0] eq "") {
1548                shift @$log;
1549        }
1550
1551        # print log
1552        my $signoff = 0;
1553        my $empty = 0;
1554        foreach my $line (@$log) {
1555                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1556                        $signoff = 1;
1557                        $empty = 0;
1558                        if (! $opts{'-remove_signoff'}) {
1559                                print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1560                                next;
1561                        } else {
1562                                # remove signoff lines
1563                                next;
1564                        }
1565                } else {
1566                        $signoff = 0;
1567                }
1568
1569                # print only one empty line
1570                # do not print empty line after signoff
1571                if ($line eq "") {
1572                        next if ($empty || $signoff);
1573                        $empty = 1;
1574                } else {
1575                        $empty = 0;
1576                }
1577
1578                print format_log_line_html($line) . "<br/>\n";
1579        }
1580
1581        if ($opts{'-final_empty_line'}) {
1582                # end with single empty line
1583                print "<br/>\n" unless $empty;
1584        }
1585}
1586
1587sub git_print_simplified_log {
1588        my $log = shift;
1589        my $remove_title = shift;
1590
1591        git_print_log($log,
1592                -final_empty_line=> 1,
1593                -remove_title => $remove_title);
1594}
1595
1596# print tree entry (row of git_tree), but without encompassing <tr> element
1597sub git_print_tree_entry {
1598        my ($t, $basedir, $hash_base, $have_blame) = @_;
1599
1600        my %base_key = ();
1601        $base_key{hash_base} = $hash_base if defined $hash_base;
1602
1603        print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
1604        if ($t->{'type'} eq "blob") {
1605                print "<td class=\"list\">" .
1606                      $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1607                                             file_name=>"$basedir$t->{'name'}", %base_key),
1608                              -class => "list"}, esc_html($t->{'name'})) .
1609                      "</td>\n" .
1610                      "<td class=\"link\">" .
1611                      $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1612                                             file_name=>"$basedir$t->{'name'}", %base_key)},
1613                              "blob");
1614                if ($have_blame) {
1615                        print " | " .
1616                                $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
1617                                                       file_name=>"$basedir$t->{'name'}", %base_key)},
1618                                        "blame");
1619                }
1620                if (defined $hash_base) {
1621                        print " | " .
1622                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1623                                                     hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
1624                                      "history");
1625                }
1626                print " | " .
1627                      $cgi->a({-href => href(action=>"blob_plain",
1628                                             hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
1629                              "raw") .
1630                      "</td>\n";
1631
1632        } elsif ($t->{'type'} eq "tree") {
1633                print "<td class=\"list\">" .
1634                      $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1635                                             file_name=>"$basedir$t->{'name'}", %base_key)},
1636                              esc_html($t->{'name'})) .
1637                      "</td>\n" .
1638                      "<td class=\"link\">" .
1639                      $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1640                                             file_name=>"$basedir$t->{'name'}", %base_key)},
1641                              "tree");
1642                if (defined $hash_base) {
1643                        print " | " .
1644                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1645                                                     file_name=>"$basedir$t->{'name'}")},
1646                                      "history");
1647                }
1648                print "</td>\n";
1649        }
1650}
1651
1652## ......................................................................
1653## functions printing large fragments of HTML
1654
1655sub git_difftree_body {
1656        my ($difftree, $hash, $parent) = @_;
1657
1658        print "<div class=\"list_head\">\n";
1659        if ($#{$difftree} > 10) {
1660                print(($#{$difftree} + 1) . " files changed:\n");
1661        }
1662        print "</div>\n";
1663
1664        print "<table class=\"diff_tree\">\n";
1665        my $alternate = 0;
1666        my $patchno = 0;
1667        foreach my $line (@{$difftree}) {
1668                my %diff = parse_difftree_raw_line($line);
1669
1670                if ($alternate) {
1671                        print "<tr class=\"dark\">\n";
1672                } else {
1673                        print "<tr class=\"light\">\n";
1674                }
1675                $alternate ^= 1;
1676
1677                my ($to_mode_oct, $to_mode_str, $to_file_type);
1678                my ($from_mode_oct, $from_mode_str, $from_file_type);
1679                if ($diff{'to_mode'} ne ('0' x 6)) {
1680                        $to_mode_oct = oct $diff{'to_mode'};
1681                        if (S_ISREG($to_mode_oct)) { # only for regular file
1682                                $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
1683                        }
1684                        $to_file_type = file_type($diff{'to_mode'});
1685                }
1686                if ($diff{'from_mode'} ne ('0' x 6)) {
1687                        $from_mode_oct = oct $diff{'from_mode'};
1688                        if (S_ISREG($to_mode_oct)) { # only for regular file
1689                                $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
1690                        }
1691                        $from_file_type = file_type($diff{'from_mode'});
1692                }
1693
1694                if ($diff{'status'} eq "A") { # created
1695                        my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
1696                        $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
1697                        $mode_chng   .= "]</span>";
1698                        print "<td>" .
1699                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1700                                                     hash_base=>$hash, file_name=>$diff{'file'}),
1701                                      -class => "list"}, esc_html($diff{'file'})) .
1702                              "</td>\n" .
1703                              "<td>$mode_chng</td>\n" .
1704                              "<td class=\"link\">" .
1705                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1706                                                     hash_base=>$hash, file_name=>$diff{'file'})},
1707                                      "blob");
1708                        if ($action eq 'commitdiff') {
1709                                # link to patch
1710                                $patchno++;
1711                                print " | " .
1712                                      $cgi->a({-href => "#patch$patchno"}, "patch");
1713                        }
1714                        print "</td>\n";
1715
1716                } elsif ($diff{'status'} eq "D") { # deleted
1717                        my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
1718                        print "<td>" .
1719                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1720                                                     hash_base=>$parent, file_name=>$diff{'file'}),
1721                                       -class => "list"}, esc_html($diff{'file'})) .
1722                              "</td>\n" .
1723                              "<td>$mode_chng</td>\n" .
1724                              "<td class=\"link\">" .
1725                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1726                                                     hash_base=>$parent, file_name=>$diff{'file'})},
1727                                      "blob") .
1728                              " | ";
1729                        if ($action eq 'commitdiff') {
1730                                # link to patch
1731                                $patchno++;
1732                                print " | " .
1733                                      $cgi->a({-href => "#patch$patchno"}, "patch");
1734                        }
1735                        print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1736                                                     file_name=>$diff{'file'})},
1737                                      "history") .
1738                              "</td>\n";
1739
1740                } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
1741                        my $mode_chnge = "";
1742                        if ($diff{'from_mode'} != $diff{'to_mode'}) {
1743                                $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
1744                                if ($from_file_type != $to_file_type) {
1745                                        $mode_chnge .= " from $from_file_type to $to_file_type";
1746                                }
1747                                if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
1748                                        if ($from_mode_str && $to_mode_str) {
1749                                                $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
1750                                        } elsif ($to_mode_str) {
1751                                                $mode_chnge .= " mode: $to_mode_str";
1752                                        }
1753                                }
1754                                $mode_chnge .= "]</span>\n";
1755                        }
1756                        print "<td>";
1757                        if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1758                                print $cgi->a({-href => href(action=>"blobdiff",
1759                                                             hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1760                                                             hash_base=>$hash, hash_parent_base=>$parent,
1761                                                             file_name=>$diff{'file'}),
1762                                              -class => "list"}, esc_html($diff{'file'}));
1763                        } else { # only mode changed
1764                                print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1765                                                             hash_base=>$hash, file_name=>$diff{'file'}),
1766                                              -class => "list"}, esc_html($diff{'file'}));
1767                        }
1768                        print "</td>\n" .
1769                              "<td>$mode_chnge</td>\n" .
1770                              "<td class=\"link\">" .
1771                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1772                                                     hash_base=>$hash, file_name=>$diff{'file'})},
1773                                      "blob");
1774                        if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1775                                if ($action eq 'commitdiff') {
1776                                        # link to patch
1777                                        $patchno++;
1778                                        print " | " .
1779                                                $cgi->a({-href => "#patch$patchno"}, "patch");
1780                                } else {
1781                                        print " | " .
1782                                                $cgi->a({-href => href(action=>"blobdiff",
1783                                                                       hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1784                                                                       hash_base=>$hash, hash_parent_base=>$parent,
1785                                                                       file_name=>$diff{'file'})},
1786                                                        "diff");
1787                                }
1788                        }
1789                        print " | " .
1790                                $cgi->a({-href => href(action=>"history",
1791                                                       hash_base=>$hash, file_name=>$diff{'file'})},
1792                                        "history");
1793                        print "</td>\n";
1794
1795                } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
1796                        my %status_name = ('R' => 'moved', 'C' => 'copied');
1797                        my $nstatus = $status_name{$diff{'status'}};
1798                        my $mode_chng = "";
1799                        if ($diff{'from_mode'} != $diff{'to_mode'}) {
1800                                # mode also for directories, so we cannot use $to_mode_str
1801                                $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
1802                        }
1803                        print "<td>" .
1804                              $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1805                                                     hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
1806                                      -class => "list"}, esc_html($diff{'to_file'})) . "</td>\n" .
1807                              "<td><span class=\"file_status $nstatus\">[$nstatus from " .
1808                              $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
1809                                                     hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
1810                                      -class => "list"}, esc_html($diff{'from_file'})) .
1811                              " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
1812                              "<td class=\"link\">" .
1813                              $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1814                                                     hash=>$diff{'to_id'}, file_name=>$diff{'to_file'})},
1815                                      "blob");
1816                        if ($diff{'to_id'} ne $diff{'from_id'}) {
1817                                if ($action eq 'commitdiff') {
1818                                        # link to patch
1819                                        $patchno++;
1820                                        print " | " .
1821                                                $cgi->a({-href => "#patch$patchno"}, "patch");
1822                                } else {
1823                                        print " | " .
1824                                                $cgi->a({-href => href(action=>"blobdiff",
1825                                                                       hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1826                                                                       hash_base=>$hash, hash_parent_base=>$parent,
1827                                                                       file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
1828                                                        "diff");
1829                                }
1830                        }
1831                        print "</td>\n";
1832
1833                } # we should not encounter Unmerged (U) or Unknown (X) status
1834                print "</tr>\n";
1835        }
1836        print "</table>\n";
1837}
1838
1839sub git_patchset_body {
1840        my ($fd, $difftree, $hash, $hash_parent) = @_;
1841
1842        my $patch_idx = 0;
1843        my $in_header = 0;
1844        my $patch_found = 0;
1845        my $diffinfo;
1846
1847        print "<div class=\"patchset\">\n";
1848
1849        LINE:
1850        while (my $patch_line = <$fd>) {
1851                chomp $patch_line;
1852
1853                if ($patch_line =~ m/^diff /) { # "git diff" header
1854                        # beginning of patch (in patchset)
1855                        if ($patch_found) {
1856                                # close previous patch
1857                                print "</div>\n"; # class="patch"
1858                        } else {
1859                                # first patch in patchset
1860                                $patch_found = 1;
1861                        }
1862                        print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
1863
1864                        if (ref($difftree->[$patch_idx]) eq "HASH") {
1865                                $diffinfo = $difftree->[$patch_idx];
1866                        } else {
1867                                $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
1868                        }
1869                        $patch_idx++;
1870
1871                        # for now, no extended header, hence we skip empty patches
1872                        # companion to  next LINE if $in_header;
1873                        if ($diffinfo->{'from_id'} eq $diffinfo->{'to_id'}) { # no change
1874                                $in_header = 1;
1875                                next LINE;
1876                        }
1877
1878                        if ($diffinfo->{'status'} eq "A") { # added
1879                                print "<div class=\"diff_info\">" . file_type($diffinfo->{'to_mode'}) . ":" .
1880                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1881                                                             hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1882                                              $diffinfo->{'to_id'}) . "(new)" .
1883                                      "</div>\n"; # class="diff_info"
1884
1885                        } elsif ($diffinfo->{'status'} eq "D") { # deleted
1886                                print "<div class=\"diff_info\">" . file_type($diffinfo->{'from_mode'}) . ":" .
1887                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1888                                                             hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1889                                              $diffinfo->{'from_id'}) . "(deleted)" .
1890                                      "</div>\n"; # class="diff_info"
1891
1892                        } elsif ($diffinfo->{'status'} eq "R" || # renamed
1893                                 $diffinfo->{'status'} eq "C" || # copied
1894                                 $diffinfo->{'status'} eq "2") { # with two filenames (from git_blobdiff)
1895                                print "<div class=\"diff_info\">" .
1896                                      file_type($diffinfo->{'from_mode'}) . ":" .
1897                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1898                                                             hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'from_file'})},
1899                                              $diffinfo->{'from_id'}) .
1900                                      " -> " .
1901                                      file_type($diffinfo->{'to_mode'}) . ":" .
1902                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1903                                                             hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'to_file'})},
1904                                              $diffinfo->{'to_id'});
1905                                print "</div>\n"; # class="diff_info"
1906
1907                        } else { # modified, mode changed, ...
1908                                print "<div class=\"diff_info\">" .
1909                                      file_type($diffinfo->{'from_mode'}) . ":" .
1910                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1911                                                             hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1912                                              $diffinfo->{'from_id'}) .
1913                                      " -> " .
1914                                      file_type($diffinfo->{'to_mode'}) . ":" .
1915                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1916                                                             hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1917                                              $diffinfo->{'to_id'});
1918                                print "</div>\n"; # class="diff_info"
1919                        }
1920
1921                        #print "<div class=\"diff extended_header\">\n";
1922                        $in_header = 1;
1923                        next LINE;
1924                } # start of patch in patchset
1925
1926
1927                if ($in_header && $patch_line =~ m/^---/) {
1928                        #print "</div>\n"; # class="diff extended_header"
1929                        $in_header = 0;
1930
1931                        my $file = $diffinfo->{'from_file'};
1932                        $file  ||= $diffinfo->{'file'};
1933                        $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1934                                                       hash=>$diffinfo->{'from_id'}, file_name=>$file),
1935                                        -class => "list"}, esc_html($file));
1936                        $patch_line =~ s|a/.*$|a/$file|g;
1937                        print "<div class=\"diff from_file\">$patch_line</div>\n";
1938
1939                        $patch_line = <$fd>;
1940                        chomp $patch_line;
1941
1942                        #$patch_line =~ m/^+++/;
1943                        $file    = $diffinfo->{'to_file'};
1944                        $file  ||= $diffinfo->{'file'};
1945                        $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1946                                                       hash=>$diffinfo->{'to_id'}, file_name=>$file),
1947                                        -class => "list"}, esc_html($file));
1948                        $patch_line =~ s|b/.*|b/$file|g;
1949                        print "<div class=\"diff to_file\">$patch_line</div>\n";
1950
1951                        next LINE;
1952                }
1953                next LINE if $in_header;
1954
1955                print format_diff_line($patch_line);
1956        }
1957        print "</div>\n" if $patch_found; # class="patch"
1958
1959        print "</div>\n"; # class="patchset"
1960}
1961
1962# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1963
1964sub git_shortlog_body {
1965        # uses global variable $project
1966        my ($revlist, $from, $to, $refs, $extra) = @_;
1967
1968        $from = 0 unless defined $from;
1969        $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
1970
1971        print "<table class=\"shortlog\" cellspacing=\"0\">\n";
1972        my $alternate = 0;
1973        for (my $i = $from; $i <= $to; $i++) {
1974                my $commit = $revlist->[$i];
1975                #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
1976                my $ref = format_ref_marker($refs, $commit);
1977                my %co = parse_commit($commit);
1978                if ($alternate) {
1979                        print "<tr class=\"dark\">\n";
1980                } else {
1981                        print "<tr class=\"light\">\n";
1982                }
1983                $alternate ^= 1;
1984                # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
1985                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1986                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
1987                      "<td>";
1988                print format_subject_html($co{'title'}, $co{'title_short'},
1989                                          href(action=>"commit", hash=>$commit), $ref);
1990                print "</td>\n" .
1991                      "<td class=\"link\">" .
1992                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1993                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
1994                      $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
1995                print "</td>\n" .
1996                      "</tr>\n";
1997        }
1998        if (defined $extra) {
1999                print "<tr>\n" .
2000                      "<td colspan=\"4\">$extra</td>\n" .
2001                      "</tr>\n";
2002        }
2003        print "</table>\n";
2004}
2005
2006sub git_history_body {
2007        # Warning: assumes constant type (blob or tree) during history
2008        my ($revlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
2009
2010        $from = 0 unless defined $from;
2011        $to = $#{$revlist} unless (defined $to && $to <= $#{$revlist});
2012
2013        print "<table class=\"history\" cellspacing=\"0\">\n";
2014        my $alternate = 0;
2015        for (my $i = $from; $i <= $to; $i++) {
2016                if ($revlist->[$i] !~ m/^([0-9a-fA-F]{40})/) {
2017                        next;
2018                }
2019
2020                my $commit = $1;
2021                my %co = parse_commit($commit);
2022                if (!%co) {
2023                        next;
2024                }
2025
2026                my $ref = format_ref_marker($refs, $commit);
2027
2028                if ($alternate) {
2029                        print "<tr class=\"dark\">\n";
2030                } else {
2031                        print "<tr class=\"light\">\n";
2032                }
2033                $alternate ^= 1;
2034                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2035                      # shortlog uses      chop_str($co{'author_name'}, 10)
2036                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
2037                      "<td>";
2038                # originally git_history used chop_str($co{'title'}, 50)
2039                print format_subject_html($co{'title'}, $co{'title_short'},
2040                                          href(action=>"commit", hash=>$commit), $ref);
2041                print "</td>\n" .
2042                      "<td class=\"link\">" .
2043                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
2044                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
2045                      $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype);
2046
2047                if ($ftype eq 'blob') {
2048                        my $blob_current = git_get_hash_by_path($hash_base, $file_name);
2049                        my $blob_parent  = git_get_hash_by_path($commit, $file_name);
2050                        if (defined $blob_current && defined $blob_parent &&
2051                                        $blob_current ne $blob_parent) {
2052                                print " | " .
2053                                        $cgi->a({-href => href(action=>"blobdiff",
2054                                                               hash=>$blob_current, hash_parent=>$blob_parent,
2055                                                               hash_base=>$hash_base, hash_parent_base=>$commit,
2056                                                               file_name=>$file_name)},
2057                                                "diff to current");
2058                        }
2059                }
2060                print "</td>\n" .
2061                      "</tr>\n";
2062        }
2063        if (defined $extra) {
2064                print "<tr>\n" .
2065                      "<td colspan=\"4\">$extra</td>\n" .
2066                      "</tr>\n";
2067        }
2068        print "</table>\n";
2069}
2070
2071sub git_tags_body {
2072        # uses global variable $project
2073        my ($taglist, $from, $to, $extra) = @_;
2074        $from = 0 unless defined $from;
2075        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2076
2077        print "<table class=\"tags\" cellspacing=\"0\">\n";
2078        my $alternate = 0;
2079        for (my $i = $from; $i <= $to; $i++) {
2080                my $entry = $taglist->[$i];
2081                my %tag = %$entry;
2082                my $comment_lines = $tag{'comment'};
2083                my $comment = shift @$comment_lines;
2084                my $comment_short;
2085                if (defined $comment) {
2086                        $comment_short = chop_str($comment, 30, 5);
2087                }
2088                if ($alternate) {
2089                        print "<tr class=\"dark\">\n";
2090                } else {
2091                        print "<tr class=\"light\">\n";
2092                }
2093                $alternate ^= 1;
2094                print "<td><i>$tag{'age'}</i></td>\n" .
2095                      "<td>" .
2096                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
2097                               -class => "list name"}, esc_html($tag{'name'})) .
2098                      "</td>\n" .
2099                      "<td>";
2100                if (defined $comment) {
2101                        print format_subject_html($comment, $comment_short,
2102                                                  href(action=>"tag", hash=>$tag{'id'}));
2103                }
2104                print "</td>\n" .
2105                      "<td class=\"selflink\">";
2106                if ($tag{'type'} eq "tag") {
2107                        print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
2108                } else {
2109                        print "&nbsp;";
2110                }
2111                print "</td>\n" .
2112                      "<td class=\"link\">" . " | " .
2113                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
2114                if ($tag{'reftype'} eq "commit") {
2115                        print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
2116                              " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'refid'})}, "log");
2117                } elsif ($tag{'reftype'} eq "blob") {
2118                        print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
2119                }
2120                print "</td>\n" .
2121                      "</tr>";
2122        }
2123        if (defined $extra) {
2124                print "<tr>\n" .
2125                      "<td colspan=\"5\">$extra</td>\n" .
2126                      "</tr>\n";
2127        }
2128        print "</table>\n";
2129}
2130
2131sub git_heads_body {
2132        # uses global variable $project
2133        my ($headlist, $head, $from, $to, $extra) = @_;
2134        $from = 0 unless defined $from;
2135        $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
2136
2137        print "<table class=\"heads\" cellspacing=\"0\">\n";
2138        my $alternate = 0;
2139        for (my $i = $from; $i <= $to; $i++) {
2140                my $entry = $headlist->[$i];
2141                my %tag = %$entry;
2142                my $curr = $tag{'id'} eq $head;
2143                if ($alternate) {
2144                        print "<tr class=\"dark\">\n";
2145                } else {
2146                        print "<tr class=\"light\">\n";
2147                }
2148                $alternate ^= 1;
2149                print "<td><i>$tag{'age'}</i></td>\n" .
2150                      ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
2151                      $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'}),
2152                               -class => "list name"},esc_html($tag{'name'})) .
2153                      "</td>\n" .
2154                      "<td class=\"link\">" .
2155                      $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") . " | " .
2156                      $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log") . " | " .
2157                      $cgi->a({-href => href(action=>"tree", hash=>$tag{'name'}, hash_base=>$tag{'name'})}, "tree") .
2158                      "</td>\n" .
2159                      "</tr>";
2160        }
2161        if (defined $extra) {
2162                print "<tr>\n" .
2163                      "<td colspan=\"3\">$extra</td>\n" .
2164                      "</tr>\n";
2165        }
2166        print "</table>\n";
2167}
2168
2169## ======================================================================
2170## ======================================================================
2171## actions
2172
2173sub git_project_list {
2174        my $order = $cgi->param('o');
2175        if (defined $order && $order !~ m/project|descr|owner|age/) {
2176                die_error(undef, "Unknown order parameter");
2177        }
2178
2179        my @list = git_get_projects_list();
2180        my @projects;
2181        if (!@list) {
2182                die_error(undef, "No projects found");
2183        }
2184        foreach my $pr (@list) {
2185                my $head = git_get_head_hash($pr->{'path'});
2186                if (!defined $head) {
2187                        next;
2188                }
2189                $git_dir = "$projectroot/$pr->{'path'}";
2190                my %co = parse_commit($head);
2191                if (!%co) {
2192                        next;
2193                }
2194                $pr->{'commit'} = \%co;
2195                if (!defined $pr->{'descr'}) {
2196                        my $descr = git_get_project_description($pr->{'path'}) || "";
2197                        $pr->{'descr'} = chop_str($descr, 25, 5);
2198                }
2199                if (!defined $pr->{'owner'}) {
2200                        $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2201                }
2202                push @projects, $pr;
2203        }
2204
2205        git_header_html();
2206        if (-f $home_text) {
2207                print "<div class=\"index_include\">\n";
2208                open (my $fd, $home_text);
2209                print <$fd>;
2210                close $fd;
2211                print "</div>\n";
2212        }
2213        print "<table class=\"project_list\">\n" .
2214              "<tr>\n";
2215        $order ||= "project";
2216        if ($order eq "project") {
2217                @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2218                print "<th>Project</th>\n";
2219        } else {
2220                print "<th>" .
2221                      $cgi->a({-href => href(project=>undef, order=>'project'),
2222                               -class => "header"}, "Project") .
2223                      "</th>\n";
2224        }
2225        if ($order eq "descr") {
2226                @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2227                print "<th>Description</th>\n";
2228        } else {
2229                print "<th>" .
2230                      $cgi->a({-href => href(project=>undef, order=>'descr'),
2231                               -class => "header"}, "Description") .
2232                      "</th>\n";
2233        }
2234        if ($order eq "owner") {
2235                @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2236                print "<th>Owner</th>\n";
2237        } else {
2238                print "<th>" .
2239                      $cgi->a({-href => href(project=>undef, order=>'owner'),
2240                               -class => "header"}, "Owner") .
2241                      "</th>\n";
2242        }
2243        if ($order eq "age") {
2244                @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
2245                print "<th>Last Change</th>\n";
2246        } else {
2247                print "<th>" .
2248                      $cgi->a({-href => href(project=>undef, order=>'age'),
2249                               -class => "header"}, "Last Change") .
2250                      "</th>\n";
2251        }
2252        print "<th></th>\n" .
2253              "</tr>\n";
2254        my $alternate = 0;
2255        foreach my $pr (@projects) {
2256                if ($alternate) {
2257                        print "<tr class=\"dark\">\n";
2258                } else {
2259                        print "<tr class=\"light\">\n";
2260                }
2261                $alternate ^= 1;
2262                print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2263                                        -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2264                      "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
2265                      "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2266                print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" .
2267                      $pr->{'commit'}{'age_string'} . "</td>\n" .
2268                      "<td class=\"link\">" .
2269                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2270                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
2271                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
2272                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
2273                      "</td>\n" .
2274                      "</tr>\n";
2275        }
2276        print "</table>\n";
2277        git_footer_html();
2278}
2279
2280sub git_project_index {
2281        my @projects = git_get_projects_list();
2282
2283        print $cgi->header(
2284                -type => 'text/plain',
2285                -charset => 'utf-8',
2286                -content_disposition => qq(inline; filename="index.aux"));
2287
2288        foreach my $pr (@projects) {
2289                if (!exists $pr->{'owner'}) {
2290                        $pr->{'owner'} = get_file_owner("$projectroot/$project");
2291                }
2292
2293                my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
2294                # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
2295                $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2296                $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2297                $path  =~ s/ /\+/g;
2298                $owner =~ s/ /\+/g;
2299
2300                print "$path $owner\n";
2301        }
2302}
2303
2304sub git_summary {
2305        my $descr = git_get_project_description($project) || "none";
2306        my $head = git_get_head_hash($project);
2307        my %co = parse_commit($head);
2308        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2309
2310        my $owner = git_get_project_owner($project);
2311
2312        my ($reflist, $refs) = git_get_refs_list();
2313
2314        my @taglist;
2315        my @headlist;
2316        foreach my $ref (@$reflist) {
2317                if ($ref->{'name'} =~ s!^heads/!!) {
2318                        push @headlist, $ref;
2319                } else {
2320                        $ref->{'name'} =~ s!^tags/!!;
2321                        push @taglist, $ref;
2322                }
2323        }
2324
2325        git_header_html();
2326        git_print_page_nav('summary','', $head);
2327
2328        print "<div class=\"title\">&nbsp;</div>\n";
2329        print "<table cellspacing=\"0\">\n" .
2330              "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
2331              "<tr><td>owner</td><td>$owner</td></tr>\n" .
2332              "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
2333        # use per project git URL list in $projectroot/$project/cloneurl
2334        # or make project git URL from git base URL and project name
2335        my $url_tag = "URL";
2336        my @url_list = git_get_project_url_list($project);
2337        @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
2338        foreach my $git_url (@url_list) {
2339                next unless $git_url;
2340                print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
2341                $url_tag = "";
2342        }
2343        print "</table>\n";
2344
2345        open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
2346                git_get_head_hash($project)
2347                or die_error(undef, "Open git-rev-list failed");
2348        my @revlist = map { chomp; $_ } <$fd>;
2349        close $fd;
2350        git_print_header_div('shortlog');
2351        git_shortlog_body(\@revlist, 0, 15, $refs,
2352                          $cgi->a({-href => href(action=>"shortlog")}, "..."));
2353
2354        if (@taglist) {
2355                git_print_header_div('tags');
2356                git_tags_body(\@taglist, 0, 15,
2357                              $cgi->a({-href => href(action=>"tags")}, "..."));
2358        }
2359
2360        if (@headlist) {
2361                git_print_header_div('heads');
2362                git_heads_body(\@headlist, $head, 0, 15,
2363                               $cgi->a({-href => href(action=>"heads")}, "..."));
2364        }
2365
2366        git_footer_html();
2367}
2368
2369sub git_tag {
2370        my $head = git_get_head_hash($project);
2371        git_header_html();
2372        git_print_page_nav('','', $head,undef,$head);
2373        my %tag = parse_tag($hash);
2374        git_print_header_div('commit', esc_html($tag{'name'}), $hash);
2375        print "<div class=\"title_text\">\n" .
2376              "<table cellspacing=\"0\">\n" .
2377              "<tr>\n" .
2378              "<td>object</td>\n" .
2379              "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2380                               $tag{'object'}) . "</td>\n" .
2381              "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2382                                              $tag{'type'}) . "</td>\n" .
2383              "</tr>\n";
2384        if (defined($tag{'author'})) {
2385                my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
2386                print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
2387                print "<tr><td></td><td>" . $ad{'rfc2822'} .
2388                        sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
2389                        "</td></tr>\n";
2390        }
2391        print "</table>\n\n" .
2392              "</div>\n";
2393        print "<div class=\"page_body\">";
2394        my $comment = $tag{'comment'};
2395        foreach my $line (@$comment) {
2396                print esc_html($line) . "<br/>\n";
2397        }
2398        print "</div>\n";
2399        git_footer_html();
2400}
2401
2402sub git_blame2 {
2403        my $fd;
2404        my $ftype;
2405
2406        my ($have_blame) = gitweb_check_feature('blame');
2407        if (!$have_blame) {
2408                die_error('403 Permission denied', "Permission denied");
2409        }
2410        die_error('404 Not Found', "File name not defined") if (!$file_name);
2411        $hash_base ||= git_get_head_hash($project);
2412        die_error(undef, "Couldn't find base commit") unless ($hash_base);
2413        my %co = parse_commit($hash_base)
2414                or die_error(undef, "Reading commit failed");
2415        if (!defined $hash) {
2416                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2417                        or die_error(undef, "Error looking up file");
2418        }
2419        $ftype = git_get_type($hash);
2420        if ($ftype !~ "blob") {
2421                die_error("400 Bad Request", "Object is not a blob");
2422        }
2423        open ($fd, "-|", git_cmd(), "blame", '-l', '--', $file_name, $hash_base)
2424                or die_error(undef, "Open git-blame failed");
2425        git_header_html();
2426        my $formats_nav =
2427                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2428                        "blob") .
2429                " | " .
2430                $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2431                        "history") .
2432                " | " .
2433                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2434                        "HEAD");
2435        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2436        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2437        git_print_page_path($file_name, $ftype, $hash_base);
2438        my @rev_color = (qw(light2 dark2));
2439        my $num_colors = scalar(@rev_color);
2440        my $current_color = 0;
2441        my $last_rev;
2442        print <<HTML;
2443<div class="page_body">
2444<table class="blame">
2445<tr><th>Commit</th><th>Line</th><th>Data</th></tr>
2446HTML
2447        while (<$fd>) {
2448                /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
2449                my $full_rev = $1;
2450                my $rev = substr($full_rev, 0, 8);
2451                my $lineno = $2;
2452                my $data = $3;
2453
2454                if (!defined $last_rev) {
2455                        $last_rev = $full_rev;
2456                } elsif ($last_rev ne $full_rev) {
2457                        $last_rev = $full_rev;
2458                        $current_color = ++$current_color % $num_colors;
2459                }
2460                print "<tr class=\"$rev_color[$current_color]\">\n";
2461                print "<td class=\"sha1\">" .
2462                        $cgi->a({-href => href(action=>"commit", hash=>$full_rev, file_name=>$file_name)},
2463                                esc_html($rev)) . "</td>\n";
2464                print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" .
2465                      esc_html($lineno) . "</a></td>\n";
2466                print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
2467                print "</tr>\n";
2468        }
2469        print "</table>\n";
2470        print "</div>";
2471        close $fd
2472                or print "Reading blob failed\n";
2473        git_footer_html();
2474}
2475
2476sub git_blame {
2477        my $fd;
2478
2479        my ($have_blame) = gitweb_check_feature('blame');
2480        if (!$have_blame) {
2481                die_error('403 Permission denied', "Permission denied");
2482        }
2483        die_error('404 Not Found', "File name not defined") if (!$file_name);
2484        $hash_base ||= git_get_head_hash($project);
2485        die_error(undef, "Couldn't find base commit") unless ($hash_base);
2486        my %co = parse_commit($hash_base)
2487                or die_error(undef, "Reading commit failed");
2488        if (!defined $hash) {
2489                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2490                        or die_error(undef, "Error lookup file");
2491        }
2492        open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
2493                or die_error(undef, "Open git-annotate failed");
2494        git_header_html();
2495        my $formats_nav =
2496                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2497                        "blob") .
2498                " | " .
2499                $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2500                        "history") .
2501                " | " .
2502                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2503                        "HEAD");
2504        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2505        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2506        git_print_page_path($file_name, 'blob', $hash_base);
2507        print "<div class=\"page_body\">\n";
2508        print <<HTML;
2509<table class="blame">
2510  <tr>
2511    <th>Commit</th>
2512    <th>Age</th>
2513    <th>Author</th>
2514    <th>Line</th>
2515    <th>Data</th>
2516  </tr>
2517HTML
2518        my @line_class = (qw(light dark));
2519        my $line_class_len = scalar (@line_class);
2520        my $line_class_num = $#line_class;
2521        while (my $line = <$fd>) {
2522                my $long_rev;
2523                my $short_rev;
2524                my $author;
2525                my $time;
2526                my $lineno;
2527                my $data;
2528                my $age;
2529                my $age_str;
2530                my $age_class;
2531
2532                chomp $line;
2533                $line_class_num = ($line_class_num + 1) % $line_class_len;
2534
2535                if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
2536                        $long_rev = $1;
2537                        $author   = $2;
2538                        $time     = $3;
2539                        $lineno   = $4;
2540                        $data     = $5;
2541                } else {
2542                        print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
2543                        next;
2544                }
2545                $short_rev  = substr ($long_rev, 0, 8);
2546                $age        = time () - $time;
2547                $age_str    = age_string ($age);
2548                $age_str    =~ s/ /&nbsp;/g;
2549                $age_class  = age_class($age);
2550                $author     = esc_html ($author);
2551                $author     =~ s/ /&nbsp;/g;
2552
2553                $data = untabify($data);
2554                $data = esc_html ($data);
2555
2556                print <<HTML;
2557  <tr class="$line_class[$line_class_num]">
2558    <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
2559    <td class="$age_class">$age_str</td>
2560    <td>$author</td>
2561    <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
2562    <td class="pre">$data</td>
2563  </tr>
2564HTML
2565        } # while (my $line = <$fd>)
2566        print "</table>\n\n";
2567        close $fd
2568                or print "Reading blob failed.\n";
2569        print "</div>";
2570        git_footer_html();
2571}
2572
2573sub git_tags {
2574        my $head = git_get_head_hash($project);
2575        git_header_html();
2576        git_print_page_nav('','', $head,undef,$head);
2577        git_print_header_div('summary', $project);
2578
2579        my ($taglist) = git_get_refs_list("tags");
2580        if (@$taglist) {
2581                git_tags_body($taglist);
2582        }
2583        git_footer_html();
2584}
2585
2586sub git_heads {
2587        my $head = git_get_head_hash($project);
2588        git_header_html();
2589        git_print_page_nav('','', $head,undef,$head);
2590        git_print_header_div('summary', $project);
2591
2592        my ($headlist) = git_get_refs_list("heads");
2593        if (@$headlist) {
2594                git_heads_body($headlist, $head);
2595        }
2596        git_footer_html();
2597}
2598
2599sub git_blob_plain {
2600        my $expires;
2601
2602        if (!defined $hash) {
2603                if (defined $file_name) {
2604                        my $base = $hash_base || git_get_head_hash($project);
2605                        $hash = git_get_hash_by_path($base, $file_name, "blob")
2606                                or die_error(undef, "Error lookup file");
2607                } else {
2608                        die_error(undef, "No file name defined");
2609                }
2610        } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2611                # blobs defined by non-textual hash id's can be cached
2612                $expires = "+1d";
2613        }
2614
2615        my $type = shift;
2616        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2617                or die_error(undef, "Couldn't cat $file_name, $hash");
2618
2619        $type ||= blob_mimetype($fd, $file_name);
2620
2621        # save as filename, even when no $file_name is given
2622        my $save_as = "$hash";
2623        if (defined $file_name) {
2624                $save_as = $file_name;
2625        } elsif ($type =~ m/^text\//) {
2626                $save_as .= '.txt';
2627        }
2628
2629        print $cgi->header(
2630                -type => "$type",
2631                -expires=>$expires,
2632                -content_disposition => "inline; filename=\"$save_as\"");
2633        undef $/;
2634        binmode STDOUT, ':raw';
2635        print <$fd>;
2636        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2637        $/ = "\n";
2638        close $fd;
2639}
2640
2641sub git_blob {
2642        my $expires;
2643
2644        if (!defined $hash) {
2645                if (defined $file_name) {
2646                        my $base = $hash_base || git_get_head_hash($project);
2647                        $hash = git_get_hash_by_path($base, $file_name, "blob")
2648                                or die_error(undef, "Error lookup file");
2649                } else {
2650                        die_error(undef, "No file name defined");
2651                }
2652        } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2653                # blobs defined by non-textual hash id's can be cached
2654                $expires = "+1d";
2655        }
2656
2657        my ($have_blame) = gitweb_check_feature('blame');
2658        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2659                or die_error(undef, "Couldn't cat $file_name, $hash");
2660        my $mimetype = blob_mimetype($fd, $file_name);
2661        if ($mimetype !~ m/^text\//) {
2662                close $fd;
2663                return git_blob_plain($mimetype);
2664        }
2665        git_header_html(undef, $expires);
2666        my $formats_nav = '';
2667        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2668                if (defined $file_name) {
2669                        if ($have_blame) {
2670                                $formats_nav .=
2671                                        $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
2672                                                               hash=>$hash, file_name=>$file_name)},
2673                                                "blame") .
2674                                        " | ";
2675                        }
2676                        $formats_nav .=
2677                                $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2678                                                       hash=>$hash, file_name=>$file_name)},
2679                                        "history") .
2680                                " | " .
2681                                $cgi->a({-href => href(action=>"blob_plain",
2682                                                       hash=>$hash, file_name=>$file_name)},
2683                                        "raw") .
2684                                " | " .
2685                                $cgi->a({-href => href(action=>"blob",
2686                                                       hash_base=>"HEAD", file_name=>$file_name)},
2687                                        "HEAD");
2688                } else {
2689                        $formats_nav .=
2690                                $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
2691                }
2692                git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2693                git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2694        } else {
2695                print "<div class=\"page_nav\">\n" .
2696                      "<br/><br/></div>\n" .
2697                      "<div class=\"title\">$hash</div>\n";
2698        }
2699        git_print_page_path($file_name, "blob", $hash_base);
2700        print "<div class=\"page_body\">\n";
2701        my $nr;
2702        while (my $line = <$fd>) {
2703                chomp $line;
2704                $nr++;
2705                $line = untabify($line);
2706                printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
2707                       $nr, $nr, $nr, esc_html($line);
2708        }
2709        close $fd
2710                or print "Reading blob failed.\n";
2711        print "</div>";
2712        git_footer_html();
2713}
2714
2715sub git_tree {
2716        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2717        my $have_snapshot = (defined $ctype && defined $suffix);
2718
2719        if (!defined $hash) {
2720                $hash = git_get_head_hash($project);
2721                if (defined $file_name) {
2722                        my $base = $hash_base || $hash;
2723                        $hash = git_get_hash_by_path($base, $file_name, "tree");
2724                }
2725                if (!defined $hash_base) {
2726                        $hash_base = $hash;
2727                }
2728        }
2729        $/ = "\0";
2730        open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
2731                or die_error(undef, "Open git-ls-tree failed");
2732        my @entries = map { chomp; $_ } <$fd>;
2733        close $fd or die_error(undef, "Reading tree failed");
2734        $/ = "\n";
2735
2736        my $refs = git_get_references();
2737        my $ref = format_ref_marker($refs, $hash_base);
2738        git_header_html();
2739        my $base = "";
2740        my ($have_blame) = gitweb_check_feature('blame');
2741        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2742                my @views_nav = ();
2743                if (defined $file_name) {
2744                        push @views_nav,
2745                                $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2746                                                       hash=>$hash, file_name=>$file_name)},
2747                                        "history"),
2748                                $cgi->a({-href => href(action=>"tree",
2749                                                       hash_base=>"HEAD", file_name=>$file_name)},
2750                                        "HEAD"),
2751                }
2752                if ($have_snapshot) {
2753                        # FIXME: Should be available when we have no hash base as well.
2754                        push @views_nav,
2755                                $cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
2756                                        "snapshot");
2757                }
2758                git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
2759                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
2760        } else {
2761                undef $hash_base;
2762                print "<div class=\"page_nav\">\n";
2763                print "<br/><br/></div>\n";
2764                print "<div class=\"title\">$hash</div>\n";
2765        }
2766        if (defined $file_name) {
2767                $base = esc_html("$file_name/");
2768        }
2769        git_print_page_path($file_name, 'tree', $hash_base);
2770        print "<div class=\"page_body\">\n";
2771        print "<table cellspacing=\"0\">\n";
2772        my $alternate = 0;
2773        foreach my $line (@entries) {
2774                my %t = parse_ls_tree_line($line, -z => 1);
2775
2776                if ($alternate) {
2777                        print "<tr class=\"dark\">\n";
2778                } else {
2779                        print "<tr class=\"light\">\n";
2780                }
2781                $alternate ^= 1;
2782
2783                git_print_tree_entry(\%t, $base, $hash_base, $have_blame);
2784
2785                print "</tr>\n";
2786        }
2787        print "</table>\n" .
2788              "</div>";
2789        git_footer_html();
2790}
2791
2792sub git_snapshot {
2793
2794        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2795        my $have_snapshot = (defined $ctype && defined $suffix);
2796        if (!$have_snapshot) {
2797                die_error('403 Permission denied', "Permission denied");
2798        }
2799
2800        if (!defined $hash) {
2801                $hash = git_get_head_hash($project);
2802        }
2803
2804        my $filename = basename($project) . "-$hash.tar.$suffix";
2805
2806        print $cgi->header(-type => 'application/x-tar',
2807                           -content_encoding => $ctype,
2808                           -content_disposition => "inline; filename=\"$filename\"",
2809                           -status => '200 OK');
2810
2811        my $git_command = git_cmd_str();
2812        open my $fd, "-|", "$git_command tar-tree $hash \'$project\' | $command" or
2813                die_error(undef, "Execute git-tar-tree failed.");
2814        binmode STDOUT, ':raw';
2815        print <$fd>;
2816        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2817        close $fd;
2818
2819}
2820
2821sub git_log {
2822        my $head = git_get_head_hash($project);
2823        if (!defined $hash) {
2824                $hash = $head;
2825        }
2826        if (!defined $page) {
2827                $page = 0;
2828        }
2829        my $refs = git_get_references();
2830
2831        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2832        open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
2833                or die_error(undef, "Open git-rev-list failed");
2834        my @revlist = map { chomp; $_ } <$fd>;
2835        close $fd;
2836
2837        my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
2838
2839        git_header_html();
2840        git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
2841
2842        if (!@revlist) {
2843                my %co = parse_commit($hash);
2844
2845                git_print_header_div('summary', $project);
2846                print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
2847        }
2848        for (my $i = ($page * 100); $i <= $#revlist; $i++) {
2849                my $commit = $revlist[$i];
2850                my $ref = format_ref_marker($refs, $commit);
2851                my %co = parse_commit($commit);
2852                next if !%co;
2853                my %ad = parse_date($co{'author_epoch'});
2854                git_print_header_div('commit',
2855                               "<span class=\"age\">$co{'age_string'}</span>" .
2856                               esc_html($co{'title'}) . $ref,
2857                               $commit);
2858                print "<div class=\"title_text\">\n" .
2859                      "<div class=\"log_link\">\n" .
2860                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
2861                      " | " .
2862                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
2863                      " | " .
2864                      $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
2865                      "<br/>\n" .
2866                      "</div>\n" .
2867                      "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
2868                      "</div>\n";
2869
2870                print "<div class=\"log_body\">\n";
2871                git_print_simplified_log($co{'comment'});
2872                print "</div>\n";
2873        }
2874        git_footer_html();
2875}
2876
2877sub git_commit {
2878        my %co = parse_commit($hash);
2879        if (!%co) {
2880                die_error(undef, "Unknown commit object");
2881        }
2882        my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2883        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2884
2885        my $parent = $co{'parent'};
2886        if (!defined $parent) {
2887                $parent = "--root";
2888        }
2889        open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $parent, $hash
2890                or die_error(undef, "Open git-diff-tree failed");
2891        my @difftree = map { chomp; $_ } <$fd>;
2892        close $fd or die_error(undef, "Reading git-diff-tree failed");
2893
2894        # non-textual hash id's can be cached
2895        my $expires;
2896        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2897                $expires = "+1d";
2898        }
2899        my $refs = git_get_references();
2900        my $ref = format_ref_marker($refs, $co{'id'});
2901
2902        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2903        my $have_snapshot = (defined $ctype && defined $suffix);
2904
2905        my @views_nav = ();
2906        if (defined $file_name && defined $co{'parent'}) {
2907                my $parent = $co{'parent'};
2908                push @views_nav,
2909                        $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)},
2910                                "blame");
2911        }
2912        if (defined $co{'parent'}) {
2913                push @views_nav,
2914                        $cgi->a({-href => href(action=>"shortlog", hash=>$hash)}, "shortlog"),
2915                        $cgi->a({-href => href(action=>"log", hash=>$hash)}, "log");
2916        }
2917        git_header_html(undef, $expires);
2918        git_print_page_nav('commit', defined $co{'parent'} ? '' : 'commitdiff',
2919                           $hash, $co{'tree'}, $hash,
2920                           join (' | ', @views_nav));
2921
2922        if (defined $co{'parent'}) {
2923                git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
2924        } else {
2925                git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
2926        }
2927        print "<div class=\"title_text\">\n" .
2928              "<table cellspacing=\"0\">\n";
2929        print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
2930              "<tr>" .
2931              "<td></td><td> $ad{'rfc2822'}";
2932        if ($ad{'hour_local'} < 6) {
2933                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2934                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2935        } else {
2936                printf(" (%02d:%02d %s)",
2937                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2938        }
2939        print "</td>" .
2940              "</tr>\n";
2941        print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
2942        print "<tr><td></td><td> $cd{'rfc2822'}" .
2943              sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
2944              "</td></tr>\n";
2945        print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
2946        print "<tr>" .
2947              "<td>tree</td>" .
2948              "<td class=\"sha1\">" .
2949              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
2950                       class => "list"}, $co{'tree'}) .
2951              "</td>" .
2952              "<td class=\"link\">" .
2953              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
2954                      "tree");
2955        if ($have_snapshot) {
2956                print " | " .
2957                      $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
2958        }
2959        print "</td>" .
2960              "</tr>\n";
2961        my $parents = $co{'parents'};
2962        foreach my $par (@$parents) {
2963                print "<tr>" .
2964                      "<td>parent</td>" .
2965                      "<td class=\"sha1\">" .
2966                      $cgi->a({-href => href(action=>"commit", hash=>$par),
2967                               class => "list"}, $par) .
2968                      "</td>" .
2969                      "<td class=\"link\">" .
2970                      $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
2971                      " | " .
2972                      $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
2973                      "</td>" .
2974                      "</tr>\n";
2975        }
2976        print "</table>".
2977              "</div>\n";
2978
2979        print "<div class=\"page_body\">\n";
2980        git_print_log($co{'comment'});
2981        print "</div>\n";
2982
2983        git_difftree_body(\@difftree, $hash, $parent);
2984
2985        git_footer_html();
2986}
2987
2988sub git_blobdiff {
2989        my $format = shift || 'html';
2990
2991        my $fd;
2992        my @difftree;
2993        my %diffinfo;
2994        my $expires;
2995
2996        # preparing $fd and %diffinfo for git_patchset_body
2997        # new style URI
2998        if (defined $hash_base && defined $hash_parent_base) {
2999                if (defined $file_name) {
3000                        # read raw output
3001                        open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base,
3002                                "--", $file_name
3003                                or die_error(undef, "Open git-diff-tree failed");
3004                        @difftree = map { chomp; $_ } <$fd>;
3005                        close $fd
3006                                or die_error(undef, "Reading git-diff-tree failed");
3007                        @difftree
3008                                or die_error('404 Not Found', "Blob diff not found");
3009
3010                } elsif (defined $hash &&
3011                         $hash =~ /[0-9a-fA-F]{40}/) {
3012                        # try to find filename from $hash
3013
3014                        # read filtered raw output
3015                        open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base
3016                                or die_error(undef, "Open git-diff-tree failed");
3017                        @difftree =
3018                                # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
3019                                # $hash == to_id
3020                                grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
3021                                map { chomp; $_ } <$fd>;
3022                        close $fd
3023                                or die_error(undef, "Reading git-diff-tree failed");
3024                        @difftree
3025                                or die_error('404 Not Found', "Blob diff not found");
3026
3027                } else {
3028                        die_error('404 Not Found', "Missing one of the blob diff parameters");
3029                }
3030
3031                if (@difftree > 1) {
3032                        die_error('404 Not Found', "Ambiguous blob diff specification");
3033                }
3034
3035                %diffinfo = parse_difftree_raw_line($difftree[0]);
3036                $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
3037                $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
3038
3039                $hash_parent ||= $diffinfo{'from_id'};
3040                $hash        ||= $diffinfo{'to_id'};
3041
3042                # non-textual hash id's can be cached
3043                if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
3044                    $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
3045                        $expires = '+1d';
3046                }
3047
3048                # open patch output
3049                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3050                        '-p', $hash_parent_base, $hash_base,
3051                        "--", $file_name
3052                        or die_error(undef, "Open git-diff-tree failed");
3053        }
3054
3055        # old/legacy style URI
3056        if (!%diffinfo && # if new style URI failed
3057            defined $hash && defined $hash_parent) {
3058                # fake git-diff-tree raw output
3059                $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
3060                $diffinfo{'from_id'} = $hash_parent;
3061                $diffinfo{'to_id'}   = $hash;
3062                if (defined $file_name) {
3063                        if (defined $file_parent) {
3064                                $diffinfo{'status'} = '2';
3065                                $diffinfo{'from_file'} = $file_parent;
3066                                $diffinfo{'to_file'}   = $file_name;
3067                        } else { # assume not renamed
3068                                $diffinfo{'status'} = '1';
3069                                $diffinfo{'from_file'} = $file_name;
3070                                $diffinfo{'to_file'}   = $file_name;
3071                        }
3072                } else { # no filename given
3073                        $diffinfo{'status'} = '2';
3074                        $diffinfo{'from_file'} = $hash_parent;
3075                        $diffinfo{'to_file'}   = $hash;
3076                }
3077
3078                # non-textual hash id's can be cached
3079                if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
3080                    $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3081                        $expires = '+1d';
3082                }
3083
3084                # open patch output
3085                open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts, $hash_parent, $hash
3086                        or die_error(undef, "Open git-diff failed");
3087        } else  {
3088                die_error('404 Not Found', "Missing one of the blob diff parameters")
3089                        unless %diffinfo;
3090        }
3091
3092        # header
3093        if ($format eq 'html') {
3094                my $formats_nav =
3095                        $cgi->a({-href => href(action=>"blobdiff_plain",
3096                                               hash=>$hash, hash_parent=>$hash_parent,
3097                                               hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
3098                                               file_name=>$file_name, file_parent=>$file_parent)},
3099                                "raw");
3100                git_header_html(undef, $expires);
3101                if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3102                        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3103                        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3104                } else {
3105                        print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
3106                        print "<div class=\"title\">$hash vs $hash_parent</div>\n";
3107                }
3108                if (defined $file_name) {
3109                        git_print_page_path($file_name, "blob", $hash_base);
3110                } else {
3111                        print "<div class=\"page_path\"></div>\n";
3112                }
3113
3114        } elsif ($format eq 'plain') {
3115                print $cgi->header(
3116                        -type => 'text/plain',
3117                        -charset => 'utf-8',
3118                        -expires => $expires,
3119                        -content_disposition => qq(inline; filename=") . quotemeta($file_name) . qq(.patch"));
3120
3121                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3122
3123        } else {
3124                die_error(undef, "Unknown blobdiff format");
3125        }
3126
3127        # patch
3128        if ($format eq 'html') {
3129                print "<div class=\"page_body\">\n";
3130
3131                git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
3132                close $fd;
3133
3134                print "</div>\n"; # class="page_body"
3135                git_footer_html();
3136
3137        } else {
3138                while (my $line = <$fd>) {
3139                        $line =~ s!a/($hash|$hash_parent)!'a/'.esc_html($diffinfo{'from_file'})!eg;
3140                        $line =~ s!b/($hash|$hash_parent)!'b/'.esc_html($diffinfo{'to_file'})!eg;
3141
3142                        print $line;
3143
3144                        last if $line =~ m!^\+\+\+!;
3145                }
3146                local $/ = undef;
3147                print <$fd>;
3148                close $fd;
3149        }
3150}
3151
3152sub git_blobdiff_plain {
3153        git_blobdiff('plain');
3154}
3155
3156sub git_commitdiff {
3157        my $format = shift || 'html';
3158        my %co = parse_commit($hash);
3159        if (!%co) {
3160                die_error(undef, "Unknown commit object");
3161        }
3162        if (!defined $hash_parent) {
3163                $hash_parent = $co{'parent'} || '--root';
3164        }
3165
3166        # read commitdiff
3167        my $fd;
3168        my @difftree;
3169        if ($format eq 'html') {
3170                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3171                        "--patch-with-raw", "--full-index", $hash_parent, $hash
3172                        or die_error(undef, "Open git-diff-tree failed");
3173
3174                while (chomp(my $line = <$fd>)) {
3175                        # empty line ends raw part of diff-tree output
3176                        last unless $line;
3177                        push @difftree, $line;
3178                }
3179
3180        } elsif ($format eq 'plain') {
3181                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3182                        '-p', $hash_parent, $hash
3183                        or die_error(undef, "Open git-diff-tree failed");
3184
3185        } else {
3186                die_error(undef, "Unknown commitdiff format");
3187        }
3188
3189        # non-textual hash id's can be cached
3190        my $expires;
3191        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3192                $expires = "+1d";
3193        }
3194
3195        # write commit message
3196        if ($format eq 'html') {
3197                my $refs = git_get_references();
3198                my $ref = format_ref_marker($refs, $co{'id'});
3199                my $formats_nav =
3200                        $cgi->a({-href => href(action=>"commitdiff_plain",
3201                                               hash=>$hash, hash_parent=>$hash_parent)},
3202                                "raw");
3203
3204                git_header_html(undef, $expires);
3205                git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
3206                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
3207                git_print_authorship(\%co);
3208                print "<div class=\"page_body\">\n";
3209                print "<div class=\"log\">\n";
3210                git_print_simplified_log($co{'comment'}, 1); # skip title
3211                print "</div>\n"; # class="log"
3212
3213        } elsif ($format eq 'plain') {
3214                my $refs = git_get_references("tags");
3215                my $tagname = git_get_rev_name_tags($hash);
3216                my $filename = basename($project) . "-$hash.patch";
3217
3218                print $cgi->header(
3219                        -type => 'text/plain',
3220                        -charset => 'utf-8',
3221                        -expires => $expires,
3222                        -content_disposition => qq(inline; filename="$filename"));
3223                my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3224                print <<TEXT;
3225From: $co{'author'}
3226Date: $ad{'rfc2822'} ($ad{'tz_local'})
3227Subject: $co{'title'}
3228TEXT
3229                print "X-Git-Tag: $tagname\n" if $tagname;
3230                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3231
3232                foreach my $line (@{$co{'comment'}}) {
3233                        print "$line\n";
3234                }
3235                print "---\n\n";
3236        }
3237
3238        # write patch
3239        if ($format eq 'html') {
3240                git_difftree_body(\@difftree, $hash, $hash_parent);
3241                print "<br/>\n";
3242
3243                git_patchset_body($fd, \@difftree, $hash, $hash_parent);
3244                close $fd;
3245                print "</div>\n"; # class="page_body"
3246                git_footer_html();
3247
3248        } elsif ($format eq 'plain') {
3249                local $/ = undef;
3250                print <$fd>;
3251                close $fd
3252                        or print "Reading git-diff-tree failed\n";
3253        }
3254}
3255
3256sub git_commitdiff_plain {
3257        git_commitdiff('plain');
3258}
3259
3260sub git_history {
3261        if (!defined $hash_base) {
3262                $hash_base = git_get_head_hash($project);
3263        }
3264        if (!defined $page) {
3265                $page = 0;
3266        }
3267        my $ftype;
3268        my %co = parse_commit($hash_base);
3269        if (!%co) {
3270                die_error(undef, "Unknown commit object");
3271        }
3272
3273        my $refs = git_get_references();
3274        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3275
3276        if (!defined $hash && defined $file_name) {
3277                $hash = git_get_hash_by_path($hash_base, $file_name);
3278        }
3279        if (defined $hash) {
3280                $ftype = git_get_type($hash);
3281        }
3282
3283        open my $fd, "-|",
3284                git_cmd(), "rev-list", $limit, "--full-history", $hash_base, "--", $file_name
3285                        or die_error(undef, "Open git-rev-list-failed");
3286        my @revlist = map { chomp; $_ } <$fd>;
3287        close $fd
3288                or die_error(undef, "Reading git-rev-list failed");
3289
3290        my $paging_nav = '';
3291        if ($page > 0) {
3292                $paging_nav .=
3293                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3294                                               file_name=>$file_name)},
3295                                "first");
3296                $paging_nav .= " &sdot; " .
3297                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3298                                               file_name=>$file_name, page=>$page-1),
3299                                 -accesskey => "p", -title => "Alt-p"}, "prev");
3300        } else {
3301                $paging_nav .= "first";
3302                $paging_nav .= " &sdot; prev";
3303        }
3304        if ($#revlist >= (100 * ($page+1)-1)) {
3305                $paging_nav .= " &sdot; " .
3306                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3307                                               file_name=>$file_name, page=>$page+1),
3308                                 -accesskey => "n", -title => "Alt-n"}, "next");
3309        } else {
3310                $paging_nav .= " &sdot; next";
3311        }
3312        my $next_link = '';
3313        if ($#revlist >= (100 * ($page+1)-1)) {
3314                $next_link =
3315                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3316                                               file_name=>$file_name, page=>$page+1),
3317                                 -title => "Alt-n"}, "next");
3318        }
3319
3320        git_header_html();
3321        git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
3322        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3323        git_print_page_path($file_name, $ftype, $hash_base);
3324
3325        git_history_body(\@revlist, ($page * 100), $#revlist,
3326                         $refs, $hash_base, $ftype, $next_link);
3327
3328        git_footer_html();
3329}
3330
3331sub git_search {
3332        if (!defined $searchtext) {
3333                die_error(undef, "Text field empty");
3334        }
3335        if (!defined $hash) {
3336                $hash = git_get_head_hash($project);
3337        }
3338        my %co = parse_commit($hash);
3339        if (!%co) {
3340                die_error(undef, "Unknown commit object");
3341        }
3342
3343        my $commit_search = 1;
3344        my $author_search = 0;
3345        my $committer_search = 0;
3346        my $pickaxe_search = 0;
3347        if ($searchtext =~ s/^author\\://i) {
3348                $author_search = 1;
3349        } elsif ($searchtext =~ s/^committer\\://i) {
3350                $committer_search = 1;
3351        } elsif ($searchtext =~ s/^pickaxe\\://i) {
3352                $commit_search = 0;
3353                $pickaxe_search = 1;
3354
3355                # pickaxe may take all resources of your box and run for several minutes
3356                # with every query - so decide by yourself how public you make this feature
3357                my ($have_pickaxe) = gitweb_check_feature('pickaxe');
3358                if (!$have_pickaxe) {
3359                        die_error('403 Permission denied', "Permission denied");
3360                }
3361        }
3362        git_header_html();
3363        git_print_page_nav('','', $hash,$co{'tree'},$hash);
3364        git_print_header_div('commit', esc_html($co{'title'}), $hash);
3365
3366        print "<table cellspacing=\"0\">\n";
3367        my $alternate = 0;
3368        if ($commit_search) {
3369                $/ = "\0";
3370                open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", $hash or next;
3371                while (my $commit_text = <$fd>) {
3372                        if (!grep m/$searchtext/i, $commit_text) {
3373                                next;
3374                        }
3375                        if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
3376                                next;
3377                        }
3378                        if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
3379                                next;
3380                        }
3381                        my @commit_lines = split "\n", $commit_text;
3382                        my %co = parse_commit(undef, \@commit_lines);
3383                        if (!%co) {
3384                                next;
3385                        }
3386                        if ($alternate) {
3387                                print "<tr class=\"dark\">\n";
3388                        } else {
3389                                print "<tr class=\"light\">\n";
3390                        }
3391                        $alternate ^= 1;
3392                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3393                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3394                              "<td>" .
3395                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3396                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3397                        my $comment = $co{'comment'};
3398                        foreach my $line (@$comment) {
3399                                if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
3400                                        my $lead = esc_html($1) || "";
3401                                        $lead = chop_str($lead, 30, 10);
3402                                        my $match = esc_html($2) || "";
3403                                        my $trail = esc_html($3) || "";
3404                                        $trail = chop_str($trail, 30, 10);
3405                                        my $text = "$lead<span class=\"match\">$match</span>$trail";
3406                                        print chop_str($text, 80, 5) . "<br/>\n";
3407                                }
3408                        }
3409                        print "</td>\n" .
3410                              "<td class=\"link\">" .
3411                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3412                              " | " .
3413                              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3414                        print "</td>\n" .
3415                              "</tr>\n";
3416                }
3417                close $fd;
3418        }
3419
3420        if ($pickaxe_search) {
3421                $/ = "\n";
3422                my $git_command = git_cmd_str();
3423                open my $fd, "-|", "$git_command rev-list $hash | " .
3424                        "$git_command diff-tree -r --stdin -S\'$searchtext\'";
3425                undef %co;
3426                my @files;
3427                while (my $line = <$fd>) {
3428                        if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
3429                                my %set;
3430                                $set{'file'} = $6;
3431                                $set{'from_id'} = $3;
3432                                $set{'to_id'} = $4;
3433                                $set{'id'} = $set{'to_id'};
3434                                if ($set{'id'} =~ m/0{40}/) {
3435                                        $set{'id'} = $set{'from_id'};
3436                                }
3437                                if ($set{'id'} =~ m/0{40}/) {
3438                                        next;
3439                                }
3440                                push @files, \%set;
3441                        } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
3442                                if (%co) {
3443                                        if ($alternate) {
3444                                                print "<tr class=\"dark\">\n";
3445                                        } else {
3446                                                print "<tr class=\"light\">\n";
3447                                        }
3448                                        $alternate ^= 1;
3449                                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3450                                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3451                                              "<td>" .
3452                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
3453                                                      -class => "list subject"},
3454                                                      esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3455                                        while (my $setref = shift @files) {
3456                                                my %set = %$setref;
3457                                                print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
3458                                                                             hash=>$set{'id'}, file_name=>$set{'file'}),
3459                                                              -class => "list"},
3460                                                              "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
3461                                                      "<br/>\n";
3462                                        }
3463                                        print "</td>\n" .
3464                                              "<td class=\"link\">" .
3465                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3466                                              " | " .
3467                                              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3468                                        print "</td>\n" .
3469                                              "</tr>\n";
3470                                }
3471                                %co = parse_commit($1);
3472                        }
3473                }
3474                close $fd;
3475        }
3476        print "</table>\n";
3477        git_footer_html();
3478}
3479
3480sub git_shortlog {
3481        my $head = git_get_head_hash($project);
3482        if (!defined $hash) {
3483                $hash = $head;
3484        }
3485        if (!defined $page) {
3486                $page = 0;
3487        }
3488        my $refs = git_get_references();
3489
3490        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3491        open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
3492                or die_error(undef, "Open git-rev-list failed");
3493        my @revlist = map { chomp; $_ } <$fd>;
3494        close $fd;
3495
3496        my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
3497        my $next_link = '';
3498        if ($#revlist >= (100 * ($page+1)-1)) {
3499                $next_link =
3500                        $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
3501                                 -title => "Alt-n"}, "next");
3502        }
3503
3504
3505        git_header_html();
3506        git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
3507        git_print_header_div('summary', $project);
3508
3509        git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
3510
3511        git_footer_html();
3512}
3513
3514## ......................................................................
3515## feeds (RSS, OPML)
3516
3517sub git_rss {
3518        # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
3519        open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150", git_get_head_hash($project)
3520                or die_error(undef, "Open git-rev-list failed");
3521        my @revlist = map { chomp; $_ } <$fd>;
3522        close $fd or die_error(undef, "Reading git-rev-list failed");
3523        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3524        print <<XML;
3525<?xml version="1.0" encoding="utf-8"?>
3526<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
3527<channel>
3528<title>$project $my_uri $my_url</title>
3529<link>${\esc_html("$my_url?p=$project;a=summary")}</link>
3530<description>$project log</description>
3531<language>en</language>
3532XML
3533
3534        for (my $i = 0; $i <= $#revlist; $i++) {
3535                my $commit = $revlist[$i];
3536                my %co = parse_commit($commit);
3537                # we read 150, we always show 30 and the ones more recent than 48 hours
3538                if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
3539                        last;
3540                }
3541                my %cd = parse_date($co{'committer_epoch'});
3542                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3543                        $co{'parent'}, $co{'id'}
3544                        or next;
3545                my @difftree = map { chomp; $_ } <$fd>;
3546                close $fd
3547                        or next;
3548                print "<item>\n" .
3549                      "<title>" .
3550                      sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
3551                      "</title>\n" .
3552                      "<author>" . esc_html($co{'author'}) . "</author>\n" .
3553                      "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
3554                      "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
3555                      "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
3556                      "<description>" . esc_html($co{'title'}) . "</description>\n" .
3557                      "<content:encoded>" .
3558                      "<![CDATA[\n";
3559                my $comment = $co{'comment'};
3560                foreach my $line (@$comment) {
3561                        $line = decode("utf8", $line, Encode::FB_DEFAULT);
3562                        print "$line<br/>\n";
3563                }
3564                print "<br/>\n";
3565                foreach my $line (@difftree) {
3566                        if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
3567                                next;
3568                        }
3569                        my $file = esc_html(unquote($7));
3570                        $file = decode("utf8", $file, Encode::FB_DEFAULT);
3571                        print "$file<br/>\n";
3572                }
3573                print "]]>\n" .
3574                      "</content:encoded>\n" .
3575                      "</item>\n";
3576        }
3577        print "</channel></rss>";
3578}
3579
3580sub git_opml {
3581        my @list = git_get_projects_list();
3582
3583        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3584        print <<XML;
3585<?xml version="1.0" encoding="utf-8"?>
3586<opml version="1.0">
3587<head>
3588  <title>$site_name Git OPML Export</title>
3589</head>
3590<body>
3591<outline text="git RSS feeds">
3592XML
3593
3594        foreach my $pr (@list) {
3595                my %proj = %$pr;
3596                my $head = git_get_head_hash($proj{'path'});
3597                if (!defined $head) {
3598                        next;
3599                }
3600                $git_dir = "$projectroot/$proj{'path'}";
3601                my %co = parse_commit($head);
3602                if (!%co) {
3603                        next;
3604                }
3605
3606                my $path = esc_html(chop_str($proj{'path'}, 25, 5));
3607                my $rss  = "$my_url?p=$proj{'path'};a=rss";
3608                my $html = "$my_url?p=$proj{'path'};a=summary";
3609                print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
3610        }
3611        print <<XML;
3612</outline>
3613</body>
3614</opml>
3615XML
3616}