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