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