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