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