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