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