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