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