6d53c8b9563da00254272f4cc7863cbc3b173dd1
   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++";
 155require $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## ......................................................................
1038## parse to array of hashes functions
1039
1040sub git_get_refs_list {
1041        my $ref_dir = shift;
1042        my @reflist;
1043
1044        my @refs;
1045        my $pfxlen = length("$projectroot/$project/$ref_dir");
1046        File::Find::find(sub {
1047                return if (/^\./);
1048                if (-f $_) {
1049                        push @refs, substr($File::Find::name, $pfxlen + 1);
1050                }
1051        }, "$projectroot/$project/$ref_dir");
1052
1053        foreach my $ref_file (@refs) {
1054                my $ref_id = git_get_hash_by_ref("$project/$ref_dir/$ref_file");
1055                my $type = git_get_type($ref_id) || next;
1056                my %ref_item = parse_ref($ref_file, $ref_id, $type);
1057
1058                push @reflist, \%ref_item;
1059        }
1060        # sort refs by age
1061        @reflist = sort {$b->{'epoch'} <=> $a->{'epoch'}} @reflist;
1062        return \@reflist;
1063}
1064
1065## ----------------------------------------------------------------------
1066## filesystem-related functions
1067
1068sub get_file_owner {
1069        my $path = shift;
1070
1071        my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1072        my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1073        if (!defined $gcos) {
1074                return undef;
1075        }
1076        my $owner = $gcos;
1077        $owner =~ s/[,;].*$//;
1078        return decode("utf8", $owner, Encode::FB_DEFAULT);
1079}
1080
1081## ......................................................................
1082## mimetype related functions
1083
1084sub mimetype_guess_file {
1085        my $filename = shift;
1086        my $mimemap = shift;
1087        -r $mimemap or return undef;
1088
1089        my %mimemap;
1090        open(MIME, $mimemap) or return undef;
1091        while (<MIME>) {
1092                next if m/^#/; # skip comments
1093                my ($mime, $exts) = split(/\t+/);
1094                if (defined $exts) {
1095                        my @exts = split(/\s+/, $exts);
1096                        foreach my $ext (@exts) {
1097                                $mimemap{$ext} = $mime;
1098                        }
1099                }
1100        }
1101        close(MIME);
1102
1103        $filename =~ /\.(.*?)$/;
1104        return $mimemap{$1};
1105}
1106
1107sub mimetype_guess {
1108        my $filename = shift;
1109        my $mime;
1110        $filename =~ /\./ or return undef;
1111
1112        if ($mimetypes_file) {
1113                my $file = $mimetypes_file;
1114                if ($file !~ m!^/!) { # if it is relative path
1115                        # it is relative to project
1116                        $file = "$projectroot/$project/$file";
1117                }
1118                $mime = mimetype_guess_file($filename, $file);
1119        }
1120        $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1121        return $mime;
1122}
1123
1124sub blob_mimetype {
1125        my $fd = shift;
1126        my $filename = shift;
1127
1128        if ($filename) {
1129                my $mime = mimetype_guess($filename);
1130                $mime and return $mime;
1131        }
1132
1133        # just in case
1134        return $default_blob_plain_mimetype unless $fd;
1135
1136        if (-T $fd) {
1137                return 'text/plain' .
1138                       ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1139        } elsif (! $filename) {
1140                return 'application/octet-stream';
1141        } elsif ($filename =~ m/\.png$/i) {
1142                return 'image/png';
1143        } elsif ($filename =~ m/\.gif$/i) {
1144                return 'image/gif';
1145        } elsif ($filename =~ m/\.jpe?g$/i) {
1146                return 'image/jpeg';
1147        } else {
1148                return 'application/octet-stream';
1149        }
1150}
1151
1152## ======================================================================
1153## functions printing HTML: header, footer, error page
1154
1155sub git_header_html {
1156        my $status = shift || "200 OK";
1157        my $expires = shift;
1158
1159        my $title = "$site_name git";
1160        if (defined $project) {
1161                $title .= " - $project";
1162                if (defined $action) {
1163                        $title .= "/$action";
1164                        if (defined $file_name) {
1165                                $title .= " - $file_name";
1166                                if ($action eq "tree" && $file_name !~ m|/$|) {
1167                                        $title .= "/";
1168                                }
1169                        }
1170                }
1171        }
1172        my $content_type;
1173        # require explicit support from the UA if we are to send the page as
1174        # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1175        # we have to do this because MSIE sometimes globs '*/*', pretending to
1176        # support xhtml+xml but choking when it gets what it asked for.
1177        if (defined $cgi->http('HTTP_ACCEPT') &&
1178            $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1179            $cgi->Accept('application/xhtml+xml') != 0) {
1180                $content_type = 'application/xhtml+xml';
1181        } else {
1182                $content_type = 'text/html';
1183        }
1184        print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1185                           -status=> $status, -expires => $expires);
1186        print <<EOF;
1187<?xml version="1.0" encoding="utf-8"?>
1188<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1189<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1190<!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1191<!-- git core binaries version $git_version -->
1192<head>
1193<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1194<meta name="generator" content="gitweb/$version git/$git_version"/>
1195<meta name="robots" content="index, nofollow"/>
1196<title>$title</title>
1197<link rel="stylesheet" type="text/css" href="$stylesheet"/>
1198EOF
1199        if (defined $project) {
1200                printf('<link rel="alternate" title="%s log" '.
1201                       'href="%s" type="application/rss+xml"/>'."\n",
1202                       esc_param($project), href(action=>"rss"));
1203        }
1204
1205        print "</head>\n" .
1206              "<body>\n" .
1207              "<div class=\"page_header\">\n" .
1208              "<a href=\"http://www.kernel.org/pub/software/scm/git/docs/\" title=\"git documentation\">" .
1209              "<img src=\"$logo\" width=\"72\" height=\"27\" alt=\"git\" style=\"float:right; border-width:0px;\"/>" .
1210              "</a>\n";
1211        print $cgi->a({-href => esc_param($home_link)}, $home_link_str) . " / ";
1212        if (defined $project) {
1213                print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1214                if (defined $action) {
1215                        print " / $action";
1216                }
1217                print "\n";
1218                if (!defined $searchtext) {
1219                        $searchtext = "";
1220                }
1221                my $search_hash;
1222                if (defined $hash_base) {
1223                        $search_hash = $hash_base;
1224                } elsif (defined $hash) {
1225                        $search_hash = $hash;
1226                } else {
1227                        $search_hash = "HEAD";
1228                }
1229                $cgi->param("a", "search");
1230                $cgi->param("h", $search_hash);
1231                print $cgi->startform(-method => "get", -action => $my_uri) .
1232                      "<div class=\"search\">\n" .
1233                      $cgi->hidden(-name => "p") . "\n" .
1234                      $cgi->hidden(-name => "a") . "\n" .
1235                      $cgi->hidden(-name => "h") . "\n" .
1236                      $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1237                      "</div>" .
1238                      $cgi->end_form() . "\n";
1239        }
1240        print "</div>\n";
1241}
1242
1243sub git_footer_html {
1244        print "<div class=\"page_footer\">\n";
1245        if (defined $project) {
1246                my $descr = git_get_project_description($project);
1247                if (defined $descr) {
1248                        print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1249                }
1250                print $cgi->a({-href => href(action=>"rss"), -class => "rss_logo"}, "RSS") . "\n";
1251        } else {
1252                print $cgi->a({-href => href(action=>"opml"), -class => "rss_logo"}, "OPML") . "\n";
1253        }
1254        print "</div>\n" .
1255              "</body>\n" .
1256              "</html>";
1257}
1258
1259sub die_error {
1260        my $status = shift || "403 Forbidden";
1261        my $error = shift || "Malformed query, file missing or permission denied";
1262
1263        git_header_html($status);
1264        print <<EOF;
1265<div class="page_body">
1266<br /><br />
1267$status - $error
1268<br />
1269</div>
1270EOF
1271        git_footer_html();
1272        exit;
1273}
1274
1275## ----------------------------------------------------------------------
1276## functions printing or outputting HTML: navigation
1277
1278sub git_print_page_nav {
1279        my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1280        $extra = '' if !defined $extra; # pager or formats
1281
1282        my @navs = qw(summary shortlog log commit commitdiff tree);
1283        if ($suppress) {
1284                @navs = grep { $_ ne $suppress } @navs;
1285        }
1286
1287        my %arg = map { $_ => {action=>$_} } @navs;
1288        if (defined $head) {
1289                for (qw(commit commitdiff)) {
1290                        $arg{$_}{hash} = $head;
1291                }
1292                if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1293                        for (qw(shortlog log)) {
1294                                $arg{$_}{hash} = $head;
1295                        }
1296                }
1297        }
1298        $arg{tree}{hash} = $treehead if defined $treehead;
1299        $arg{tree}{hash_base} = $treebase if defined $treebase;
1300
1301        print "<div class=\"page_nav\">\n" .
1302                (join " | ",
1303                 map { $_ eq $current ?
1304                       $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1305                 } @navs);
1306        print "<br/>\n$extra<br/>\n" .
1307              "</div>\n";
1308}
1309
1310sub format_paging_nav {
1311        my ($action, $hash, $head, $page, $nrevs) = @_;
1312        my $paging_nav;
1313
1314
1315        if ($hash ne $head || $page) {
1316                $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1317        } else {
1318                $paging_nav .= "HEAD";
1319        }
1320
1321        if ($page > 0) {
1322                $paging_nav .= " &sdot; " .
1323                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1324                                 -accesskey => "p", -title => "Alt-p"}, "prev");
1325        } else {
1326                $paging_nav .= " &sdot; prev";
1327        }
1328
1329        if ($nrevs >= (100 * ($page+1)-1)) {
1330                $paging_nav .= " &sdot; " .
1331                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1332                                 -accesskey => "n", -title => "Alt-n"}, "next");
1333        } else {
1334                $paging_nav .= " &sdot; next";
1335        }
1336
1337        return $paging_nav;
1338}
1339
1340## ......................................................................
1341## functions printing or outputting HTML: div
1342
1343sub git_print_header_div {
1344        my ($action, $title, $hash, $hash_base) = @_;
1345        my %args = ();
1346
1347        $args{action} = $action;
1348        $args{hash} = $hash if $hash;
1349        $args{hash_base} = $hash_base if $hash_base;
1350
1351        print "<div class=\"header\">\n" .
1352              $cgi->a({-href => href(%args), -class => "title"},
1353              $title ? $title : $action) .
1354              "\n</div>\n";
1355}
1356
1357#sub git_print_authorship (\%) {
1358sub git_print_authorship {
1359        my $co = shift;
1360
1361        my %ad = parse_date($co->{'author_epoch'});
1362        print "<div class=\"author_date\">" .
1363              esc_html($co->{'author_name'}) .
1364              " [$ad{'rfc2822'}]</div>\n";
1365}
1366
1367sub git_print_page_path {
1368        my $name = shift;
1369        my $type = shift;
1370        my $hb = shift;
1371
1372        if (!defined $name) {
1373                print "<div class=\"page_path\">/</div>\n";
1374        } elsif (defined $type && $type eq 'blob') {
1375                print "<div class=\"page_path\">";
1376                if (defined $hb) {
1377                        print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1378                                                     hash_base=>$hb)},
1379                                      esc_html($name));
1380                } else {
1381                        print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name)},
1382                                      esc_html($name));
1383                }
1384                print "<br/></div>\n";
1385        } else {
1386                print "<div class=\"page_path\">" . esc_html($name) . "<br/></div>\n";
1387        }
1388}
1389
1390# sub git_print_log (\@;%) {
1391sub git_print_log ($;%) {
1392        my $log = shift;
1393        my %opts = @_;
1394
1395        if ($opts{'-remove_title'}) {
1396                # remove title, i.e. first line of log
1397                shift @$log;
1398        }
1399        # remove leading empty lines
1400        while (defined $log->[0] && $log->[0] eq "") {
1401                shift @$log;
1402        }
1403
1404        # print log
1405        my $signoff = 0;
1406        my $empty = 0;
1407        foreach my $line (@$log) {
1408                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1409                        $signoff = 1;
1410                        if (! $opts{'-remove_signoff'}) {
1411                                print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1412                                next;
1413                        } else {
1414                                # remove signoff lines
1415                                next;
1416                        }
1417                } else {
1418                        $signoff = 0;
1419                }
1420
1421                # print only one empty line
1422                # do not print empty line after signoff
1423                if ($line eq "") {
1424                        next if ($empty || $signoff);
1425                        $empty = 1;
1426                } else {
1427                        $empty = 0;
1428                }
1429
1430                print format_log_line_html($line) . "<br/>\n";
1431        }
1432
1433        if ($opts{'-final_empty_line'}) {
1434                # end with single empty line
1435                print "<br/>\n" unless $empty;
1436        }
1437}
1438
1439sub git_print_simplified_log {
1440        my $log = shift;
1441        my $remove_title = shift;
1442
1443        git_print_log($log,
1444                -final_empty_line=> 1,
1445                -remove_title => $remove_title);
1446}
1447
1448## ......................................................................
1449## functions printing large fragments of HTML
1450
1451sub git_difftree_body {
1452        my ($difftree, $hash, $parent) = @_;
1453
1454        print "<div class=\"list_head\">\n";
1455        if ($#{$difftree} > 10) {
1456                print(($#{$difftree} + 1) . " files changed:\n");
1457        }
1458        print "</div>\n";
1459
1460        print "<table class=\"diff_tree\">\n";
1461        my $alternate = 0;
1462        foreach my $line (@{$difftree}) {
1463                my %diff = parse_difftree_raw_line($line);
1464
1465                if ($alternate) {
1466                        print "<tr class=\"dark\">\n";
1467                } else {
1468                        print "<tr class=\"light\">\n";
1469                }
1470                $alternate ^= 1;
1471
1472                my ($to_mode_oct, $to_mode_str, $to_file_type);
1473                my ($from_mode_oct, $from_mode_str, $from_file_type);
1474                if ($diff{'to_mode'} ne ('0' x 6)) {
1475                        $to_mode_oct = oct $diff{'to_mode'};
1476                        if (S_ISREG($to_mode_oct)) { # only for regular file
1477                                $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
1478                        }
1479                        $to_file_type = file_type($diff{'to_mode'});
1480                }
1481                if ($diff{'from_mode'} ne ('0' x 6)) {
1482                        $from_mode_oct = oct $diff{'from_mode'};
1483                        if (S_ISREG($to_mode_oct)) { # only for regular file
1484                                $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
1485                        }
1486                        $from_file_type = file_type($diff{'from_mode'});
1487                }
1488
1489                if ($diff{'status'} eq "A") { # created
1490                        my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
1491                        $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
1492                        $mode_chng   .= "]</span>";
1493                        print "<td>" .
1494                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1495                                                     hash_base=>$hash, file_name=>$diff{'file'}),
1496                                      -class => "list"}, esc_html($diff{'file'})) .
1497                              "</td>\n" .
1498                              "<td>$mode_chng</td>\n" .
1499                              "<td class=\"link\">" .
1500                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1501                                                     hash_base=>$hash, file_name=>$diff{'file'})},
1502                                      "blob") .
1503                              "</td>\n";
1504
1505                } elsif ($diff{'status'} eq "D") { # deleted
1506                        my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
1507                        print "<td>" .
1508                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1509                                                     hash_base=>$parent, file_name=>$diff{'file'}),
1510                                       -class => "list"}, esc_html($diff{'file'})) .
1511                              "</td>\n" .
1512                              "<td>$mode_chng</td>\n" .
1513                              "<td class=\"link\">" .
1514                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1515                                                     hash_base=>$parent, file_name=>$diff{'file'})},
1516                                      "blob") .
1517                              " | " .
1518                              $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1519                                                     file_name=>$diff{'file'})},
1520                                      "history") .
1521                              "</td>\n";
1522
1523                } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
1524                        my $mode_chnge = "";
1525                        if ($diff{'from_mode'} != $diff{'to_mode'}) {
1526                                $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
1527                                if ($from_file_type != $to_file_type) {
1528                                        $mode_chnge .= " from $from_file_type to $to_file_type";
1529                                }
1530                                if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
1531                                        if ($from_mode_str && $to_mode_str) {
1532                                                $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
1533                                        } elsif ($to_mode_str) {
1534                                                $mode_chnge .= " mode: $to_mode_str";
1535                                        }
1536                                }
1537                                $mode_chnge .= "]</span>\n";
1538                        }
1539                        print "<td>";
1540                        if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1541                                print $cgi->a({-href => href(action=>"blobdiff",
1542                                                             hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1543                                                             hash_base=>$hash, hash_parent_base=>$parent,
1544                                                             file_name=>$diff{'file'}),
1545                                              -class => "list"}, esc_html($diff{'file'}));
1546                        } else { # only mode changed
1547                                print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1548                                                             hash_base=>$hash, file_name=>$diff{'file'}),
1549                                              -class => "list"}, esc_html($diff{'file'}));
1550                        }
1551                        print "</td>\n" .
1552                              "<td>$mode_chnge</td>\n" .
1553                              "<td class=\"link\">" .
1554                                $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1555                                                       hash_base=>$hash, file_name=>$diff{'file'})},
1556                                        "blob");
1557                        if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1558                                print " | " .
1559                                        $cgi->a({-href => href(action=>"blobdiff",
1560                                                               hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1561                                                               hash_base=>$hash, hash_parent_base=>$parent,
1562                                                               file_name=>$diff{'file'})},
1563                                                "diff");
1564                        }
1565                        print " | " .
1566                                $cgi->a({-href => href(action=>"history",
1567                                                       hash_base=>$hash, file_name=>$diff{'file'})},
1568                                        "history");
1569                        print "</td>\n";
1570
1571                } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
1572                        my %status_name = ('R' => 'moved', 'C' => 'copied');
1573                        my $nstatus = $status_name{$diff{'status'}};
1574                        my $mode_chng = "";
1575                        if ($diff{'from_mode'} != $diff{'to_mode'}) {
1576                                # mode also for directories, so we cannot use $to_mode_str
1577                                $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
1578                        }
1579                        print "<td>" .
1580                              $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1581                                                     hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
1582                                      -class => "list"}, esc_html($diff{'to_file'})) . "</td>\n" .
1583                              "<td><span class=\"file_status $nstatus\">[$nstatus from " .
1584                              $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
1585                                                     hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
1586                                      -class => "list"}, esc_html($diff{'from_file'})) .
1587                              " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
1588                              "<td class=\"link\">" .
1589                              $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1590                                                     hash=>$diff{'to_id'}, file_name=>$diff{'to_file'})},
1591                                      "blob");
1592                        if ($diff{'to_id'} ne $diff{'from_id'}) {
1593                                print " | " .
1594                                        $cgi->a({-href => href(action=>"blobdiff",
1595                                                               hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1596                                                               hash_base=>$hash, hash_parent_base=>$parent,
1597                                                               file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
1598                                                "diff");
1599                        }
1600                        print "</td>\n";
1601
1602                } # we should not encounter Unmerged (U) or Unknown (X) status
1603                print "</tr>\n";
1604        }
1605        print "</table>\n";
1606}
1607
1608sub git_patchset_body {
1609        my ($fd, $difftree, $hash, $hash_parent) = @_;
1610
1611        my $patch_idx = 0;
1612        my $in_header = 0;
1613        my $patch_found = 0;
1614        my $diffinfo;
1615
1616        print "<div class=\"patchset\">\n";
1617
1618        LINE:
1619        while (my $patch_line = <$fd>) {
1620                chomp $patch_line;
1621
1622                if ($patch_line =~ m/^diff /) { # "git diff" header
1623                        # beginning of patch (in patchset)
1624                        if ($patch_found) {
1625                                # close previous patch
1626                                print "</div>\n"; # class="patch"
1627                        } else {
1628                                # first patch in patchset
1629                                $patch_found = 1;
1630                        }
1631                        print "<div class=\"patch\">\n";
1632
1633                        if (ref($difftree->[$patch_idx]) eq "HASH") {
1634                                $diffinfo = $difftree->[$patch_idx];
1635                        } else {
1636                                $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
1637                        }
1638                        $patch_idx++;
1639
1640                        # for now, no extended header, hence we skip empty patches
1641                        # companion to  next LINE if $in_header;
1642                        if ($diffinfo->{'from_id'} eq $diffinfo->{'to_id'}) { # no change
1643                                $in_header = 1;
1644                                next LINE;
1645                        }
1646
1647                        if ($diffinfo->{'status'} eq "A") { # added
1648                                print "<div class=\"diff_info\">" . file_type($diffinfo->{'to_mode'}) . ":" .
1649                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1650                                                             hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1651                                              $diffinfo->{'to_id'}) . "(new)" .
1652                                      "</div>\n"; # class="diff_info"
1653
1654                        } elsif ($diffinfo->{'status'} eq "D") { # deleted
1655                                print "<div class=\"diff_info\">" . file_type($diffinfo->{'from_mode'}) . ":" .
1656                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1657                                                             hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1658                                              $diffinfo->{'from_id'}) . "(deleted)" .
1659                                      "</div>\n"; # class="diff_info"
1660
1661                        } elsif ($diffinfo->{'status'} eq "R" || # renamed
1662                                 $diffinfo->{'status'} eq "C" || # copied
1663                                 $diffinfo->{'status'} eq "2") { # with two filenames (from git_blobdiff)
1664                                print "<div class=\"diff_info\">" .
1665                                      file_type($diffinfo->{'from_mode'}) . ":" .
1666                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1667                                                             hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'from_file'})},
1668                                              $diffinfo->{'from_id'}) .
1669                                      " -> " .
1670                                      file_type($diffinfo->{'to_mode'}) . ":" .
1671                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1672                                                             hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'to_file'})},
1673                                              $diffinfo->{'to_id'});
1674                                print "</div>\n"; # class="diff_info"
1675
1676                        } else { # modified, mode changed, ...
1677                                print "<div class=\"diff_info\">" .
1678                                      file_type($diffinfo->{'from_mode'}) . ":" .
1679                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1680                                                             hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1681                                              $diffinfo->{'from_id'}) .
1682                                      " -> " .
1683                                      file_type($diffinfo->{'to_mode'}) . ":" .
1684                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1685                                                             hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1686                                              $diffinfo->{'to_id'});
1687                                print "</div>\n"; # class="diff_info"
1688                        }
1689
1690                        #print "<div class=\"diff extended_header\">\n";
1691                        $in_header = 1;
1692                        next LINE;
1693                } # start of patch in patchset
1694
1695
1696                if ($in_header && $patch_line =~ m/^---/) {
1697                        #print "</div>\n"; # class="diff extended_header"
1698                        $in_header = 0;
1699
1700                        my $file = $diffinfo->{'from_file'};
1701                        $file  ||= $diffinfo->{'file'};
1702                        $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1703                                                       hash=>$diffinfo->{'from_id'}, file_name=>$file),
1704                                        -class => "list"}, esc_html($file));
1705                        $patch_line =~ s|a/.*$|a/$file|g;
1706                        print "<div class=\"diff from_file\">$patch_line</div>\n";
1707
1708                        $patch_line = <$fd>;
1709                        chomp $patch_line;
1710
1711                        #$patch_line =~ m/^+++/;
1712                        $file    = $diffinfo->{'to_file'};
1713                        $file  ||= $diffinfo->{'file'};
1714                        $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1715                                                       hash=>$diffinfo->{'to_id'}, file_name=>$file),
1716                                        -class => "list"}, esc_html($file));
1717                        $patch_line =~ s|b/.*|b/$file|g;
1718                        print "<div class=\"diff to_file\">$patch_line</div>\n";
1719
1720                        next LINE;
1721                }
1722                next LINE if $in_header;
1723
1724                print format_diff_line($patch_line);
1725        }
1726        print "</div>\n" if $patch_found; # class="patch"
1727
1728        print "</div>\n"; # class="patchset"
1729}
1730
1731# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1732
1733sub git_shortlog_body {
1734        # uses global variable $project
1735        my ($revlist, $from, $to, $refs, $extra) = @_;
1736
1737        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
1738        my $have_snapshot = (defined $ctype && defined $suffix);
1739
1740        $from = 0 unless defined $from;
1741        $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
1742
1743        print "<table class=\"shortlog\" cellspacing=\"0\">\n";
1744        my $alternate = 0;
1745        for (my $i = $from; $i <= $to; $i++) {
1746                my $commit = $revlist->[$i];
1747                #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
1748                my $ref = format_ref_marker($refs, $commit);
1749                my %co = parse_commit($commit);
1750                if ($alternate) {
1751                        print "<tr class=\"dark\">\n";
1752                } else {
1753                        print "<tr class=\"light\">\n";
1754                }
1755                $alternate ^= 1;
1756                # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
1757                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1758                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
1759                      "<td>";
1760                print format_subject_html($co{'title'}, $co{'title_short'},
1761                                          href(action=>"commit", hash=>$commit), $ref);
1762                print "</td>\n" .
1763                      "<td class=\"link\">" .
1764                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1765                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
1766                if ($have_snapshot) {
1767                        print " | " .  $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
1768                }
1769                print "</td>\n" .
1770                      "</tr>\n";
1771        }
1772        if (defined $extra) {
1773                print "<tr>\n" .
1774                      "<td colspan=\"4\">$extra</td>\n" .
1775                      "</tr>\n";
1776        }
1777        print "</table>\n";
1778}
1779
1780sub git_history_body {
1781        # Warning: assumes constant type (blob or tree) during history
1782        my ($fd, $refs, $hash_base, $ftype, $extra) = @_;
1783
1784        print "<table class=\"history\" cellspacing=\"0\">\n";
1785        my $alternate = 0;
1786        while (my $line = <$fd>) {
1787                if ($line !~ m/^([0-9a-fA-F]{40})/) {
1788                        next;
1789                }
1790
1791                my $commit = $1;
1792                my %co = parse_commit($commit);
1793                if (!%co) {
1794                        next;
1795                }
1796
1797                my $ref = format_ref_marker($refs, $commit);
1798
1799                if ($alternate) {
1800                        print "<tr class=\"dark\">\n";
1801                } else {
1802                        print "<tr class=\"light\">\n";
1803                }
1804                $alternate ^= 1;
1805                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1806                      # shortlog uses      chop_str($co{'author_name'}, 10)
1807                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
1808                      "<td>";
1809                # originally git_history used chop_str($co{'title'}, 50)
1810                print format_subject_html($co{'title'}, $co{'title_short'},
1811                                          href(action=>"commit", hash=>$commit), $ref);
1812                print "</td>\n" .
1813                      "<td class=\"link\">" .
1814                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1815                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
1816                      $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype);
1817
1818                if ($ftype eq 'blob') {
1819                        my $blob_current = git_get_hash_by_path($hash_base, $file_name);
1820                        my $blob_parent  = git_get_hash_by_path($commit, $file_name);
1821                        if (defined $blob_current && defined $blob_parent &&
1822                                        $blob_current ne $blob_parent) {
1823                                print " | " .
1824                                        $cgi->a({-href => href(action=>"blobdiff",
1825                                                               hash=>$blob_current, hash_parent=>$blob_parent,
1826                                                               hash_base=>$hash_base, hash_parent_base=>$commit,
1827                                                               file_name=>$file_name)},
1828                                                "diff to current");
1829                        }
1830                }
1831                print "</td>\n" .
1832                      "</tr>\n";
1833        }
1834        if (defined $extra) {
1835                print "<tr>\n" .
1836                      "<td colspan=\"4\">$extra</td>\n" .
1837                      "</tr>\n";
1838        }
1839        print "</table>\n";
1840}
1841
1842sub git_tags_body {
1843        # uses global variable $project
1844        my ($taglist, $from, $to, $extra) = @_;
1845        $from = 0 unless defined $from;
1846        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
1847
1848        print "<table class=\"tags\" cellspacing=\"0\">\n";
1849        my $alternate = 0;
1850        for (my $i = $from; $i <= $to; $i++) {
1851                my $entry = $taglist->[$i];
1852                my %tag = %$entry;
1853                my $comment_lines = $tag{'comment'};
1854                my $comment = shift @$comment_lines;
1855                my $comment_short;
1856                if (defined $comment) {
1857                        $comment_short = chop_str($comment, 30, 5);
1858                }
1859                if ($alternate) {
1860                        print "<tr class=\"dark\">\n";
1861                } else {
1862                        print "<tr class=\"light\">\n";
1863                }
1864                $alternate ^= 1;
1865                print "<td><i>$tag{'age'}</i></td>\n" .
1866                      "<td>" .
1867                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
1868                               -class => "list name"}, esc_html($tag{'name'})) .
1869                      "</td>\n" .
1870                      "<td>";
1871                if (defined $comment) {
1872                        print format_subject_html($comment, $comment_short,
1873                                                  href(action=>"tag", hash=>$tag{'id'}));
1874                }
1875                print "</td>\n" .
1876                      "<td class=\"selflink\">";
1877                if ($tag{'type'} eq "tag") {
1878                        print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
1879                } else {
1880                        print "&nbsp;";
1881                }
1882                print "</td>\n" .
1883                      "<td class=\"link\">" . " | " .
1884                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
1885                if ($tag{'reftype'} eq "commit") {
1886                        print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
1887                              " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'refid'})}, "log");
1888                } elsif ($tag{'reftype'} eq "blob") {
1889                        print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
1890                }
1891                print "</td>\n" .
1892                      "</tr>";
1893        }
1894        if (defined $extra) {
1895                print "<tr>\n" .
1896                      "<td colspan=\"5\">$extra</td>\n" .
1897                      "</tr>\n";
1898        }
1899        print "</table>\n";
1900}
1901
1902sub git_heads_body {
1903        # uses global variable $project
1904        my ($taglist, $head, $from, $to, $extra) = @_;
1905        $from = 0 unless defined $from;
1906        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
1907
1908        print "<table class=\"heads\" cellspacing=\"0\">\n";
1909        my $alternate = 0;
1910        for (my $i = $from; $i <= $to; $i++) {
1911                my $entry = $taglist->[$i];
1912                my %tag = %$entry;
1913                my $curr = $tag{'id'} eq $head;
1914                if ($alternate) {
1915                        print "<tr class=\"dark\">\n";
1916                } else {
1917                        print "<tr class=\"light\">\n";
1918                }
1919                $alternate ^= 1;
1920                print "<td><i>$tag{'age'}</i></td>\n" .
1921                      ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
1922                      $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'}),
1923                               -class => "list name"},esc_html($tag{'name'})) .
1924                      "</td>\n" .
1925                      "<td class=\"link\">" .
1926                      $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") . " | " .
1927                      $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log") .
1928                      "</td>\n" .
1929                      "</tr>";
1930        }
1931        if (defined $extra) {
1932                print "<tr>\n" .
1933                      "<td colspan=\"3\">$extra</td>\n" .
1934                      "</tr>\n";
1935        }
1936        print "</table>\n";
1937}
1938
1939## ======================================================================
1940## ======================================================================
1941## actions
1942
1943sub git_project_list {
1944        my $order = $cgi->param('o');
1945        if (defined $order && $order !~ m/project|descr|owner|age/) {
1946                die_error(undef, "Unknown order parameter");
1947        }
1948
1949        my @list = git_get_projects_list();
1950        my @projects;
1951        if (!@list) {
1952                die_error(undef, "No projects found");
1953        }
1954        foreach my $pr (@list) {
1955                my $head = git_get_head_hash($pr->{'path'});
1956                if (!defined $head) {
1957                        next;
1958                }
1959                $git_dir = "$projectroot/$pr->{'path'}";
1960                my %co = parse_commit($head);
1961                if (!%co) {
1962                        next;
1963                }
1964                $pr->{'commit'} = \%co;
1965                if (!defined $pr->{'descr'}) {
1966                        my $descr = git_get_project_description($pr->{'path'}) || "";
1967                        $pr->{'descr'} = chop_str($descr, 25, 5);
1968                }
1969                if (!defined $pr->{'owner'}) {
1970                        $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
1971                }
1972                push @projects, $pr;
1973        }
1974
1975        git_header_html();
1976        if (-f $home_text) {
1977                print "<div class=\"index_include\">\n";
1978                open (my $fd, $home_text);
1979                print <$fd>;
1980                close $fd;
1981                print "</div>\n";
1982        }
1983        print "<table class=\"project_list\">\n" .
1984              "<tr>\n";
1985        $order ||= "project";
1986        if ($order eq "project") {
1987                @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
1988                print "<th>Project</th>\n";
1989        } else {
1990                print "<th>" .
1991                      $cgi->a({-href => "$my_uri?" . esc_param("o=project"),
1992                               -class => "header"}, "Project") .
1993                      "</th>\n";
1994        }
1995        if ($order eq "descr") {
1996                @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
1997                print "<th>Description</th>\n";
1998        } else {
1999                print "<th>" .
2000                      $cgi->a({-href => "$my_uri?" . esc_param("o=descr"),
2001                               -class => "header"}, "Description") .
2002                      "</th>\n";
2003        }
2004        if ($order eq "owner") {
2005                @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2006                print "<th>Owner</th>\n";
2007        } else {
2008                print "<th>" .
2009                      $cgi->a({-href => "$my_uri?" . esc_param("o=owner"),
2010                               -class => "header"}, "Owner") .
2011                      "</th>\n";
2012        }
2013        if ($order eq "age") {
2014                @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
2015                print "<th>Last Change</th>\n";
2016        } else {
2017                print "<th>" .
2018                      $cgi->a({-href => "$my_uri?" . esc_param("o=age"),
2019                               -class => "header"}, "Last Change") .
2020                      "</th>\n";
2021        }
2022        print "<th></th>\n" .
2023              "</tr>\n";
2024        my $alternate = 0;
2025        foreach my $pr (@projects) {
2026                if ($alternate) {
2027                        print "<tr class=\"dark\">\n";
2028                } else {
2029                        print "<tr class=\"light\">\n";
2030                }
2031                $alternate ^= 1;
2032                print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2033                                        -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2034                      "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
2035                      "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2036                print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" .
2037                      $pr->{'commit'}{'age_string'} . "</td>\n" .
2038                      "<td class=\"link\">" .
2039                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2040                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
2041                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") .
2042                      "</td>\n" .
2043                      "</tr>\n";
2044        }
2045        print "</table>\n";
2046        git_footer_html();
2047}
2048
2049sub git_summary {
2050        my $descr = git_get_project_description($project) || "none";
2051        my $head = git_get_head_hash($project);
2052        my %co = parse_commit($head);
2053        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2054
2055        my $owner = git_get_project_owner($project);
2056
2057        my $refs = git_get_references();
2058        git_header_html();
2059        git_print_page_nav('summary','', $head);
2060
2061        print "<div class=\"title\">&nbsp;</div>\n";
2062        print "<table cellspacing=\"0\">\n" .
2063              "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
2064              "<tr><td>owner</td><td>$owner</td></tr>\n" .
2065              "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
2066        # use per project git URL list in $projectroot/$project/cloneurl
2067        # or make project git URL from git base URL and project name
2068        my $url_tag = "URL";
2069        my @url_list = git_get_project_url_list($project);
2070        @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
2071        foreach my $git_url (@url_list) {
2072                next unless $git_url;
2073                print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
2074                $url_tag = "";
2075        }
2076        print "</table>\n";
2077
2078        open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
2079                git_get_head_hash($project)
2080                or die_error(undef, "Open git-rev-list failed");
2081        my @revlist = map { chomp; $_ } <$fd>;
2082        close $fd;
2083        git_print_header_div('shortlog');
2084        git_shortlog_body(\@revlist, 0, 15, $refs,
2085                          $cgi->a({-href => href(action=>"shortlog")}, "..."));
2086
2087        my $taglist = git_get_refs_list("refs/tags");
2088        if (defined @$taglist) {
2089                git_print_header_div('tags');
2090                git_tags_body($taglist, 0, 15,
2091                              $cgi->a({-href => href(action=>"tags")}, "..."));
2092        }
2093
2094        my $headlist = git_get_refs_list("refs/heads");
2095        if (defined @$headlist) {
2096                git_print_header_div('heads');
2097                git_heads_body($headlist, $head, 0, 15,
2098                               $cgi->a({-href => href(action=>"heads")}, "..."));
2099        }
2100
2101        git_footer_html();
2102}
2103
2104sub git_tag {
2105        my $head = git_get_head_hash($project);
2106        git_header_html();
2107        git_print_page_nav('','', $head,undef,$head);
2108        my %tag = parse_tag($hash);
2109        git_print_header_div('commit', esc_html($tag{'name'}), $hash);
2110        print "<div class=\"title_text\">\n" .
2111              "<table cellspacing=\"0\">\n" .
2112              "<tr>\n" .
2113              "<td>object</td>\n" .
2114              "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2115                               $tag{'object'}) . "</td>\n" .
2116              "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2117                                              $tag{'type'}) . "</td>\n" .
2118              "</tr>\n";
2119        if (defined($tag{'author'})) {
2120                my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
2121                print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
2122                print "<tr><td></td><td>" . $ad{'rfc2822'} .
2123                        sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
2124                        "</td></tr>\n";
2125        }
2126        print "</table>\n\n" .
2127              "</div>\n";
2128        print "<div class=\"page_body\">";
2129        my $comment = $tag{'comment'};
2130        foreach my $line (@$comment) {
2131                print esc_html($line) . "<br/>\n";
2132        }
2133        print "</div>\n";
2134        git_footer_html();
2135}
2136
2137sub git_blame2 {
2138        my $fd;
2139        my $ftype;
2140
2141        if (!gitweb_check_feature('blame')) {
2142                die_error('403 Permission denied', "Permission denied");
2143        }
2144        die_error('404 Not Found', "File name not defined") if (!$file_name);
2145        $hash_base ||= git_get_head_hash($project);
2146        die_error(undef, "Couldn't find base commit") unless ($hash_base);
2147        my %co = parse_commit($hash_base)
2148                or die_error(undef, "Reading commit failed");
2149        if (!defined $hash) {
2150                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2151                        or die_error(undef, "Error looking up file");
2152        }
2153        $ftype = git_get_type($hash);
2154        if ($ftype !~ "blob") {
2155                die_error("400 Bad Request", "Object is not a blob");
2156        }
2157        open ($fd, "-|", git_cmd(), "blame", '-l', $file_name, $hash_base)
2158                or die_error(undef, "Open git-blame failed");
2159        git_header_html();
2160        my $formats_nav =
2161                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2162                        "blob") .
2163                " | " .
2164                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2165                        "head");
2166        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2167        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2168        git_print_page_path($file_name, $ftype, $hash_base);
2169        my @rev_color = (qw(light2 dark2));
2170        my $num_colors = scalar(@rev_color);
2171        my $current_color = 0;
2172        my $last_rev;
2173        print <<HTML;
2174<div class="page_body">
2175<table class="blame">
2176<tr><th>Commit</th><th>Line</th><th>Data</th></tr>
2177HTML
2178        while (<$fd>) {
2179                /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
2180                my $full_rev = $1;
2181                my $rev = substr($full_rev, 0, 8);
2182                my $lineno = $2;
2183                my $data = $3;
2184
2185                if (!defined $last_rev) {
2186                        $last_rev = $full_rev;
2187                } elsif ($last_rev ne $full_rev) {
2188                        $last_rev = $full_rev;
2189                        $current_color = ++$current_color % $num_colors;
2190                }
2191                print "<tr class=\"$rev_color[$current_color]\">\n";
2192                print "<td class=\"sha1\">" .
2193                        $cgi->a({-href => href(action=>"commit", hash=>$full_rev, file_name=>$file_name)},
2194                                esc_html($rev)) . "</td>\n";
2195                print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" .
2196                      esc_html($lineno) . "</a></td>\n";
2197                print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
2198                print "</tr>\n";
2199        }
2200        print "</table>\n";
2201        print "</div>";
2202        close $fd
2203                or print "Reading blob failed\n";
2204        git_footer_html();
2205}
2206
2207sub git_blame {
2208        my $fd;
2209
2210        if (!gitweb_check_feature('blame')) {
2211                die_error('403 Permission denied', "Permission denied");
2212        }
2213        die_error('404 Not Found', "File name not defined") if (!$file_name);
2214        $hash_base ||= git_get_head_hash($project);
2215        die_error(undef, "Couldn't find base commit") unless ($hash_base);
2216        my %co = parse_commit($hash_base)
2217                or die_error(undef, "Reading commit failed");
2218        if (!defined $hash) {
2219                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2220                        or die_error(undef, "Error lookup file");
2221        }
2222        open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
2223                or die_error(undef, "Open git-annotate failed");
2224        git_header_html();
2225        my $formats_nav =
2226                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2227                        "blob") .
2228                " | " .
2229                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2230                        "head");
2231        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2232        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2233        git_print_page_path($file_name, 'blob', $hash_base);
2234        print "<div class=\"page_body\">\n";
2235        print <<HTML;
2236<table class="blame">
2237  <tr>
2238    <th>Commit</th>
2239    <th>Age</th>
2240    <th>Author</th>
2241    <th>Line</th>
2242    <th>Data</th>
2243  </tr>
2244HTML
2245        my @line_class = (qw(light dark));
2246        my $line_class_len = scalar (@line_class);
2247        my $line_class_num = $#line_class;
2248        while (my $line = <$fd>) {
2249                my $long_rev;
2250                my $short_rev;
2251                my $author;
2252                my $time;
2253                my $lineno;
2254                my $data;
2255                my $age;
2256                my $age_str;
2257                my $age_class;
2258
2259                chomp $line;
2260                $line_class_num = ($line_class_num + 1) % $line_class_len;
2261
2262                if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
2263                        $long_rev = $1;
2264                        $author   = $2;
2265                        $time     = $3;
2266                        $lineno   = $4;
2267                        $data     = $5;
2268                } else {
2269                        print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
2270                        next;
2271                }
2272                $short_rev  = substr ($long_rev, 0, 8);
2273                $age        = time () - $time;
2274                $age_str    = age_string ($age);
2275                $age_str    =~ s/ /&nbsp;/g;
2276                $age_class  = age_class($age);
2277                $author     = esc_html ($author);
2278                $author     =~ s/ /&nbsp;/g;
2279
2280                $data = untabify($data);
2281                $data = esc_html ($data);
2282
2283                print <<HTML;
2284  <tr class="$line_class[$line_class_num]">
2285    <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
2286    <td class="$age_class">$age_str</td>
2287    <td>$author</td>
2288    <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
2289    <td class="pre">$data</td>
2290  </tr>
2291HTML
2292        } # while (my $line = <$fd>)
2293        print "</table>\n\n";
2294        close $fd
2295                or print "Reading blob failed.\n";
2296        print "</div>";
2297        git_footer_html();
2298}
2299
2300sub git_tags {
2301        my $head = git_get_head_hash($project);
2302        git_header_html();
2303        git_print_page_nav('','', $head,undef,$head);
2304        git_print_header_div('summary', $project);
2305
2306        my $taglist = git_get_refs_list("refs/tags");
2307        if (defined @$taglist) {
2308                git_tags_body($taglist);
2309        }
2310        git_footer_html();
2311}
2312
2313sub git_heads {
2314        my $head = git_get_head_hash($project);
2315        git_header_html();
2316        git_print_page_nav('','', $head,undef,$head);
2317        git_print_header_div('summary', $project);
2318
2319        my $taglist = git_get_refs_list("refs/heads");
2320        if (defined @$taglist) {
2321                git_heads_body($taglist, $head);
2322        }
2323        git_footer_html();
2324}
2325
2326sub git_blob_plain {
2327        # blobs defined by non-textual hash id's can be cached
2328        my $expires;
2329        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2330                $expires = "+1d";
2331        }
2332
2333        if (!defined $hash) {
2334                if (defined $file_name) {
2335                        my $base = $hash_base || git_get_head_hash($project);
2336                        $hash = git_get_hash_by_path($base, $file_name, "blob")
2337                                or die_error(undef, "Error lookup file");
2338                } else {
2339                        die_error(undef, "No file name defined");
2340                }
2341        }
2342        my $type = shift;
2343        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2344                or die_error(undef, "Couldn't cat $file_name, $hash");
2345
2346        $type ||= blob_mimetype($fd, $file_name);
2347
2348        # save as filename, even when no $file_name is given
2349        my $save_as = "$hash";
2350        if (defined $file_name) {
2351                $save_as = $file_name;
2352        } elsif ($type =~ m/^text\//) {
2353                $save_as .= '.txt';
2354        }
2355
2356        print $cgi->header(
2357                -type => "$type",
2358                -expires=>$expires,
2359                -content_disposition => "inline; filename=\"$save_as\"");
2360        undef $/;
2361        binmode STDOUT, ':raw';
2362        print <$fd>;
2363        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2364        $/ = "\n";
2365        close $fd;
2366}
2367
2368sub git_blob {
2369        # blobs defined by non-textual hash id's can be cached
2370        my $expires;
2371        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2372                $expires = "+1d";
2373        }
2374
2375        if (!defined $hash) {
2376                if (defined $file_name) {
2377                        my $base = $hash_base || git_get_head_hash($project);
2378                        $hash = git_get_hash_by_path($base, $file_name, "blob")
2379                                or die_error(undef, "Error lookup file");
2380                } else {
2381                        die_error(undef, "No file name defined");
2382                }
2383        }
2384        my $have_blame = gitweb_check_feature('blame');
2385        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2386                or die_error(undef, "Couldn't cat $file_name, $hash");
2387        my $mimetype = blob_mimetype($fd, $file_name);
2388        if ($mimetype !~ m/^text\//) {
2389                close $fd;
2390                return git_blob_plain($mimetype);
2391        }
2392        git_header_html(undef, $expires);
2393        my $formats_nav = '';
2394        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2395                if (defined $file_name) {
2396                        if ($have_blame) {
2397                                $formats_nav .=
2398                                        $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
2399                                                               hash=>$hash, file_name=>$file_name)},
2400                                                "blame") .
2401                                        " | ";
2402                        }
2403                        $formats_nav .=
2404                                $cgi->a({-href => href(action=>"blob_plain",
2405                                                       hash=>$hash, file_name=>$file_name)},
2406                                        "plain") .
2407                                " | " .
2408                                $cgi->a({-href => href(action=>"blob",
2409                                                       hash_base=>"HEAD", file_name=>$file_name)},
2410                                        "head");
2411                } else {
2412                        $formats_nav .=
2413                                $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "plain");
2414                }
2415                git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2416                git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2417        } else {
2418                print "<div class=\"page_nav\">\n" .
2419                      "<br/><br/></div>\n" .
2420                      "<div class=\"title\">$hash</div>\n";
2421        }
2422        git_print_page_path($file_name, "blob", $hash_base);
2423        print "<div class=\"page_body\">\n";
2424        my $nr;
2425        while (my $line = <$fd>) {
2426                chomp $line;
2427                $nr++;
2428                $line = untabify($line);
2429                printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
2430                       $nr, $nr, $nr, esc_html($line);
2431        }
2432        close $fd
2433                or print "Reading blob failed.\n";
2434        print "</div>";
2435        git_footer_html();
2436}
2437
2438sub git_tree {
2439        if (!defined $hash) {
2440                $hash = git_get_head_hash($project);
2441                if (defined $file_name) {
2442                        my $base = $hash_base || $hash;
2443                        $hash = git_get_hash_by_path($base, $file_name, "tree");
2444                }
2445                if (!defined $hash_base) {
2446                        $hash_base = $hash;
2447                }
2448        }
2449        $/ = "\0";
2450        open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
2451                or die_error(undef, "Open git-ls-tree failed");
2452        my @entries = map { chomp; $_ } <$fd>;
2453        close $fd or die_error(undef, "Reading tree failed");
2454        $/ = "\n";
2455
2456        my $refs = git_get_references();
2457        my $ref = format_ref_marker($refs, $hash_base);
2458        git_header_html();
2459        my %base_key = ();
2460        my $base = "";
2461        my $have_blame = gitweb_check_feature('blame');
2462        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2463                $base_key{hash_base} = $hash_base;
2464                git_print_page_nav('tree','', $hash_base);
2465                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
2466        } else {
2467                print "<div class=\"page_nav\">\n";
2468                print "<br/><br/></div>\n";
2469                print "<div class=\"title\">$hash</div>\n";
2470        }
2471        if (defined $file_name) {
2472                $base = esc_html("$file_name/");
2473        }
2474        git_print_page_path($file_name, 'tree', $hash_base);
2475        print "<div class=\"page_body\">\n";
2476        print "<table cellspacing=\"0\">\n";
2477        my $alternate = 0;
2478        foreach my $line (@entries) {
2479                #'100644        blob    0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa        panic.c'
2480                $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
2481                my $t_mode = $1;
2482                my $t_type = $2;
2483                my $t_hash = $3;
2484                my $t_name = validate_input($4);
2485                if ($alternate) {
2486                        print "<tr class=\"dark\">\n";
2487                } else {
2488                        print "<tr class=\"light\">\n";
2489                }
2490                $alternate ^= 1;
2491                print "<td class=\"mode\">" . mode_str($t_mode) . "</td>\n";
2492                if ($t_type eq "blob") {
2493                        print "<td class=\"list\">" .
2494                              $cgi->a({-href => href(action=>"blob", hash=>$t_hash, file_name=>"$base$t_name", %base_key),
2495                                      -class => "list"}, esc_html($t_name)) .
2496                              "</td>\n" .
2497                              "<td class=\"link\">" .
2498                              $cgi->a({-href => href(action=>"blob", hash=>$t_hash, file_name=>"$base$t_name", %base_key)},
2499                                      "blob");
2500                        if ($have_blame) {
2501                                print " | " .
2502                                        $cgi->a({-href => href(action=>"blame", hash=>$t_hash, file_name=>"$base$t_name", %base_key)},
2503                                                "blame");
2504                        }
2505                        print " | " .
2506                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2507                                                     hash=>$t_hash, file_name=>"$base$t_name")},
2508                                      "history") .
2509                              " | " .
2510                              $cgi->a({-href => href(action=>"blob_plain",
2511                                                     hash=>$t_hash, file_name=>"$base$t_name")},
2512                                      "raw") .
2513                              "</td>\n";
2514                } elsif ($t_type eq "tree") {
2515                        print "<td class=\"list\">" .
2516                              $cgi->a({-href => href(action=>"tree", hash=>$t_hash, file_name=>"$base$t_name", %base_key)},
2517                                      esc_html($t_name)) .
2518                              "</td>\n" .
2519                              "<td class=\"link\">" .
2520                              $cgi->a({-href => href(action=>"tree", hash=>$t_hash, file_name=>"$base$t_name", %base_key)},
2521                                      "tree") .
2522                              " | " .
2523                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base, file_name=>"$base$t_name")},
2524                                      "history") .
2525                              "</td>\n";
2526                }
2527                print "</tr>\n";
2528        }
2529        print "</table>\n" .
2530              "</div>";
2531        git_footer_html();
2532}
2533
2534sub git_snapshot {
2535
2536        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2537        my $have_snapshot = (defined $ctype && defined $suffix);
2538        if (!$have_snapshot) {
2539                die_error('403 Permission denied', "Permission denied");
2540        }
2541
2542        if (!defined $hash) {
2543                $hash = git_get_head_hash($project);
2544        }
2545
2546        my $filename = basename($project) . "-$hash.tar.$suffix";
2547
2548        print $cgi->header(-type => 'application/x-tar',
2549                           -content_encoding => $ctype,
2550                           -content_disposition => "inline; filename=\"$filename\"",
2551                           -status => '200 OK');
2552
2553        my $git_command = git_cmd_str();
2554        open my $fd, "-|", "$git_command tar-tree $hash \'$project\' | $command" or
2555                die_error(undef, "Execute git-tar-tree failed.");
2556        binmode STDOUT, ':raw';
2557        print <$fd>;
2558        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2559        close $fd;
2560
2561}
2562
2563sub git_log {
2564        my $head = git_get_head_hash($project);
2565        if (!defined $hash) {
2566                $hash = $head;
2567        }
2568        if (!defined $page) {
2569                $page = 0;
2570        }
2571        my $refs = git_get_references();
2572
2573        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2574        open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
2575                or die_error(undef, "Open git-rev-list failed");
2576        my @revlist = map { chomp; $_ } <$fd>;
2577        close $fd;
2578
2579        my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
2580
2581        git_header_html();
2582        git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
2583
2584        if (!@revlist) {
2585                my %co = parse_commit($hash);
2586
2587                git_print_header_div('summary', $project);
2588                print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
2589        }
2590        for (my $i = ($page * 100); $i <= $#revlist; $i++) {
2591                my $commit = $revlist[$i];
2592                my $ref = format_ref_marker($refs, $commit);
2593                my %co = parse_commit($commit);
2594                next if !%co;
2595                my %ad = parse_date($co{'author_epoch'});
2596                git_print_header_div('commit',
2597                               "<span class=\"age\">$co{'age_string'}</span>" .
2598                               esc_html($co{'title'}) . $ref,
2599                               $commit);
2600                print "<div class=\"title_text\">\n" .
2601                      "<div class=\"log_link\">\n" .
2602                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
2603                      " | " .
2604                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
2605                      "<br/>\n" .
2606                      "</div>\n" .
2607                      "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
2608                      "</div>\n";
2609
2610                print "<div class=\"log_body\">\n";
2611                git_print_simplified_log($co{'comment'});
2612                print "</div>\n";
2613        }
2614        git_footer_html();
2615}
2616
2617sub git_commit {
2618        my %co = parse_commit($hash);
2619        if (!%co) {
2620                die_error(undef, "Unknown commit object");
2621        }
2622        my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2623        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2624
2625        my $parent = $co{'parent'};
2626        if (!defined $parent) {
2627                $parent = "--root";
2628        }
2629        open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $parent, $hash
2630                or die_error(undef, "Open git-diff-tree failed");
2631        my @difftree = map { chomp; $_ } <$fd>;
2632        close $fd or die_error(undef, "Reading git-diff-tree failed");
2633
2634        # non-textual hash id's can be cached
2635        my $expires;
2636        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2637                $expires = "+1d";
2638        }
2639        my $refs = git_get_references();
2640        my $ref = format_ref_marker($refs, $co{'id'});
2641
2642        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2643        my $have_snapshot = (defined $ctype && defined $suffix);
2644
2645        my $formats_nav = '';
2646        if (defined $file_name && defined $co{'parent'}) {
2647                my $parent = $co{'parent'};
2648                $formats_nav .=
2649                        $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)},
2650                                "blame");
2651        }
2652        git_header_html(undef, $expires);
2653        git_print_page_nav('commit', defined $co{'parent'} ? '' : 'commitdiff',
2654                           $hash, $co{'tree'}, $hash,
2655                           $formats_nav);
2656
2657        if (defined $co{'parent'}) {
2658                git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
2659        } else {
2660                git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
2661        }
2662        print "<div class=\"title_text\">\n" .
2663              "<table cellspacing=\"0\">\n";
2664        print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
2665              "<tr>" .
2666              "<td></td><td> $ad{'rfc2822'}";
2667        if ($ad{'hour_local'} < 6) {
2668                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2669                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2670        } else {
2671                printf(" (%02d:%02d %s)",
2672                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2673        }
2674        print "</td>" .
2675              "</tr>\n";
2676        print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
2677        print "<tr><td></td><td> $cd{'rfc2822'}" .
2678              sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
2679              "</td></tr>\n";
2680        print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
2681        print "<tr>" .
2682              "<td>tree</td>" .
2683              "<td class=\"sha1\">" .
2684              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
2685                       class => "list"}, $co{'tree'}) .
2686              "</td>" .
2687              "<td class=\"link\">" .
2688              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
2689                      "tree");
2690        if ($have_snapshot) {
2691                print " | " .
2692                      $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
2693        }
2694        print "</td>" .
2695              "</tr>\n";
2696        my $parents = $co{'parents'};
2697        foreach my $par (@$parents) {
2698                print "<tr>" .
2699                      "<td>parent</td>" .
2700                      "<td class=\"sha1\">" .
2701                      $cgi->a({-href => href(action=>"commit", hash=>$par),
2702                               class => "list"}, $par) .
2703                      "</td>" .
2704                      "<td class=\"link\">" .
2705                      $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
2706                      " | " .
2707                      $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "commitdiff") .
2708                      "</td>" .
2709                      "</tr>\n";
2710        }
2711        print "</table>".
2712              "</div>\n";
2713
2714        print "<div class=\"page_body\">\n";
2715        git_print_log($co{'comment'});
2716        print "</div>\n";
2717
2718        git_difftree_body(\@difftree, $hash, $parent);
2719
2720        git_footer_html();
2721}
2722
2723sub git_blobdiff {
2724        my $format = shift || 'html';
2725
2726        my $fd;
2727        my @difftree;
2728        my %diffinfo;
2729        my $expires;
2730
2731        # preparing $fd and %diffinfo for git_patchset_body
2732        # new style URI
2733        if (defined $hash_base && defined $hash_parent_base) {
2734                if (defined $file_name) {
2735                        # read raw output
2736                        open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base,
2737                                "--", $file_name
2738                                or die_error(undef, "Open git-diff-tree failed");
2739                        @difftree = map { chomp; $_ } <$fd>;
2740                        close $fd
2741                                or die_error(undef, "Reading git-diff-tree failed");
2742                        @difftree
2743                                or die_error('404 Not Found', "Blob diff not found");
2744
2745                } elsif (defined $hash) { # try to find filename from $hash
2746                        if ($hash !~ /[0-9a-fA-F]{40}/) {
2747                                $hash = git_to_hash($hash);
2748                        }
2749                } elsif (defined $hash &&
2750                         $hash =~ /[0-9a-fA-F]{40}/) {
2751                        # try to find filename from $hash
2752
2753                        # read filtered raw output
2754                        open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base
2755                                or die_error(undef, "Open git-diff-tree failed");
2756                        @difftree =
2757                                # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
2758                                # $hash == to_id
2759                                grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
2760                                map { chomp; $_ } <$fd>;
2761                        close $fd
2762                                or die_error(undef, "Reading git-diff-tree failed");
2763                        @difftree
2764                                or die_error('404 Not Found', "Blob diff not found");
2765
2766                } else {
2767                        die_error('404 Not Found', "Missing one of the blob diff parameters");
2768                }
2769
2770                if (@difftree > 1) {
2771                        die_error('404 Not Found', "Ambiguous blob diff specification");
2772                }
2773
2774                %diffinfo = parse_difftree_raw_line($difftree[0]);
2775                $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
2776                $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
2777
2778                $hash_parent ||= $diffinfo{'from_id'};
2779                $hash        ||= $diffinfo{'to_id'};
2780
2781                # non-textual hash id's can be cached
2782                if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
2783                    $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
2784                        $expires = '+1d';
2785                }
2786
2787                # open patch output
2788                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
2789                        '-p', $hash_parent_base, $hash_base,
2790                        "--", $file_name
2791                        or die_error(undef, "Open git-diff-tree failed");
2792        }
2793
2794        # old/legacy style URI
2795        if (!%diffinfo && # if new style URI failed
2796            defined $hash && defined $hash_parent) {
2797                # fake git-diff-tree raw output
2798                $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
2799                $diffinfo{'from_id'} = $hash_parent;
2800                $diffinfo{'to_id'}   = $hash;
2801                if (defined $file_name) {
2802                        if (defined $file_parent) {
2803                                $diffinfo{'status'} = '2';
2804                                $diffinfo{'from_file'} = $file_parent;
2805                                $diffinfo{'to_file'}   = $file_name;
2806                        } else { # assume not renamed
2807                                $diffinfo{'status'} = '1';
2808                                $diffinfo{'from_file'} = $file_name;
2809                                $diffinfo{'to_file'}   = $file_name;
2810                        }
2811                } else { # no filename given
2812                        $diffinfo{'status'} = '2';
2813                        $diffinfo{'from_file'} = $hash_parent;
2814                        $diffinfo{'to_file'}   = $hash;
2815                }
2816
2817                # non-textual hash id's can be cached
2818                if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
2819                    $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
2820                        $expires = '+1d';
2821                }
2822
2823                # open patch output
2824                open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts, $hash_parent, $hash
2825                        or die_error(undef, "Open git-diff failed");
2826        } else  {
2827                die_error('404 Not Found', "Missing one of the blob diff parameters")
2828                        unless %diffinfo;
2829        }
2830
2831        # header
2832        if ($format eq 'html') {
2833                my $formats_nav =
2834                        $cgi->a({-href => href(action=>"blobdiff_plain",
2835                                               hash=>$hash, hash_parent=>$hash_parent,
2836                                               hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
2837                                               file_name=>$file_name, file_parent=>$file_parent)},
2838                                "plain");
2839                git_header_html(undef, $expires);
2840                if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2841                        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2842                        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2843                } else {
2844                        print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
2845                        print "<div class=\"title\">$hash vs $hash_parent</div>\n";
2846                }
2847                if (defined $file_name) {
2848                        git_print_page_path($file_name, "blob", $hash_base);
2849                } else {
2850                        print "<div class=\"page_path\"></div>\n";
2851                }
2852
2853        } elsif ($format eq 'plain') {
2854                print $cgi->header(
2855                        -type => 'text/plain',
2856                        -charset => 'utf-8',
2857                        -expires => $expires,
2858                        -content_disposition => qq(inline; filename="${file_name}.patch"));
2859
2860                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
2861
2862        } else {
2863                die_error(undef, "Unknown blobdiff format");
2864        }
2865
2866        # patch
2867        if ($format eq 'html') {
2868                print "<div class=\"page_body\">\n";
2869
2870                git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
2871                close $fd;
2872
2873                print "</div>\n"; # class="page_body"
2874                git_footer_html();
2875
2876        } else {
2877                while (my $line = <$fd>) {
2878                        $line =~ s!a/($hash|$hash_parent)!a/$diffinfo{'from_file'}!g;
2879                        $line =~ s!b/($hash|$hash_parent)!b/$diffinfo{'to_file'}!g;
2880
2881                        print $line;
2882
2883                        last if $line =~ m!^\+\+\+!;
2884                }
2885                local $/ = undef;
2886                print <$fd>;
2887                close $fd;
2888        }
2889}
2890
2891sub git_blobdiff_plain {
2892        git_blobdiff('plain');
2893}
2894
2895sub git_commitdiff {
2896        my $format = shift || 'html';
2897        my %co = parse_commit($hash);
2898        if (!%co) {
2899                die_error(undef, "Unknown commit object");
2900        }
2901        if (!defined $hash_parent) {
2902                $hash_parent = $co{'parent'} || '--root';
2903        }
2904
2905        # read commitdiff
2906        my $fd;
2907        my @difftree;
2908        if ($format eq 'html') {
2909                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
2910                        "--patch-with-raw", "--full-index", $hash_parent, $hash
2911                        or die_error(undef, "Open git-diff-tree failed");
2912
2913                while (chomp(my $line = <$fd>)) {
2914                        # empty line ends raw part of diff-tree output
2915                        last unless $line;
2916                        push @difftree, $line;
2917                }
2918
2919        } elsif ($format eq 'plain') {
2920                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
2921                        '-p', $hash_parent, $hash
2922                        or die_error(undef, "Open git-diff-tree failed");
2923
2924        } else {
2925                die_error(undef, "Unknown commitdiff format");
2926        }
2927
2928        # non-textual hash id's can be cached
2929        my $expires;
2930        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2931                $expires = "+1d";
2932        }
2933
2934        # write commit message
2935        if ($format eq 'html') {
2936                my $refs = git_get_references();
2937                my $ref = format_ref_marker($refs, $co{'id'});
2938                my $formats_nav =
2939                        $cgi->a({-href => href(action=>"commitdiff_plain",
2940                                               hash=>$hash, hash_parent=>$hash_parent)},
2941                                "plain");
2942
2943                git_header_html(undef, $expires);
2944                git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
2945                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
2946                git_print_authorship(\%co);
2947                print "<div class=\"page_body\">\n";
2948                print "<div class=\"log\">\n";
2949                git_print_simplified_log($co{'comment'}, 1); # skip title
2950                print "</div>\n"; # class="log"
2951
2952        } elsif ($format eq 'plain') {
2953                my $refs = git_get_references("tags");
2954                my $tagname = git_get_rev_name_tags($hash);
2955                my $filename = basename($project) . "-$hash.patch";
2956
2957                print $cgi->header(
2958                        -type => 'text/plain',
2959                        -charset => 'utf-8',
2960                        -expires => $expires,
2961                        -content_disposition => qq(inline; filename="$filename"));
2962                my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2963                print <<TEXT;
2964From: $co{'author'}
2965Date: $ad{'rfc2822'} ($ad{'tz_local'})
2966Subject: $co{'title'}
2967TEXT
2968                print "X-Git-Tag: $tagname\n" if $tagname;
2969                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
2970
2971                foreach my $line (@{$co{'comment'}}) {
2972                        print "$line\n";
2973                }
2974                print "---\n\n";
2975        }
2976
2977        # write patch
2978        if ($format eq 'html') {
2979                #git_difftree_body(\@difftree, $hash, $hash_parent);
2980                #print "<br/>\n";
2981
2982                git_patchset_body($fd, \@difftree, $hash, $hash_parent);
2983                close $fd;
2984                print "</div>\n"; # class="page_body"
2985                git_footer_html();
2986
2987        } elsif ($format eq 'plain') {
2988                local $/ = undef;
2989                print <$fd>;
2990                close $fd
2991                        or print "Reading git-diff-tree failed\n";
2992        }
2993}
2994
2995sub git_commitdiff_plain {
2996        git_commitdiff('plain');
2997}
2998
2999sub git_history {
3000        if (!defined $hash_base) {
3001                $hash_base = git_get_head_hash($project);
3002        }
3003        my $ftype;
3004        my %co = parse_commit($hash_base);
3005        if (!%co) {
3006                die_error(undef, "Unknown commit object");
3007        }
3008        my $refs = git_get_references();
3009        git_header_html();
3010        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base);
3011        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3012        if (!defined $hash && defined $file_name) {
3013                $hash = git_get_hash_by_path($hash_base, $file_name);
3014        }
3015        if (defined $hash) {
3016                $ftype = git_get_type($hash);
3017        }
3018        git_print_page_path($file_name, $ftype, $hash_base);
3019
3020        open my $fd, "-|",
3021                git_cmd(), "rev-list", "--full-history", $hash_base, "--", $file_name;
3022
3023        git_history_body($fd, $refs, $hash_base, $ftype);
3024
3025        close $fd;
3026        git_footer_html();
3027}
3028
3029sub git_search {
3030        if (!defined $searchtext) {
3031                die_error(undef, "Text field empty");
3032        }
3033        if (!defined $hash) {
3034                $hash = git_get_head_hash($project);
3035        }
3036        my %co = parse_commit($hash);
3037        if (!%co) {
3038                die_error(undef, "Unknown commit object");
3039        }
3040        # pickaxe may take all resources of your box and run for several minutes
3041        # with every query - so decide by yourself how public you make this feature :)
3042        my $commit_search = 1;
3043        my $author_search = 0;
3044        my $committer_search = 0;
3045        my $pickaxe_search = 0;
3046        if ($searchtext =~ s/^author\\://i) {
3047                $author_search = 1;
3048        } elsif ($searchtext =~ s/^committer\\://i) {
3049                $committer_search = 1;
3050        } elsif ($searchtext =~ s/^pickaxe\\://i) {
3051                $commit_search = 0;
3052                $pickaxe_search = 1;
3053        }
3054        git_header_html();
3055        git_print_page_nav('','', $hash,$co{'tree'},$hash);
3056        git_print_header_div('commit', esc_html($co{'title'}), $hash);
3057
3058        print "<table cellspacing=\"0\">\n";
3059        my $alternate = 0;
3060        if ($commit_search) {
3061                $/ = "\0";
3062                open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", $hash or next;
3063                while (my $commit_text = <$fd>) {
3064                        if (!grep m/$searchtext/i, $commit_text) {
3065                                next;
3066                        }
3067                        if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
3068                                next;
3069                        }
3070                        if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
3071                                next;
3072                        }
3073                        my @commit_lines = split "\n", $commit_text;
3074                        my %co = parse_commit(undef, \@commit_lines);
3075                        if (!%co) {
3076                                next;
3077                        }
3078                        if ($alternate) {
3079                                print "<tr class=\"dark\">\n";
3080                        } else {
3081                                print "<tr class=\"light\">\n";
3082                        }
3083                        $alternate ^= 1;
3084                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3085                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3086                              "<td>" .
3087                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3088                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3089                        my $comment = $co{'comment'};
3090                        foreach my $line (@$comment) {
3091                                if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
3092                                        my $lead = esc_html($1) || "";
3093                                        $lead = chop_str($lead, 30, 10);
3094                                        my $match = esc_html($2) || "";
3095                                        my $trail = esc_html($3) || "";
3096                                        $trail = chop_str($trail, 30, 10);
3097                                        my $text = "$lead<span class=\"match\">$match</span>$trail";
3098                                        print chop_str($text, 80, 5) . "<br/>\n";
3099                                }
3100                        }
3101                        print "</td>\n" .
3102                              "<td class=\"link\">" .
3103                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3104                              " | " .
3105                              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3106                        print "</td>\n" .
3107                              "</tr>\n";
3108                }
3109                close $fd;
3110        }
3111
3112        if ($pickaxe_search) {
3113                $/ = "\n";
3114                my $git_command = git_cmd_str();
3115                open my $fd, "-|", "$git_command rev-list $hash | " .
3116                        "$git_command diff-tree -r --stdin -S\'$searchtext\'";
3117                undef %co;
3118                my @files;
3119                while (my $line = <$fd>) {
3120                        if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
3121                                my %set;
3122                                $set{'file'} = $6;
3123                                $set{'from_id'} = $3;
3124                                $set{'to_id'} = $4;
3125                                $set{'id'} = $set{'to_id'};
3126                                if ($set{'id'} =~ m/0{40}/) {
3127                                        $set{'id'} = $set{'from_id'};
3128                                }
3129                                if ($set{'id'} =~ m/0{40}/) {
3130                                        next;
3131                                }
3132                                push @files, \%set;
3133                        } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
3134                                if (%co) {
3135                                        if ($alternate) {
3136                                                print "<tr class=\"dark\">\n";
3137                                        } else {
3138                                                print "<tr class=\"light\">\n";
3139                                        }
3140                                        $alternate ^= 1;
3141                                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3142                                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3143                                              "<td>" .
3144                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
3145                                                      -class => "list subject"},
3146                                                      esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3147                                        while (my $setref = shift @files) {
3148                                                my %set = %$setref;
3149                                                print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
3150                                                                             hash=>$set{'id'}, file_name=>$set{'file'}),
3151                                                              -class => "list"},
3152                                                              "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
3153                                                      "<br/>\n";
3154                                        }
3155                                        print "</td>\n" .
3156                                              "<td class=\"link\">" .
3157                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3158                                              " | " .
3159                                              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3160                                        print "</td>\n" .
3161                                              "</tr>\n";
3162                                }
3163                                %co = parse_commit($1);
3164                        }
3165                }
3166                close $fd;
3167        }
3168        print "</table>\n";
3169        git_footer_html();
3170}
3171
3172sub git_shortlog {
3173        my $head = git_get_head_hash($project);
3174        if (!defined $hash) {
3175                $hash = $head;
3176        }
3177        if (!defined $page) {
3178                $page = 0;
3179        }
3180        my $refs = git_get_references();
3181
3182        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3183        open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
3184                or die_error(undef, "Open git-rev-list failed");
3185        my @revlist = map { chomp; $_ } <$fd>;
3186        close $fd;
3187
3188        my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
3189        my $next_link = '';
3190        if ($#revlist >= (100 * ($page+1)-1)) {
3191                $next_link =
3192                        $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
3193                                 -title => "Alt-n"}, "next");
3194        }
3195
3196
3197        git_header_html();
3198        git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
3199        git_print_header_div('summary', $project);
3200
3201        git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
3202
3203        git_footer_html();
3204}
3205
3206## ......................................................................
3207## feeds (RSS, OPML)
3208
3209sub git_rss {
3210        # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
3211        open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150", git_get_head_hash($project)
3212                or die_error(undef, "Open git-rev-list failed");
3213        my @revlist = map { chomp; $_ } <$fd>;
3214        close $fd or die_error(undef, "Reading git-rev-list failed");
3215        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3216        print <<XML;
3217<?xml version="1.0" encoding="utf-8"?>
3218<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
3219<channel>
3220<title>$project $my_uri $my_url</title>
3221<link>${\esc_html("$my_url?p=$project;a=summary")}</link>
3222<description>$project log</description>
3223<language>en</language>
3224XML
3225
3226        for (my $i = 0; $i <= $#revlist; $i++) {
3227                my $commit = $revlist[$i];
3228                my %co = parse_commit($commit);
3229                # we read 150, we always show 30 and the ones more recent than 48 hours
3230                if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
3231                        last;
3232                }
3233                my %cd = parse_date($co{'committer_epoch'});
3234                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3235                        $co{'parent'}, $co{'id'}
3236                        or next;
3237                my @difftree = map { chomp; $_ } <$fd>;
3238                close $fd
3239                        or next;
3240                print "<item>\n" .
3241                      "<title>" .
3242                      sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
3243                      "</title>\n" .
3244                      "<author>" . esc_html($co{'author'}) . "</author>\n" .
3245                      "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
3246                      "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
3247                      "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
3248                      "<description>" . esc_html($co{'title'}) . "</description>\n" .
3249                      "<content:encoded>" .
3250                      "<![CDATA[\n";
3251                my $comment = $co{'comment'};
3252                foreach my $line (@$comment) {
3253                        $line = decode("utf8", $line, Encode::FB_DEFAULT);
3254                        print "$line<br/>\n";
3255                }
3256                print "<br/>\n";
3257                foreach my $line (@difftree) {
3258                        if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
3259                                next;
3260                        }
3261                        my $file = validate_input(unquote($7));
3262                        $file = decode("utf8", $file, Encode::FB_DEFAULT);
3263                        print "$file<br/>\n";
3264                }
3265                print "]]>\n" .
3266                      "</content:encoded>\n" .
3267                      "</item>\n";
3268        }
3269        print "</channel></rss>";
3270}
3271
3272sub git_opml {
3273        my @list = git_get_projects_list();
3274
3275        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3276        print <<XML;
3277<?xml version="1.0" encoding="utf-8"?>
3278<opml version="1.0">
3279<head>
3280  <title>$site_name Git OPML Export</title>
3281</head>
3282<body>
3283<outline text="git RSS feeds">
3284XML
3285
3286        foreach my $pr (@list) {
3287                my %proj = %$pr;
3288                my $head = git_get_head_hash($proj{'path'});
3289                if (!defined $head) {
3290                        next;
3291                }
3292                $git_dir = "$projectroot/$proj{'path'}";
3293                my %co = parse_commit($head);
3294                if (!%co) {
3295                        next;
3296                }
3297
3298                my $path = esc_html(chop_str($proj{'path'}, 25, 5));
3299                my $rss  = "$my_url?p=$proj{'path'};a=rss";
3300                my $html = "$my_url?p=$proj{'path'};a=summary";
3301                print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
3302        }
3303        print <<XML;
3304</outline>
3305</body>
3306</opml>
3307XML
3308}