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