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