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