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