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