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