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