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