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