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