gitweb / gitweb.perlon commit gitweb: make search form generate pathinfo-style URLs (40375a8)
   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
  21BEGIN {
  22        CGI->compile() if $ENV{'MOD_PERL'};
  23}
  24
  25our $cgi = new CGI;
  26our $version = "++GIT_VERSION++";
  27our $my_url = $cgi->url();
  28our $my_uri = $cgi->url(-absolute => 1);
  29
  30# core git executable to use
  31# this can just be "git" if your webserver has a sensible PATH
  32our $GIT = "++GIT_BINDIR++/git";
  33
  34# absolute fs-path which will be prepended to the project path
  35#our $projectroot = "/pub/scm";
  36our $projectroot = "++GITWEB_PROJECTROOT++";
  37
  38# target of the home link on top of all pages
  39our $home_link = $my_uri || "/";
  40
  41# string of the home link on top of all pages
  42our $home_link_str = "++GITWEB_HOME_LINK_STR++";
  43
  44# name of your site or organization to appear in page titles
  45# replace this with something more descriptive for clearer bookmarks
  46our $site_name = "++GITWEB_SITENAME++"
  47                 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
  48
  49# filename of html text to include at top of each page
  50our $site_header = "++GITWEB_SITE_HEADER++";
  51# html text to include at home page
  52our $home_text = "++GITWEB_HOMETEXT++";
  53# filename of html text to include at bottom of each page
  54our $site_footer = "++GITWEB_SITE_FOOTER++";
  55
  56# URI of stylesheets
  57our @stylesheets = ("++GITWEB_CSS++");
  58# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
  59our $stylesheet = undef;
  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# default order of projects list
  75# valid values are none, project, descr, owner, and age
  76our $default_projects_order = "project";
  77
  78# show repository only if this file exists
  79# (only effective if this variable evaluates to true)
  80our $export_ok = "++GITWEB_EXPORT_OK++";
  81
  82# only allow viewing of repositories also shown on the overview page
  83our $strict_export = "++GITWEB_STRICT_EXPORT++";
  84
  85# list of git base URLs used for URL to where fetch project from,
  86# i.e. full URL is "$git_base_url/$project"
  87our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
  88
  89# default blob_plain mimetype and default charset for text/plain blob
  90our $default_blob_plain_mimetype = 'text/plain';
  91our $default_text_plain_charset  = undef;
  92
  93# file to use for guessing MIME types before trying /etc/mime.types
  94# (relative to the current git repository)
  95our $mimetypes_file = undef;
  96
  97# assume this charset if line contains non-UTF-8 characters;
  98# it should be valid encoding (see Encoding::Supported(3pm) for list),
  99# for which encoding all byte sequences are valid, for example
 100# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
 101# could be even 'utf-8' for the old behavior)
 102our $fallback_encoding = 'latin1';
 103
 104# You define site-wide feature defaults here; override them with
 105# $GITWEB_CONFIG as necessary.
 106our %feature = (
 107        # feature => {
 108        #       'sub' => feature-sub (subroutine),
 109        #       'override' => allow-override (boolean),
 110        #       'default' => [ default options...] (array reference)}
 111        #
 112        # if feature is overridable (it means that allow-override has true value),
 113        # then feature-sub will be called with default options as parameters;
 114        # return value of feature-sub indicates if to enable specified feature
 115        #
 116        # if there is no 'sub' key (no feature-sub), then feature cannot be
 117        # overriden
 118        #
 119        # use gitweb_check_feature(<feature>) to check if <feature> is enabled
 120
 121        # Enable the 'blame' blob view, showing the last commit that modified
 122        # each line in the file. This can be very CPU-intensive.
 123
 124        # To enable system wide have in $GITWEB_CONFIG
 125        # $feature{'blame'}{'default'} = [1];
 126        # To have project specific config enable override in $GITWEB_CONFIG
 127        # $feature{'blame'}{'override'} = 1;
 128        # and in project config gitweb.blame = 0|1;
 129        'blame' => {
 130                'sub' => \&feature_blame,
 131                'override' => 0,
 132                'default' => [0]},
 133
 134        # Enable the 'snapshot' link, providing a compressed tarball of any
 135        # tree. This can potentially generate high traffic if you have large
 136        # project.
 137
 138        # To disable system wide have in $GITWEB_CONFIG
 139        # $feature{'snapshot'}{'default'} = [undef];
 140        # To have project specific config enable override in $GITWEB_CONFIG
 141        # $feature{'snapshot'}{'override'} = 1;
 142        # and in project config gitweb.snapshot = none|gzip|bzip2|zip;
 143        'snapshot' => {
 144                'sub' => \&feature_snapshot,
 145                'override' => 0,
 146                #         => [content-encoding, suffix, program]
 147                'default' => ['x-gzip', 'gz', 'gzip']},
 148
 149        # Enable text search, which will list the commits which match author,
 150        # committer or commit text to a given string.  Enabled by default.
 151        # Project specific override is not supported.
 152        'search' => {
 153                'override' => 0,
 154                'default' => [1]},
 155
 156        # Enable grep search, which will list the files in currently selected
 157        # tree containing the given string. Enabled by default. This can be
 158        # potentially CPU-intensive, of course.
 159
 160        # To enable system wide have in $GITWEB_CONFIG
 161        # $feature{'grep'}{'default'} = [1];
 162        # To have project specific config enable override in $GITWEB_CONFIG
 163        # $feature{'grep'}{'override'} = 1;
 164        # and in project config gitweb.grep = 0|1;
 165        'grep' => {
 166                'override' => 0,
 167                'default' => [1]},
 168
 169        # Enable the pickaxe search, which will list the commits that modified
 170        # a given string in a file. This can be practical and quite faster
 171        # alternative to 'blame', but still potentially CPU-intensive.
 172
 173        # To enable system wide have in $GITWEB_CONFIG
 174        # $feature{'pickaxe'}{'default'} = [1];
 175        # To have project specific config enable override in $GITWEB_CONFIG
 176        # $feature{'pickaxe'}{'override'} = 1;
 177        # and in project config gitweb.pickaxe = 0|1;
 178        'pickaxe' => {
 179                'sub' => \&feature_pickaxe,
 180                'override' => 0,
 181                'default' => [1]},
 182
 183        # Make gitweb use an alternative format of the URLs which can be
 184        # more readable and natural-looking: project name is embedded
 185        # directly in the path and the query string contains other
 186        # auxiliary information. All gitweb installations recognize
 187        # URL in either format; this configures in which formats gitweb
 188        # generates links.
 189
 190        # To enable system wide have in $GITWEB_CONFIG
 191        # $feature{'pathinfo'}{'default'} = [1];
 192        # Project specific override is not supported.
 193
 194        # Note that you will need to change the default location of CSS,
 195        # favicon, logo and possibly other files to an absolute URL. Also,
 196        # if gitweb.cgi serves as your indexfile, you will need to force
 197        # $my_uri to contain the script name in your $GITWEB_CONFIG.
 198        'pathinfo' => {
 199                'override' => 0,
 200                'default' => [0]},
 201
 202        # Make gitweb consider projects in project root subdirectories
 203        # to be forks of existing projects. Given project $projname.git,
 204        # projects matching $projname/*.git will not be shown in the main
 205        # projects list, instead a '+' mark will be added to $projname
 206        # there and a 'forks' view will be enabled for the project, listing
 207        # all the forks. If project list is taken from a file, forks have
 208        # to be listed after the main project.
 209
 210        # To enable system wide have in $GITWEB_CONFIG
 211        # $feature{'forks'}{'default'} = [1];
 212        # Project specific override is not supported.
 213        'forks' => {
 214                'override' => 0,
 215                'default' => [0]},
 216);
 217
 218sub gitweb_check_feature {
 219        my ($name) = @_;
 220        return unless exists $feature{$name};
 221        my ($sub, $override, @defaults) = (
 222                $feature{$name}{'sub'},
 223                $feature{$name}{'override'},
 224                @{$feature{$name}{'default'}});
 225        if (!$override) { return @defaults; }
 226        if (!defined $sub) {
 227                warn "feature $name is not overrideable";
 228                return @defaults;
 229        }
 230        return $sub->(@defaults);
 231}
 232
 233sub feature_blame {
 234        my ($val) = git_get_project_config('blame', '--bool');
 235
 236        if ($val eq 'true') {
 237                return 1;
 238        } elsif ($val eq 'false') {
 239                return 0;
 240        }
 241
 242        return $_[0];
 243}
 244
 245sub feature_snapshot {
 246        my ($ctype, $suffix, $command) = @_;
 247
 248        my ($val) = git_get_project_config('snapshot');
 249
 250        if ($val eq 'gzip') {
 251                return ('x-gzip', 'gz', 'gzip');
 252        } elsif ($val eq 'bzip2') {
 253                return ('x-bzip2', 'bz2', 'bzip2');
 254        } elsif ($val eq 'zip') {
 255                return ('x-zip', 'zip', '');
 256        } elsif ($val eq 'none') {
 257                return ();
 258        }
 259
 260        return ($ctype, $suffix, $command);
 261}
 262
 263sub gitweb_have_snapshot {
 264        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
 265        my $have_snapshot = (defined $ctype && defined $suffix);
 266
 267        return $have_snapshot;
 268}
 269
 270sub feature_grep {
 271        my ($val) = git_get_project_config('grep', '--bool');
 272
 273        if ($val eq 'true') {
 274                return (1);
 275        } elsif ($val eq 'false') {
 276                return (0);
 277        }
 278
 279        return ($_[0]);
 280}
 281
 282sub feature_pickaxe {
 283        my ($val) = git_get_project_config('pickaxe', '--bool');
 284
 285        if ($val eq 'true') {
 286                return (1);
 287        } elsif ($val eq 'false') {
 288                return (0);
 289        }
 290
 291        return ($_[0]);
 292}
 293
 294# checking HEAD file with -e is fragile if the repository was
 295# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
 296# and then pruned.
 297sub check_head_link {
 298        my ($dir) = @_;
 299        my $headfile = "$dir/HEAD";
 300        return ((-e $headfile) ||
 301                (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
 302}
 303
 304sub check_export_ok {
 305        my ($dir) = @_;
 306        return (check_head_link($dir) &&
 307                (!$export_ok || -e "$dir/$export_ok"));
 308}
 309
 310# rename detection options for git-diff and git-diff-tree
 311# - default is '-M', with the cost proportional to
 312#   (number of removed files) * (number of new files).
 313# - more costly is '-C' (or '-C', '-M'), with the cost proportional to
 314#   (number of changed files + number of removed files) * (number of new files)
 315# - even more costly is '-C', '--find-copies-harder' with cost
 316#   (number of files in the original tree) * (number of new files)
 317# - one might want to include '-B' option, e.g. '-B', '-M'
 318our @diff_opts = ('-M'); # taken from git_commit
 319
 320our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
 321do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
 322
 323# version of the core git binary
 324our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
 325
 326$projects_list ||= $projectroot;
 327
 328# ======================================================================
 329# input validation and dispatch
 330our $action = $cgi->param('a');
 331if (defined $action) {
 332        if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
 333                die_error(undef, "Invalid action parameter");
 334        }
 335}
 336
 337# parameters which are pathnames
 338our $project = $cgi->param('p');
 339if (defined $project) {
 340        if (!validate_pathname($project) ||
 341            !(-d "$projectroot/$project") ||
 342            !check_head_link("$projectroot/$project") ||
 343            ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
 344            ($strict_export && !project_in_list($project))) {
 345                undef $project;
 346                die_error(undef, "No such project");
 347        }
 348}
 349
 350our $file_name = $cgi->param('f');
 351if (defined $file_name) {
 352        if (!validate_pathname($file_name)) {
 353                die_error(undef, "Invalid file parameter");
 354        }
 355}
 356
 357our $file_parent = $cgi->param('fp');
 358if (defined $file_parent) {
 359        if (!validate_pathname($file_parent)) {
 360                die_error(undef, "Invalid file parent parameter");
 361        }
 362}
 363
 364# parameters which are refnames
 365our $hash = $cgi->param('h');
 366if (defined $hash) {
 367        if (!validate_refname($hash)) {
 368                die_error(undef, "Invalid hash parameter");
 369        }
 370}
 371
 372our $hash_parent = $cgi->param('hp');
 373if (defined $hash_parent) {
 374        if (!validate_refname($hash_parent)) {
 375                die_error(undef, "Invalid hash parent parameter");
 376        }
 377}
 378
 379our $hash_base = $cgi->param('hb');
 380if (defined $hash_base) {
 381        if (!validate_refname($hash_base)) {
 382                die_error(undef, "Invalid hash base parameter");
 383        }
 384}
 385
 386our $hash_parent_base = $cgi->param('hpb');
 387if (defined $hash_parent_base) {
 388        if (!validate_refname($hash_parent_base)) {
 389                die_error(undef, "Invalid hash parent base parameter");
 390        }
 391}
 392
 393# other parameters
 394our $page = $cgi->param('pg');
 395if (defined $page) {
 396        if ($page =~ m/[^0-9]/) {
 397                die_error(undef, "Invalid page parameter");
 398        }
 399}
 400
 401our $searchtype = $cgi->param('st');
 402if (defined $searchtype) {
 403        if ($searchtype =~ m/[^a-z]/) {
 404                die_error(undef, "Invalid searchtype parameter");
 405        }
 406}
 407
 408our $searchtext = $cgi->param('s');
 409our $search_regexp;
 410if (defined $searchtext) {
 411        if ($searchtype ne 'grep' and $searchtype ne 'pickaxe' and $searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
 412                die_error(undef, "Invalid search parameter");
 413        }
 414        if (length($searchtext) < 2) {
 415                die_error(undef, "At least two characters are required for search parameter");
 416        }
 417        $search_regexp = quotemeta $searchtext;
 418}
 419
 420# now read PATH_INFO and use it as alternative to parameters
 421sub evaluate_path_info {
 422        return if defined $project;
 423        my $path_info = $ENV{"PATH_INFO"};
 424        return if !$path_info;
 425        $path_info =~ s,^/+,,;
 426        return if !$path_info;
 427        # find which part of PATH_INFO is project
 428        $project = $path_info;
 429        $project =~ s,/+$,,;
 430        while ($project && !check_head_link("$projectroot/$project")) {
 431                $project =~ s,/*[^/]*$,,;
 432        }
 433        # validate project
 434        $project = validate_pathname($project);
 435        if (!$project ||
 436            ($export_ok && !-e "$projectroot/$project/$export_ok") ||
 437            ($strict_export && !project_in_list($project))) {
 438                undef $project;
 439                return;
 440        }
 441        # do not change any parameters if an action is given using the query string
 442        return if $action;
 443        $path_info =~ s,^$project/*,,;
 444        my ($refname, $pathname) = split(/:/, $path_info, 2);
 445        if (defined $pathname) {
 446                # we got "project.git/branch:filename" or "project.git/branch:dir/"
 447                # we could use git_get_type(branch:pathname), but it needs $git_dir
 448                $pathname =~ s,^/+,,;
 449                if (!$pathname || substr($pathname, -1) eq "/") {
 450                        $action  ||= "tree";
 451                        $pathname =~ s,/$,,;
 452                } else {
 453                        $action  ||= "blob_plain";
 454                }
 455                $hash_base ||= validate_refname($refname);
 456                $file_name ||= validate_pathname($pathname);
 457        } elsif (defined $refname) {
 458                # we got "project.git/branch"
 459                $action ||= "shortlog";
 460                $hash   ||= validate_refname($refname);
 461        }
 462}
 463evaluate_path_info();
 464
 465# path to the current git repository
 466our $git_dir;
 467$git_dir = "$projectroot/$project" if $project;
 468
 469# dispatch
 470my %actions = (
 471        "blame" => \&git_blame2,
 472        "blobdiff" => \&git_blobdiff,
 473        "blobdiff_plain" => \&git_blobdiff_plain,
 474        "blob" => \&git_blob,
 475        "blob_plain" => \&git_blob_plain,
 476        "commitdiff" => \&git_commitdiff,
 477        "commitdiff_plain" => \&git_commitdiff_plain,
 478        "commit" => \&git_commit,
 479        "forks" => \&git_forks,
 480        "heads" => \&git_heads,
 481        "history" => \&git_history,
 482        "log" => \&git_log,
 483        "rss" => \&git_rss,
 484        "atom" => \&git_atom,
 485        "search" => \&git_search,
 486        "search_help" => \&git_search_help,
 487        "shortlog" => \&git_shortlog,
 488        "summary" => \&git_summary,
 489        "tag" => \&git_tag,
 490        "tags" => \&git_tags,
 491        "tree" => \&git_tree,
 492        "snapshot" => \&git_snapshot,
 493        "object" => \&git_object,
 494        # those below don't need $project
 495        "opml" => \&git_opml,
 496        "project_list" => \&git_project_list,
 497        "project_index" => \&git_project_index,
 498);
 499
 500if (!defined $action) {
 501        if (defined $hash) {
 502                $action = git_get_type($hash);
 503        } elsif (defined $hash_base && defined $file_name) {
 504                $action = git_get_type("$hash_base:$file_name");
 505        } elsif (defined $project) {
 506                $action = 'summary';
 507        } else {
 508                $action = 'project_list';
 509        }
 510}
 511if (!defined($actions{$action})) {
 512        die_error(undef, "Unknown action");
 513}
 514if ($action !~ m/^(opml|project_list|project_index)$/ &&
 515    !$project) {
 516        die_error(undef, "Project needed");
 517}
 518$actions{$action}->();
 519exit;
 520
 521## ======================================================================
 522## action links
 523
 524sub href(%) {
 525        my %params = @_;
 526        # default is to use -absolute url() i.e. $my_uri
 527        my $href = $params{-full} ? $my_url : $my_uri;
 528
 529        # XXX: Warning: If you touch this, check the search form for updating,
 530        # too.
 531
 532        my @mapping = (
 533                project => "p",
 534                action => "a",
 535                file_name => "f",
 536                file_parent => "fp",
 537                hash => "h",
 538                hash_parent => "hp",
 539                hash_base => "hb",
 540                hash_parent_base => "hpb",
 541                page => "pg",
 542                order => "o",
 543                searchtext => "s",
 544                searchtype => "st",
 545        );
 546        my %mapping = @mapping;
 547
 548        $params{'project'} = $project unless exists $params{'project'};
 549
 550        my ($use_pathinfo) = gitweb_check_feature('pathinfo');
 551        if ($use_pathinfo) {
 552                # use PATH_INFO for project name
 553                $href .= "/$params{'project'}" if defined $params{'project'};
 554                delete $params{'project'};
 555
 556                # Summary just uses the project path URL
 557                if (defined $params{'action'} && $params{'action'} eq 'summary') {
 558                        delete $params{'action'};
 559                }
 560        }
 561
 562        # now encode the parameters explicitly
 563        my @result = ();
 564        for (my $i = 0; $i < @mapping; $i += 2) {
 565                my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
 566                if (defined $params{$name}) {
 567                        push @result, $symbol . "=" . esc_param($params{$name});
 568                }
 569        }
 570        $href .= "?" . join(';', @result) if scalar @result;
 571
 572        return $href;
 573}
 574
 575
 576## ======================================================================
 577## validation, quoting/unquoting and escaping
 578
 579sub validate_pathname {
 580        my $input = shift || return undef;
 581
 582        # no '.' or '..' as elements of path, i.e. no '.' nor '..'
 583        # at the beginning, at the end, and between slashes.
 584        # also this catches doubled slashes
 585        if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
 586                return undef;
 587        }
 588        # no null characters
 589        if ($input =~ m!\0!) {
 590                return undef;
 591        }
 592        return $input;
 593}
 594
 595sub validate_refname {
 596        my $input = shift || return undef;
 597
 598        # textual hashes are O.K.
 599        if ($input =~ m/^[0-9a-fA-F]{40}$/) {
 600                return $input;
 601        }
 602        # it must be correct pathname
 603        $input = validate_pathname($input)
 604                or return undef;
 605        # restrictions on ref name according to git-check-ref-format
 606        if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
 607                return undef;
 608        }
 609        return $input;
 610}
 611
 612# decode sequences of octets in utf8 into Perl's internal form,
 613# which is utf-8 with utf8 flag set if needed.  gitweb writes out
 614# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
 615sub to_utf8 {
 616        my $str = shift;
 617        my $res;
 618        eval { $res = decode_utf8($str, Encode::FB_CROAK); };
 619        if (defined $res) {
 620                return $res;
 621        } else {
 622                return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
 623        }
 624}
 625
 626# quote unsafe chars, but keep the slash, even when it's not
 627# correct, but quoted slashes look too horrible in bookmarks
 628sub esc_param {
 629        my $str = shift;
 630        $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
 631        $str =~ s/\+/%2B/g;
 632        $str =~ s/ /\+/g;
 633        return $str;
 634}
 635
 636# quote unsafe chars in whole URL, so some charactrs cannot be quoted
 637sub esc_url {
 638        my $str = shift;
 639        $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
 640        $str =~ s/\+/%2B/g;
 641        $str =~ s/ /\+/g;
 642        return $str;
 643}
 644
 645# replace invalid utf8 character with SUBSTITUTION sequence
 646sub esc_html ($;%) {
 647        my $str = shift;
 648        my %opts = @_;
 649
 650        $str = to_utf8($str);
 651        $str = $cgi->escapeHTML($str);
 652        if ($opts{'-nbsp'}) {
 653                $str =~ s/ /&nbsp;/g;
 654        }
 655        $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
 656        return $str;
 657}
 658
 659# quote control characters and escape filename to HTML
 660sub esc_path {
 661        my $str = shift;
 662        my %opts = @_;
 663
 664        $str = to_utf8($str);
 665        $str = $cgi->escapeHTML($str);
 666        if ($opts{'-nbsp'}) {
 667                $str =~ s/ /&nbsp;/g;
 668        }
 669        $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
 670        return $str;
 671}
 672
 673# Make control characters "printable", using character escape codes (CEC)
 674sub quot_cec {
 675        my $cntrl = shift;
 676        my %es = ( # character escape codes, aka escape sequences
 677                   "\t" => '\t',   # tab            (HT)
 678                   "\n" => '\n',   # line feed      (LF)
 679                   "\r" => '\r',   # carrige return (CR)
 680                   "\f" => '\f',   # form feed      (FF)
 681                   "\b" => '\b',   # backspace      (BS)
 682                   "\a" => '\a',   # alarm (bell)   (BEL)
 683                   "\e" => '\e',   # escape         (ESC)
 684                   "\013" => '\v', # vertical tab   (VT)
 685                   "\000" => '\0', # nul character  (NUL)
 686                   );
 687        my $chr = ( (exists $es{$cntrl})
 688                    ? $es{$cntrl}
 689                    : sprintf('\%03o', ord($cntrl)) );
 690        return "<span class=\"cntrl\">$chr</span>";
 691}
 692
 693# Alternatively use unicode control pictures codepoints,
 694# Unicode "printable representation" (PR)
 695sub quot_upr {
 696        my $cntrl = shift;
 697        my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
 698        return "<span class=\"cntrl\">$chr</span>";
 699}
 700
 701# git may return quoted and escaped filenames
 702sub unquote {
 703        my $str = shift;
 704
 705        sub unq {
 706                my $seq = shift;
 707                my %es = ( # character escape codes, aka escape sequences
 708                        't' => "\t",   # tab            (HT, TAB)
 709                        'n' => "\n",   # newline        (NL)
 710                        'r' => "\r",   # return         (CR)
 711                        'f' => "\f",   # form feed      (FF)
 712                        'b' => "\b",   # backspace      (BS)
 713                        'a' => "\a",   # alarm (bell)   (BEL)
 714                        'e' => "\e",   # escape         (ESC)
 715                        'v' => "\013", # vertical tab   (VT)
 716                );
 717
 718                if ($seq =~ m/^[0-7]{1,3}$/) {
 719                        # octal char sequence
 720                        return chr(oct($seq));
 721                } elsif (exists $es{$seq}) {
 722                        # C escape sequence, aka character escape code
 723                        return $es{$seq}
 724                }
 725                # quoted ordinary character
 726                return $seq;
 727        }
 728
 729        if ($str =~ m/^"(.*)"$/) {
 730                # needs unquoting
 731                $str = $1;
 732                $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
 733        }
 734        return $str;
 735}
 736
 737# escape tabs (convert tabs to spaces)
 738sub untabify {
 739        my $line = shift;
 740
 741        while ((my $pos = index($line, "\t")) != -1) {
 742                if (my $count = (8 - ($pos % 8))) {
 743                        my $spaces = ' ' x $count;
 744                        $line =~ s/\t/$spaces/;
 745                }
 746        }
 747
 748        return $line;
 749}
 750
 751sub project_in_list {
 752        my $project = shift;
 753        my @list = git_get_projects_list();
 754        return @list && scalar(grep { $_->{'path'} eq $project } @list);
 755}
 756
 757## ----------------------------------------------------------------------
 758## HTML aware string manipulation
 759
 760sub chop_str {
 761        my $str = shift;
 762        my $len = shift;
 763        my $add_len = shift || 10;
 764
 765        # allow only $len chars, but don't cut a word if it would fit in $add_len
 766        # if it doesn't fit, cut it if it's still longer than the dots we would add
 767        $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
 768        my $body = $1;
 769        my $tail = $2;
 770        if (length($tail) > 4) {
 771                $tail = " ...";
 772                $body =~ s/&[^;]*$//; # remove chopped character entities
 773        }
 774        return "$body$tail";
 775}
 776
 777## ----------------------------------------------------------------------
 778## functions returning short strings
 779
 780# CSS class for given age value (in seconds)
 781sub age_class {
 782        my $age = shift;
 783
 784        if (!defined $age) {
 785                return "noage";
 786        } elsif ($age < 60*60*2) {
 787                return "age0";
 788        } elsif ($age < 60*60*24*2) {
 789                return "age1";
 790        } else {
 791                return "age2";
 792        }
 793}
 794
 795# convert age in seconds to "nn units ago" string
 796sub age_string {
 797        my $age = shift;
 798        my $age_str;
 799
 800        if ($age > 60*60*24*365*2) {
 801                $age_str = (int $age/60/60/24/365);
 802                $age_str .= " years ago";
 803        } elsif ($age > 60*60*24*(365/12)*2) {
 804                $age_str = int $age/60/60/24/(365/12);
 805                $age_str .= " months ago";
 806        } elsif ($age > 60*60*24*7*2) {
 807                $age_str = int $age/60/60/24/7;
 808                $age_str .= " weeks ago";
 809        } elsif ($age > 60*60*24*2) {
 810                $age_str = int $age/60/60/24;
 811                $age_str .= " days ago";
 812        } elsif ($age > 60*60*2) {
 813                $age_str = int $age/60/60;
 814                $age_str .= " hours ago";
 815        } elsif ($age > 60*2) {
 816                $age_str = int $age/60;
 817                $age_str .= " min ago";
 818        } elsif ($age > 2) {
 819                $age_str = int $age;
 820                $age_str .= " sec ago";
 821        } else {
 822                $age_str .= " right now";
 823        }
 824        return $age_str;
 825}
 826
 827# convert file mode in octal to symbolic file mode string
 828sub mode_str {
 829        my $mode = oct shift;
 830
 831        if (S_ISDIR($mode & S_IFMT)) {
 832                return 'drwxr-xr-x';
 833        } elsif (S_ISLNK($mode)) {
 834                return 'lrwxrwxrwx';
 835        } elsif (S_ISREG($mode)) {
 836                # git cares only about the executable bit
 837                if ($mode & S_IXUSR) {
 838                        return '-rwxr-xr-x';
 839                } else {
 840                        return '-rw-r--r--';
 841                };
 842        } else {
 843                return '----------';
 844        }
 845}
 846
 847# convert file mode in octal to file type string
 848sub file_type {
 849        my $mode = shift;
 850
 851        if ($mode !~ m/^[0-7]+$/) {
 852                return $mode;
 853        } else {
 854                $mode = oct $mode;
 855        }
 856
 857        if (S_ISDIR($mode & S_IFMT)) {
 858                return "directory";
 859        } elsif (S_ISLNK($mode)) {
 860                return "symlink";
 861        } elsif (S_ISREG($mode)) {
 862                return "file";
 863        } else {
 864                return "unknown";
 865        }
 866}
 867
 868# convert file mode in octal to file type description string
 869sub file_type_long {
 870        my $mode = shift;
 871
 872        if ($mode !~ m/^[0-7]+$/) {
 873                return $mode;
 874        } else {
 875                $mode = oct $mode;
 876        }
 877
 878        if (S_ISDIR($mode & S_IFMT)) {
 879                return "directory";
 880        } elsif (S_ISLNK($mode)) {
 881                return "symlink";
 882        } elsif (S_ISREG($mode)) {
 883                if ($mode & S_IXUSR) {
 884                        return "executable";
 885                } else {
 886                        return "file";
 887                };
 888        } else {
 889                return "unknown";
 890        }
 891}
 892
 893
 894## ----------------------------------------------------------------------
 895## functions returning short HTML fragments, or transforming HTML fragments
 896## which don't belong to other sections
 897
 898# format line of commit message.
 899sub format_log_line_html {
 900        my $line = shift;
 901
 902        $line = esc_html($line, -nbsp=>1);
 903        if ($line =~ m/([0-9a-fA-F]{8,40})/) {
 904                my $hash_text = $1;
 905                my $link =
 906                        $cgi->a({-href => href(action=>"object", hash=>$hash_text),
 907                                -class => "text"}, $hash_text);
 908                $line =~ s/$hash_text/$link/;
 909        }
 910        return $line;
 911}
 912
 913# format marker of refs pointing to given object
 914sub format_ref_marker {
 915        my ($refs, $id) = @_;
 916        my $markers = '';
 917
 918        if (defined $refs->{$id}) {
 919                foreach my $ref (@{$refs->{$id}}) {
 920                        my ($type, $name) = qw();
 921                        # e.g. tags/v2.6.11 or heads/next
 922                        if ($ref =~ m!^(.*?)s?/(.*)$!) {
 923                                $type = $1;
 924                                $name = $2;
 925                        } else {
 926                                $type = "ref";
 927                                $name = $ref;
 928                        }
 929
 930                        $markers .= " <span class=\"$type\" title=\"$ref\">" .
 931                                    esc_html($name) . "</span>";
 932                }
 933        }
 934
 935        if ($markers) {
 936                return ' <span class="refs">'. $markers . '</span>';
 937        } else {
 938                return "";
 939        }
 940}
 941
 942# format, perhaps shortened and with markers, title line
 943sub format_subject_html {
 944        my ($long, $short, $href, $extra) = @_;
 945        $extra = '' unless defined($extra);
 946
 947        if (length($short) < length($long)) {
 948                return $cgi->a({-href => $href, -class => "list subject",
 949                                -title => to_utf8($long)},
 950                       esc_html($short) . $extra);
 951        } else {
 952                return $cgi->a({-href => $href, -class => "list subject"},
 953                       esc_html($long)  . $extra);
 954        }
 955}
 956
 957# format git diff header line, i.e. "diff --(git|combined|cc) ..."
 958sub format_git_diff_header_line {
 959        my $line = shift;
 960        my $diffinfo = shift;
 961        my ($from, $to) = @_;
 962
 963        if ($diffinfo->{'nparents'}) {
 964                # combined diff
 965                $line =~ s!^(diff (.*?) )"?.*$!$1!;
 966                if ($to->{'href'}) {
 967                        $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
 968                                         esc_path($to->{'file'}));
 969                } else { # file was deleted (no href)
 970                        $line .= esc_path($to->{'file'});
 971                }
 972        } else {
 973                # "ordinary" diff
 974                $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
 975                if ($from->{'href'}) {
 976                        $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
 977                                         'a/' . esc_path($from->{'file'}));
 978                } else { # file was added (no href)
 979                        $line .= 'a/' . esc_path($from->{'file'});
 980                }
 981                $line .= ' ';
 982                if ($to->{'href'}) {
 983                        $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
 984                                         'b/' . esc_path($to->{'file'}));
 985                } else { # file was deleted
 986                        $line .= 'b/' . esc_path($to->{'file'});
 987                }
 988        }
 989
 990        return "<div class=\"diff header\">$line</div>\n";
 991}
 992
 993# format extended diff header line, before patch itself
 994sub format_extended_diff_header_line {
 995        my $line = shift;
 996        my $diffinfo = shift;
 997        my ($from, $to) = @_;
 998
 999        # match <path>
1000        if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1001                $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1002                                       esc_path($from->{'file'}));
1003        }
1004        if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1005                $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1006                                 esc_path($to->{'file'}));
1007        }
1008        # match single <mode>
1009        if ($line =~ m/\s(\d{6})$/) {
1010                $line .= '<span class="info"> (' .
1011                         file_type_long($1) .
1012                         ')</span>';
1013        }
1014        # match <hash>
1015        if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1016                # can match only for combined diff
1017                $line = 'index ';
1018                for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1019                        if ($from->{'href'}[$i]) {
1020                                $line .= $cgi->a({-href=>$from->{'href'}[$i],
1021                                                  -class=>"hash"},
1022                                                 substr($diffinfo->{'from_id'}[$i],0,7));
1023                        } else {
1024                                $line .= '0' x 7;
1025                        }
1026                        # separator
1027                        $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1028                }
1029                $line .= '..';
1030                if ($to->{'href'}) {
1031                        $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1032                                         substr($diffinfo->{'to_id'},0,7));
1033                } else {
1034                        $line .= '0' x 7;
1035                }
1036
1037        } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1038                # can match only for ordinary diff
1039                my ($from_link, $to_link);
1040                if ($from->{'href'}) {
1041                        $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1042                                             substr($diffinfo->{'from_id'},0,7));
1043                } else {
1044                        $from_link = '0' x 7;
1045                }
1046                if ($to->{'href'}) {
1047                        $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1048                                           substr($diffinfo->{'to_id'},0,7));
1049                } else {
1050                        $to_link = '0' x 7;
1051                }
1052                my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1053                $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1054        }
1055
1056        return $line . "<br/>\n";
1057}
1058
1059# format from-file/to-file diff header
1060sub format_diff_from_to_header {
1061        my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1062        my $line;
1063        my $result = '';
1064
1065        $line = $from_line;
1066        #assert($line =~ m/^---/) if DEBUG;
1067        # no extra formatting for "^--- /dev/null"
1068        if (! $diffinfo->{'nparents'}) {
1069                # ordinary (single parent) diff
1070                if ($line =~ m!^--- "?a/!) {
1071                        if ($from->{'href'}) {
1072                                $line = '--- a/' .
1073                                        $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1074                                                esc_path($from->{'file'}));
1075                        } else {
1076                                $line = '--- a/' .
1077                                        esc_path($from->{'file'});
1078                        }
1079                }
1080                $result .= qq!<div class="diff from_file">$line</div>\n!;
1081
1082        } else {
1083                # combined diff (merge commit)
1084                for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1085                        if ($from->{'href'}[$i]) {
1086                                $line = '--- ' .
1087                                        $cgi->a({-href=>href(action=>"blobdiff",
1088                                                             hash_parent=>$diffinfo->{'from_id'}[$i],
1089                                                             hash_parent_base=>$parents[$i],
1090                                                             file_parent=>$from->{'file'}[$i],
1091                                                             hash=>$diffinfo->{'to_id'},
1092                                                             hash_base=>$hash,
1093                                                             file_name=>$to->{'file'}),
1094                                                 -class=>"path",
1095                                                 -title=>"diff" . ($i+1)},
1096                                                $i+1) .
1097                                        '/' .
1098                                        $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1099                                                esc_path($from->{'file'}[$i]));
1100                        } else {
1101                                $line = '--- /dev/null';
1102                        }
1103                        $result .= qq!<div class="diff from_file">$line</div>\n!;
1104                }
1105        }
1106
1107        $line = $to_line;
1108        #assert($line =~ m/^\+\+\+/) if DEBUG;
1109        # no extra formatting for "^+++ /dev/null"
1110        if ($line =~ m!^\+\+\+ "?b/!) {
1111                if ($to->{'href'}) {
1112                        $line = '+++ b/' .
1113                                $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1114                                        esc_path($to->{'file'}));
1115                } else {
1116                        $line = '+++ b/' .
1117                                esc_path($to->{'file'});
1118                }
1119        }
1120        $result .= qq!<div class="diff to_file">$line</div>\n!;
1121
1122        return $result;
1123}
1124
1125# create note for patch simplified by combined diff
1126sub format_diff_cc_simplified {
1127        my ($diffinfo, @parents) = @_;
1128        my $result = '';
1129
1130        $result .= "<div class=\"diff header\">" .
1131                   "diff --cc ";
1132        if (!is_deleted($diffinfo)) {
1133                $result .= $cgi->a({-href => href(action=>"blob",
1134                                                  hash_base=>$hash,
1135                                                  hash=>$diffinfo->{'to_id'},
1136                                                  file_name=>$diffinfo->{'to_file'}),
1137                                    -class => "path"},
1138                                   esc_path($diffinfo->{'to_file'}));
1139        } else {
1140                $result .= esc_path($diffinfo->{'to_file'});
1141        }
1142        $result .= "</div>\n" . # class="diff header"
1143                   "<div class=\"diff nodifferences\">" .
1144                   "Simple merge" .
1145                   "</div>\n"; # class="diff nodifferences"
1146
1147        return $result;
1148}
1149
1150# format patch (diff) line (not to be used for diff headers)
1151sub format_diff_line {
1152        my $line = shift;
1153        my ($from, $to) = @_;
1154        my $diff_class = "";
1155
1156        chomp $line;
1157
1158        if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1159                # combined diff
1160                my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1161                if ($line =~ m/^\@{3}/) {
1162                        $diff_class = " chunk_header";
1163                } elsif ($line =~ m/^\\/) {
1164                        $diff_class = " incomplete";
1165                } elsif ($prefix =~ tr/+/+/) {
1166                        $diff_class = " add";
1167                } elsif ($prefix =~ tr/-/-/) {
1168                        $diff_class = " rem";
1169                }
1170        } else {
1171                # assume ordinary diff
1172                my $char = substr($line, 0, 1);
1173                if ($char eq '+') {
1174                        $diff_class = " add";
1175                } elsif ($char eq '-') {
1176                        $diff_class = " rem";
1177                } elsif ($char eq '@') {
1178                        $diff_class = " chunk_header";
1179                } elsif ($char eq "\\") {
1180                        $diff_class = " incomplete";
1181                }
1182        }
1183        $line = untabify($line);
1184        if ($from && $to && $line =~ m/^\@{2} /) {
1185                my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1186                        $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1187
1188                $from_lines = 0 unless defined $from_lines;
1189                $to_lines   = 0 unless defined $to_lines;
1190
1191                if ($from->{'href'}) {
1192                        $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1193                                             -class=>"list"}, $from_text);
1194                }
1195                if ($to->{'href'}) {
1196                        $to_text   = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1197                                             -class=>"list"}, $to_text);
1198                }
1199                $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1200                        "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1201                return "<div class=\"diff$diff_class\">$line</div>\n";
1202        } elsif ($from && $to && $line =~ m/^\@{3}/) {
1203                my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1204                my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1205
1206                @from_text = split(' ', $ranges);
1207                for (my $i = 0; $i < @from_text; ++$i) {
1208                        ($from_start[$i], $from_nlines[$i]) =
1209                                (split(',', substr($from_text[$i], 1)), 0);
1210                }
1211
1212                $to_text   = pop @from_text;
1213                $to_start  = pop @from_start;
1214                $to_nlines = pop @from_nlines;
1215
1216                $line = "<span class=\"chunk_info\">$prefix ";
1217                for (my $i = 0; $i < @from_text; ++$i) {
1218                        if ($from->{'href'}[$i]) {
1219                                $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1220                                                  -class=>"list"}, $from_text[$i]);
1221                        } else {
1222                                $line .= $from_text[$i];
1223                        }
1224                        $line .= " ";
1225                }
1226                if ($to->{'href'}) {
1227                        $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1228                                          -class=>"list"}, $to_text);
1229                } else {
1230                        $line .= $to_text;
1231                }
1232                $line .= " $prefix</span>" .
1233                         "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1234                return "<div class=\"diff$diff_class\">$line</div>\n";
1235        }
1236        return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1237}
1238
1239## ----------------------------------------------------------------------
1240## git utility subroutines, invoking git commands
1241
1242# returns path to the core git executable and the --git-dir parameter as list
1243sub git_cmd {
1244        return $GIT, '--git-dir='.$git_dir;
1245}
1246
1247# returns path to the core git executable and the --git-dir parameter as string
1248sub git_cmd_str {
1249        return join(' ', git_cmd());
1250}
1251
1252# get HEAD ref of given project as hash
1253sub git_get_head_hash {
1254        my $project = shift;
1255        my $o_git_dir = $git_dir;
1256        my $retval = undef;
1257        $git_dir = "$projectroot/$project";
1258        if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
1259                my $head = <$fd>;
1260                close $fd;
1261                if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
1262                        $retval = $1;
1263                }
1264        }
1265        if (defined $o_git_dir) {
1266                $git_dir = $o_git_dir;
1267        }
1268        return $retval;
1269}
1270
1271# get type of given object
1272sub git_get_type {
1273        my $hash = shift;
1274
1275        open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
1276        my $type = <$fd>;
1277        close $fd or return;
1278        chomp $type;
1279        return $type;
1280}
1281
1282sub git_get_project_config {
1283        my ($key, $type) = @_;
1284
1285        return unless ($key);
1286        $key =~ s/^gitweb\.//;
1287        return if ($key =~ m/\W/);
1288
1289        my @x = (git_cmd(), 'config');
1290        if (defined $type) { push @x, $type; }
1291        push @x, "--get";
1292        push @x, "gitweb.$key";
1293        my $val = qx(@x);
1294        chomp $val;
1295        return ($val);
1296}
1297
1298# get hash of given path at given ref
1299sub git_get_hash_by_path {
1300        my $base = shift;
1301        my $path = shift || return undef;
1302        my $type = shift;
1303
1304        $path =~ s,/+$,,;
1305
1306        open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
1307                or die_error(undef, "Open git-ls-tree failed");
1308        my $line = <$fd>;
1309        close $fd or return undef;
1310
1311        if (!defined $line) {
1312                # there is no tree or hash given by $path at $base
1313                return undef;
1314        }
1315
1316        #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1317        $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
1318        if (defined $type && $type ne $2) {
1319                # type doesn't match
1320                return undef;
1321        }
1322        return $3;
1323}
1324
1325# get path of entry with given hash at given tree-ish (ref)
1326# used to get 'from' filename for combined diff (merge commit) for renames
1327sub git_get_path_by_hash {
1328        my $base = shift || return;
1329        my $hash = shift || return;
1330
1331        local $/ = "\0";
1332
1333        open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
1334                or return undef;
1335        while (my $line = <$fd>) {
1336                chomp $line;
1337
1338                #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423  gitweb'
1339                #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f  gitweb/README'
1340                if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
1341                        close $fd;
1342                        return $1;
1343                }
1344        }
1345        close $fd;
1346        return undef;
1347}
1348
1349## ......................................................................
1350## git utility functions, directly accessing git repository
1351
1352sub git_get_project_description {
1353        my $path = shift;
1354
1355        open my $fd, "$projectroot/$path/description" or return undef;
1356        my $descr = <$fd>;
1357        close $fd;
1358        if (defined $descr) {
1359                chomp $descr;
1360        }
1361        return $descr;
1362}
1363
1364sub git_get_project_url_list {
1365        my $path = shift;
1366
1367        open my $fd, "$projectroot/$path/cloneurl" or return;
1368        my @git_project_url_list = map { chomp; $_ } <$fd>;
1369        close $fd;
1370
1371        return wantarray ? @git_project_url_list : \@git_project_url_list;
1372}
1373
1374sub git_get_projects_list {
1375        my ($filter) = @_;
1376        my @list;
1377
1378        $filter ||= '';
1379        $filter =~ s/\.git$//;
1380
1381        my ($check_forks) = gitweb_check_feature('forks');
1382
1383        if (-d $projects_list) {
1384                # search in directory
1385                my $dir = $projects_list . ($filter ? "/$filter" : '');
1386                # remove the trailing "/"
1387                $dir =~ s!/+$!!;
1388                my $pfxlen = length("$dir");
1389
1390                File::Find::find({
1391                        follow_fast => 1, # follow symbolic links
1392                        dangling_symlinks => 0, # ignore dangling symlinks, silently
1393                        wanted => sub {
1394                                # skip project-list toplevel, if we get it.
1395                                return if (m!^[/.]$!);
1396                                # only directories can be git repositories
1397                                return unless (-d $_);
1398
1399                                my $subdir = substr($File::Find::name, $pfxlen + 1);
1400                                # we check related file in $projectroot
1401                                if ($check_forks and $subdir =~ m#/.#) {
1402                                        $File::Find::prune = 1;
1403                                } elsif (check_export_ok("$projectroot/$filter/$subdir")) {
1404                                        push @list, { path => ($filter ? "$filter/" : '') . $subdir };
1405                                        $File::Find::prune = 1;
1406                                }
1407                        },
1408                }, "$dir");
1409
1410        } elsif (-f $projects_list) {
1411                # read from file(url-encoded):
1412                # 'git%2Fgit.git Linus+Torvalds'
1413                # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1414                # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1415                my %paths;
1416                open my ($fd), $projects_list or return;
1417        PROJECT:
1418                while (my $line = <$fd>) {
1419                        chomp $line;
1420                        my ($path, $owner) = split ' ', $line;
1421                        $path = unescape($path);
1422                        $owner = unescape($owner);
1423                        if (!defined $path) {
1424                                next;
1425                        }
1426                        if ($filter ne '') {
1427                                # looking for forks;
1428                                my $pfx = substr($path, 0, length($filter));
1429                                if ($pfx ne $filter) {
1430                                        next PROJECT;
1431                                }
1432                                my $sfx = substr($path, length($filter));
1433                                if ($sfx !~ /^\/.*\.git$/) {
1434                                        next PROJECT;
1435                                }
1436                        } elsif ($check_forks) {
1437                        PATH:
1438                                foreach my $filter (keys %paths) {
1439                                        # looking for forks;
1440                                        my $pfx = substr($path, 0, length($filter));
1441                                        if ($pfx ne $filter) {
1442                                                next PATH;
1443                                        }
1444                                        my $sfx = substr($path, length($filter));
1445                                        if ($sfx !~ /^\/.*\.git$/) {
1446                                                next PATH;
1447                                        }
1448                                        # is a fork, don't include it in
1449                                        # the list
1450                                        next PROJECT;
1451                                }
1452                        }
1453                        if (check_export_ok("$projectroot/$path")) {
1454                                my $pr = {
1455                                        path => $path,
1456                                        owner => to_utf8($owner),
1457                                };
1458                                push @list, $pr;
1459                                (my $forks_path = $path) =~ s/\.git$//;
1460                                $paths{$forks_path}++;
1461                        }
1462                }
1463                close $fd;
1464        }
1465        return @list;
1466}
1467
1468our $gitweb_project_owner = undef;
1469sub git_get_project_list_from_file {
1470
1471        return if (defined $gitweb_project_owner);
1472
1473        $gitweb_project_owner = {};
1474        # read from file (url-encoded):
1475        # 'git%2Fgit.git Linus+Torvalds'
1476        # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1477        # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1478        if (-f $projects_list) {
1479                open (my $fd , $projects_list);
1480                while (my $line = <$fd>) {
1481                        chomp $line;
1482                        my ($pr, $ow) = split ' ', $line;
1483                        $pr = unescape($pr);
1484                        $ow = unescape($ow);
1485                        $gitweb_project_owner->{$pr} = to_utf8($ow);
1486                }
1487                close $fd;
1488        }
1489}
1490
1491sub git_get_project_owner {
1492        my $project = shift;
1493        my $owner;
1494
1495        return undef unless $project;
1496
1497        if (!defined $gitweb_project_owner) {
1498                git_get_project_list_from_file();
1499        }
1500
1501        if (exists $gitweb_project_owner->{$project}) {
1502                $owner = $gitweb_project_owner->{$project};
1503        }
1504        if (!defined $owner) {
1505                $owner = get_file_owner("$projectroot/$project");
1506        }
1507
1508        return $owner;
1509}
1510
1511sub git_get_last_activity {
1512        my ($path) = @_;
1513        my $fd;
1514
1515        $git_dir = "$projectroot/$path";
1516        open($fd, "-|", git_cmd(), 'for-each-ref',
1517             '--format=%(committer)',
1518             '--sort=-committerdate',
1519             '--count=1',
1520             'refs/heads') or return;
1521        my $most_recent = <$fd>;
1522        close $fd or return;
1523        if (defined $most_recent &&
1524            $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
1525                my $timestamp = $1;
1526                my $age = time - $timestamp;
1527                return ($age, age_string($age));
1528        }
1529}
1530
1531sub git_get_references {
1532        my $type = shift || "";
1533        my %refs;
1534        # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
1535        # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
1536        open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
1537                ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
1538                or return;
1539
1540        while (my $line = <$fd>) {
1541                chomp $line;
1542                if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type/?[^^]+)!) {
1543                        if (defined $refs{$1}) {
1544                                push @{$refs{$1}}, $2;
1545                        } else {
1546                                $refs{$1} = [ $2 ];
1547                        }
1548                }
1549        }
1550        close $fd or return;
1551        return \%refs;
1552}
1553
1554sub git_get_rev_name_tags {
1555        my $hash = shift || return undef;
1556
1557        open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
1558                or return;
1559        my $name_rev = <$fd>;
1560        close $fd;
1561
1562        if ($name_rev =~ m|^$hash tags/(.*)$|) {
1563                return $1;
1564        } else {
1565                # catches also '$hash undefined' output
1566                return undef;
1567        }
1568}
1569
1570## ----------------------------------------------------------------------
1571## parse to hash functions
1572
1573sub parse_date {
1574        my $epoch = shift;
1575        my $tz = shift || "-0000";
1576
1577        my %date;
1578        my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
1579        my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
1580        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
1581        $date{'hour'} = $hour;
1582        $date{'minute'} = $min;
1583        $date{'mday'} = $mday;
1584        $date{'day'} = $days[$wday];
1585        $date{'month'} = $months[$mon];
1586        $date{'rfc2822'}   = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
1587                             $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
1588        $date{'mday-time'} = sprintf "%d %s %02d:%02d",
1589                             $mday, $months[$mon], $hour ,$min;
1590        $date{'iso-8601'}  = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
1591                             1900+$year, $mon, $mday, $hour ,$min, $sec;
1592
1593        $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
1594        my $local = $epoch + ((int $1 + ($2/60)) * 3600);
1595        ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
1596        $date{'hour_local'} = $hour;
1597        $date{'minute_local'} = $min;
1598        $date{'tz_local'} = $tz;
1599        $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
1600                                  1900+$year, $mon+1, $mday,
1601                                  $hour, $min, $sec, $tz);
1602        return %date;
1603}
1604
1605sub parse_tag {
1606        my $tag_id = shift;
1607        my %tag;
1608        my @comment;
1609
1610        open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
1611        $tag{'id'} = $tag_id;
1612        while (my $line = <$fd>) {
1613                chomp $line;
1614                if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
1615                        $tag{'object'} = $1;
1616                } elsif ($line =~ m/^type (.+)$/) {
1617                        $tag{'type'} = $1;
1618                } elsif ($line =~ m/^tag (.+)$/) {
1619                        $tag{'name'} = $1;
1620                } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
1621                        $tag{'author'} = $1;
1622                        $tag{'epoch'} = $2;
1623                        $tag{'tz'} = $3;
1624                } elsif ($line =~ m/--BEGIN/) {
1625                        push @comment, $line;
1626                        last;
1627                } elsif ($line eq "") {
1628                        last;
1629                }
1630        }
1631        push @comment, <$fd>;
1632        $tag{'comment'} = \@comment;
1633        close $fd or return;
1634        if (!defined $tag{'name'}) {
1635                return
1636        };
1637        return %tag
1638}
1639
1640sub parse_commit_text {
1641        my ($commit_text, $withparents) = @_;
1642        my @commit_lines = split '\n', $commit_text;
1643        my %co;
1644
1645        pop @commit_lines; # Remove '\0'
1646
1647        if (! @commit_lines) {
1648                return;
1649        }
1650
1651        my $header = shift @commit_lines;
1652        if ($header !~ m/^[0-9a-fA-F]{40}/) {
1653                return;
1654        }
1655        ($co{'id'}, my @parents) = split ' ', $header;
1656        while (my $line = shift @commit_lines) {
1657                last if $line eq "\n";
1658                if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1659                        $co{'tree'} = $1;
1660                } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
1661                        push @parents, $1;
1662                } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1663                        $co{'author'} = $1;
1664                        $co{'author_epoch'} = $2;
1665                        $co{'author_tz'} = $3;
1666                        if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
1667                                $co{'author_name'}  = $1;
1668                                $co{'author_email'} = $2;
1669                        } else {
1670                                $co{'author_name'} = $co{'author'};
1671                        }
1672                } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1673                        $co{'committer'} = $1;
1674                        $co{'committer_epoch'} = $2;
1675                        $co{'committer_tz'} = $3;
1676                        $co{'committer_name'} = $co{'committer'};
1677                        if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
1678                                $co{'committer_name'}  = $1;
1679                                $co{'committer_email'} = $2;
1680                        } else {
1681                                $co{'committer_name'} = $co{'committer'};
1682                        }
1683                }
1684        }
1685        if (!defined $co{'tree'}) {
1686                return;
1687        };
1688        $co{'parents'} = \@parents;
1689        $co{'parent'} = $parents[0];
1690
1691        foreach my $title (@commit_lines) {
1692                $title =~ s/^    //;
1693                if ($title ne "") {
1694                        $co{'title'} = chop_str($title, 80, 5);
1695                        # remove leading stuff of merges to make the interesting part visible
1696                        if (length($title) > 50) {
1697                                $title =~ s/^Automatic //;
1698                                $title =~ s/^merge (of|with) /Merge ... /i;
1699                                if (length($title) > 50) {
1700                                        $title =~ s/(http|rsync):\/\///;
1701                                }
1702                                if (length($title) > 50) {
1703                                        $title =~ s/(master|www|rsync)\.//;
1704                                }
1705                                if (length($title) > 50) {
1706                                        $title =~ s/kernel.org:?//;
1707                                }
1708                                if (length($title) > 50) {
1709                                        $title =~ s/\/pub\/scm//;
1710                                }
1711                        }
1712                        $co{'title_short'} = chop_str($title, 50, 5);
1713                        last;
1714                }
1715        }
1716        if ($co{'title'} eq "") {
1717                $co{'title'} = $co{'title_short'} = '(no commit message)';
1718        }
1719        # remove added spaces
1720        foreach my $line (@commit_lines) {
1721                $line =~ s/^    //;
1722        }
1723        $co{'comment'} = \@commit_lines;
1724
1725        my $age = time - $co{'committer_epoch'};
1726        $co{'age'} = $age;
1727        $co{'age_string'} = age_string($age);
1728        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1729        if ($age > 60*60*24*7*2) {
1730                $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1731                $co{'age_string_age'} = $co{'age_string'};
1732        } else {
1733                $co{'age_string_date'} = $co{'age_string'};
1734                $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1735        }
1736        return %co;
1737}
1738
1739sub parse_commit {
1740        my ($commit_id) = @_;
1741        my %co;
1742
1743        local $/ = "\0";
1744
1745        open my $fd, "-|", git_cmd(), "rev-list",
1746                "--parents",
1747                "--header",
1748                "--max-count=1",
1749                $commit_id,
1750                "--",
1751                or die_error(undef, "Open git-rev-list failed");
1752        %co = parse_commit_text(<$fd>, 1);
1753        close $fd;
1754
1755        return %co;
1756}
1757
1758sub parse_commits {
1759        my ($commit_id, $maxcount, $skip, $arg, $filename) = @_;
1760        my @cos;
1761
1762        $maxcount ||= 1;
1763        $skip ||= 0;
1764
1765        local $/ = "\0";
1766
1767        open my $fd, "-|", git_cmd(), "rev-list",
1768                "--header",
1769                ($arg ? ($arg) : ()),
1770                ("--max-count=" . $maxcount),
1771                ("--skip=" . $skip),
1772                $commit_id,
1773                "--",
1774                ($filename ? ($filename) : ())
1775                or die_error(undef, "Open git-rev-list failed");
1776        while (my $line = <$fd>) {
1777                my %co = parse_commit_text($line);
1778                push @cos, \%co;
1779        }
1780        close $fd;
1781
1782        return wantarray ? @cos : \@cos;
1783}
1784
1785# parse ref from ref_file, given by ref_id, with given type
1786sub parse_ref {
1787        my $ref_file = shift;
1788        my $ref_id = shift;
1789        my $type = shift || git_get_type($ref_id);
1790        my %ref_item;
1791
1792        $ref_item{'type'} = $type;
1793        $ref_item{'id'} = $ref_id;
1794        $ref_item{'epoch'} = 0;
1795        $ref_item{'age'} = "unknown";
1796        if ($type eq "tag") {
1797                my %tag = parse_tag($ref_id);
1798                $ref_item{'comment'} = $tag{'comment'};
1799                if ($tag{'type'} eq "commit") {
1800                        my %co = parse_commit($tag{'object'});
1801                        $ref_item{'epoch'} = $co{'committer_epoch'};
1802                        $ref_item{'age'} = $co{'age_string'};
1803                } elsif (defined($tag{'epoch'})) {
1804                        my $age = time - $tag{'epoch'};
1805                        $ref_item{'epoch'} = $tag{'epoch'};
1806                        $ref_item{'age'} = age_string($age);
1807                }
1808                $ref_item{'reftype'} = $tag{'type'};
1809                $ref_item{'name'} = $tag{'name'};
1810                $ref_item{'refid'} = $tag{'object'};
1811        } elsif ($type eq "commit"){
1812                my %co = parse_commit($ref_id);
1813                $ref_item{'reftype'} = "commit";
1814                $ref_item{'name'} = $ref_file;
1815                $ref_item{'title'} = $co{'title'};
1816                $ref_item{'refid'} = $ref_id;
1817                $ref_item{'epoch'} = $co{'committer_epoch'};
1818                $ref_item{'age'} = $co{'age_string'};
1819        } else {
1820                $ref_item{'reftype'} = $type;
1821                $ref_item{'name'} = $ref_file;
1822                $ref_item{'refid'} = $ref_id;
1823        }
1824
1825        return %ref_item;
1826}
1827
1828# parse line of git-diff-tree "raw" output
1829sub parse_difftree_raw_line {
1830        my $line = shift;
1831        my %res;
1832
1833        # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1834        # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1835        if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1836                $res{'from_mode'} = $1;
1837                $res{'to_mode'} = $2;
1838                $res{'from_id'} = $3;
1839                $res{'to_id'} = $4;
1840                $res{'status'} = $5;
1841                $res{'similarity'} = $6;
1842                if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1843                        ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1844                } else {
1845                        $res{'file'} = unquote($7);
1846                }
1847        }
1848        # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
1849        # combined diff (for merge commit)
1850        elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
1851                $res{'nparents'}  = length($1);
1852                $res{'from_mode'} = [ split(' ', $2) ];
1853                $res{'to_mode'} = pop @{$res{'from_mode'}};
1854                $res{'from_id'} = [ split(' ', $3) ];
1855                $res{'to_id'} = pop @{$res{'from_id'}};
1856                $res{'status'} = [ split('', $4) ];
1857                $res{'to_file'} = unquote($5);
1858        }
1859        # 'c512b523472485aef4fff9e57b229d9d243c967f'
1860        elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1861                $res{'commit'} = $1;
1862        }
1863
1864        return wantarray ? %res : \%res;
1865}
1866
1867# parse line of git-ls-tree output
1868sub parse_ls_tree_line ($;%) {
1869        my $line = shift;
1870        my %opts = @_;
1871        my %res;
1872
1873        #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1874        $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
1875
1876        $res{'mode'} = $1;
1877        $res{'type'} = $2;
1878        $res{'hash'} = $3;
1879        if ($opts{'-z'}) {
1880                $res{'name'} = $4;
1881        } else {
1882                $res{'name'} = unquote($4);
1883        }
1884
1885        return wantarray ? %res : \%res;
1886}
1887
1888# generates _two_ hashes, references to which are passed as 2 and 3 argument
1889sub parse_from_to_diffinfo {
1890        my ($diffinfo, $from, $to, @parents) = @_;
1891
1892        if ($diffinfo->{'nparents'}) {
1893                # combined diff
1894                $from->{'file'} = [];
1895                $from->{'href'} = [];
1896                fill_from_file_info($diffinfo, @parents)
1897                        unless exists $diffinfo->{'from_file'};
1898                for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1899                        $from->{'file'}[$i] = $diffinfo->{'from_file'}[$i] || $diffinfo->{'to_file'};
1900                        if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
1901                                $from->{'href'}[$i] = href(action=>"blob",
1902                                                           hash_base=>$parents[$i],
1903                                                           hash=>$diffinfo->{'from_id'}[$i],
1904                                                           file_name=>$from->{'file'}[$i]);
1905                        } else {
1906                                $from->{'href'}[$i] = undef;
1907                        }
1908                }
1909        } else {
1910                $from->{'file'} = $diffinfo->{'from_file'} || $diffinfo->{'file'};
1911                if ($diffinfo->{'status'} ne "A") { # not new (added) file
1912                        $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
1913                                               hash=>$diffinfo->{'from_id'},
1914                                               file_name=>$from->{'file'});
1915                } else {
1916                        delete $from->{'href'};
1917                }
1918        }
1919
1920        $to->{'file'} = $diffinfo->{'to_file'} || $diffinfo->{'file'};
1921        if (!is_deleted($diffinfo)) { # file exists in result
1922                $to->{'href'} = href(action=>"blob", hash_base=>$hash,
1923                                     hash=>$diffinfo->{'to_id'},
1924                                     file_name=>$to->{'file'});
1925        } else {
1926                delete $to->{'href'};
1927        }
1928}
1929
1930## ......................................................................
1931## parse to array of hashes functions
1932
1933sub git_get_heads_list {
1934        my $limit = shift;
1935        my @headslist;
1936
1937        open my $fd, '-|', git_cmd(), 'for-each-ref',
1938                ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
1939                '--format=%(objectname) %(refname) %(subject)%00%(committer)',
1940                'refs/heads'
1941                or return;
1942        while (my $line = <$fd>) {
1943                my %ref_item;
1944
1945                chomp $line;
1946                my ($refinfo, $committerinfo) = split(/\0/, $line);
1947                my ($hash, $name, $title) = split(' ', $refinfo, 3);
1948                my ($committer, $epoch, $tz) =
1949                        ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
1950                $name =~ s!^refs/heads/!!;
1951
1952                $ref_item{'name'}  = $name;
1953                $ref_item{'id'}    = $hash;
1954                $ref_item{'title'} = $title || '(no commit message)';
1955                $ref_item{'epoch'} = $epoch;
1956                if ($epoch) {
1957                        $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
1958                } else {
1959                        $ref_item{'age'} = "unknown";
1960                }
1961
1962                push @headslist, \%ref_item;
1963        }
1964        close $fd;
1965
1966        return wantarray ? @headslist : \@headslist;
1967}
1968
1969sub git_get_tags_list {
1970        my $limit = shift;
1971        my @tagslist;
1972
1973        open my $fd, '-|', git_cmd(), 'for-each-ref',
1974                ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
1975                '--format=%(objectname) %(objecttype) %(refname) '.
1976                '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
1977                'refs/tags'
1978                or return;
1979        while (my $line = <$fd>) {
1980                my %ref_item;
1981
1982                chomp $line;
1983                my ($refinfo, $creatorinfo) = split(/\0/, $line);
1984                my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
1985                my ($creator, $epoch, $tz) =
1986                        ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
1987                $name =~ s!^refs/tags/!!;
1988
1989                $ref_item{'type'} = $type;
1990                $ref_item{'id'} = $id;
1991                $ref_item{'name'} = $name;
1992                if ($type eq "tag") {
1993                        $ref_item{'subject'} = $title;
1994                        $ref_item{'reftype'} = $reftype;
1995                        $ref_item{'refid'}   = $refid;
1996                } else {
1997                        $ref_item{'reftype'} = $type;
1998                        $ref_item{'refid'}   = $id;
1999                }
2000
2001                if ($type eq "tag" || $type eq "commit") {
2002                        $ref_item{'epoch'} = $epoch;
2003                        if ($epoch) {
2004                                $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2005                        } else {
2006                                $ref_item{'age'} = "unknown";
2007                        }
2008                }
2009
2010                push @tagslist, \%ref_item;
2011        }
2012        close $fd;
2013
2014        return wantarray ? @tagslist : \@tagslist;
2015}
2016
2017## ----------------------------------------------------------------------
2018## filesystem-related functions
2019
2020sub get_file_owner {
2021        my $path = shift;
2022
2023        my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2024        my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2025        if (!defined $gcos) {
2026                return undef;
2027        }
2028        my $owner = $gcos;
2029        $owner =~ s/[,;].*$//;
2030        return to_utf8($owner);
2031}
2032
2033## ......................................................................
2034## mimetype related functions
2035
2036sub mimetype_guess_file {
2037        my $filename = shift;
2038        my $mimemap = shift;
2039        -r $mimemap or return undef;
2040
2041        my %mimemap;
2042        open(MIME, $mimemap) or return undef;
2043        while (<MIME>) {
2044                next if m/^#/; # skip comments
2045                my ($mime, $exts) = split(/\t+/);
2046                if (defined $exts) {
2047                        my @exts = split(/\s+/, $exts);
2048                        foreach my $ext (@exts) {
2049                                $mimemap{$ext} = $mime;
2050                        }
2051                }
2052        }
2053        close(MIME);
2054
2055        $filename =~ /\.([^.]*)$/;
2056        return $mimemap{$1};
2057}
2058
2059sub mimetype_guess {
2060        my $filename = shift;
2061        my $mime;
2062        $filename =~ /\./ or return undef;
2063
2064        if ($mimetypes_file) {
2065                my $file = $mimetypes_file;
2066                if ($file !~ m!^/!) { # if it is relative path
2067                        # it is relative to project
2068                        $file = "$projectroot/$project/$file";
2069                }
2070                $mime = mimetype_guess_file($filename, $file);
2071        }
2072        $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
2073        return $mime;
2074}
2075
2076sub blob_mimetype {
2077        my $fd = shift;
2078        my $filename = shift;
2079
2080        if ($filename) {
2081                my $mime = mimetype_guess($filename);
2082                $mime and return $mime;
2083        }
2084
2085        # just in case
2086        return $default_blob_plain_mimetype unless $fd;
2087
2088        if (-T $fd) {
2089                return 'text/plain' .
2090                       ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
2091        } elsif (! $filename) {
2092                return 'application/octet-stream';
2093        } elsif ($filename =~ m/\.png$/i) {
2094                return 'image/png';
2095        } elsif ($filename =~ m/\.gif$/i) {
2096                return 'image/gif';
2097        } elsif ($filename =~ m/\.jpe?g$/i) {
2098                return 'image/jpeg';
2099        } else {
2100                return 'application/octet-stream';
2101        }
2102}
2103
2104## ======================================================================
2105## functions printing HTML: header, footer, error page
2106
2107sub git_header_html {
2108        my $status = shift || "200 OK";
2109        my $expires = shift;
2110
2111        my $title = "$site_name";
2112        if (defined $project) {
2113                $title .= " - " . to_utf8($project);
2114                if (defined $action) {
2115                        $title .= "/$action";
2116                        if (defined $file_name) {
2117                                $title .= " - " . esc_path($file_name);
2118                                if ($action eq "tree" && $file_name !~ m|/$|) {
2119                                        $title .= "/";
2120                                }
2121                        }
2122                }
2123        }
2124        my $content_type;
2125        # require explicit support from the UA if we are to send the page as
2126        # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
2127        # we have to do this because MSIE sometimes globs '*/*', pretending to
2128        # support xhtml+xml but choking when it gets what it asked for.
2129        if (defined $cgi->http('HTTP_ACCEPT') &&
2130            $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
2131            $cgi->Accept('application/xhtml+xml') != 0) {
2132                $content_type = 'application/xhtml+xml';
2133        } else {
2134                $content_type = 'text/html';
2135        }
2136        print $cgi->header(-type=>$content_type, -charset => 'utf-8',
2137                           -status=> $status, -expires => $expires);
2138        my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
2139        print <<EOF;
2140<?xml version="1.0" encoding="utf-8"?>
2141<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2142<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
2143<!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
2144<!-- git core binaries version $git_version -->
2145<head>
2146<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
2147<meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
2148<meta name="robots" content="index, nofollow"/>
2149<title>$title</title>
2150EOF
2151# print out each stylesheet that exist
2152        if (defined $stylesheet) {
2153#provides backwards capability for those people who define style sheet in a config file
2154                print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2155        } else {
2156                foreach my $stylesheet (@stylesheets) {
2157                        next unless $stylesheet;
2158                        print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2159                }
2160        }
2161        if (defined $project) {
2162                printf('<link rel="alternate" title="%s log RSS feed" '.
2163                       'href="%s" type="application/rss+xml" />'."\n",
2164                       esc_param($project), href(action=>"rss"));
2165                printf('<link rel="alternate" title="%s log Atom feed" '.
2166                       'href="%s" type="application/atom+xml" />'."\n",
2167                       esc_param($project), href(action=>"atom"));
2168        } else {
2169                printf('<link rel="alternate" title="%s projects list" '.
2170                       'href="%s" type="text/plain; charset=utf-8"/>'."\n",
2171                       $site_name, href(project=>undef, action=>"project_index"));
2172                printf('<link rel="alternate" title="%s projects feeds" '.
2173                       'href="%s" type="text/x-opml"/>'."\n",
2174                       $site_name, href(project=>undef, action=>"opml"));
2175        }
2176        if (defined $favicon) {
2177                print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
2178        }
2179
2180        print "</head>\n" .
2181              "<body>\n";
2182
2183        if (-f $site_header) {
2184                open (my $fd, $site_header);
2185                print <$fd>;
2186                close $fd;
2187        }
2188
2189        print "<div class=\"page_header\">\n" .
2190              $cgi->a({-href => esc_url($logo_url),
2191                       -title => $logo_label},
2192                      qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
2193        print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
2194        if (defined $project) {
2195                print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
2196                if (defined $action) {
2197                        print " / $action";
2198                }
2199                print "\n";
2200        }
2201        print "</div>\n";
2202
2203        my ($have_search) = gitweb_check_feature('search');
2204        if ((defined $project) && ($have_search)) {
2205                if (!defined $searchtext) {
2206                        $searchtext = "";
2207                }
2208                my $search_hash;
2209                if (defined $hash_base) {
2210                        $search_hash = $hash_base;
2211                } elsif (defined $hash) {
2212                        $search_hash = $hash;
2213                } else {
2214                        $search_hash = "HEAD";
2215                }
2216                my $action = $my_uri;
2217                my ($use_pathinfo) = gitweb_check_feature('pathinfo');
2218                if ($use_pathinfo) {
2219                        $action .= "/$project";
2220                } else {
2221                        $cgi->param("p", $project);
2222                }
2223                $cgi->param("a", "search");
2224                $cgi->param("h", $search_hash);
2225                print $cgi->startform(-method => "get", -action => $action) .
2226                      "<div class=\"search\">\n" .
2227                      (!$use_pathinfo && $cgi->hidden(-name => "p") . "\n") .
2228                      $cgi->hidden(-name => "a") . "\n" .
2229                      $cgi->hidden(-name => "h") . "\n" .
2230                      $cgi->popup_menu(-name => 'st', -default => 'commit',
2231                                       -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
2232                      $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
2233                      " search:\n",
2234                      $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
2235                      "</div>" .
2236                      $cgi->end_form() . "\n";
2237        }
2238}
2239
2240sub git_footer_html {
2241        print "<div class=\"page_footer\">\n";
2242        if (defined $project) {
2243                my $descr = git_get_project_description($project);
2244                if (defined $descr) {
2245                        print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
2246                }
2247                print $cgi->a({-href => href(action=>"rss"),
2248                              -class => "rss_logo"}, "RSS") . " ";
2249                print $cgi->a({-href => href(action=>"atom"),
2250                              -class => "rss_logo"}, "Atom") . "\n";
2251        } else {
2252                print $cgi->a({-href => href(project=>undef, action=>"opml"),
2253                              -class => "rss_logo"}, "OPML") . " ";
2254                print $cgi->a({-href => href(project=>undef, action=>"project_index"),
2255                              -class => "rss_logo"}, "TXT") . "\n";
2256        }
2257        print "</div>\n" ;
2258
2259        if (-f $site_footer) {
2260                open (my $fd, $site_footer);
2261                print <$fd>;
2262                close $fd;
2263        }
2264
2265        print "</body>\n" .
2266              "</html>";
2267}
2268
2269sub die_error {
2270        my $status = shift || "403 Forbidden";
2271        my $error = shift || "Malformed query, file missing or permission denied";
2272
2273        git_header_html($status);
2274        print <<EOF;
2275<div class="page_body">
2276<br /><br />
2277$status - $error
2278<br />
2279</div>
2280EOF
2281        git_footer_html();
2282        exit;
2283}
2284
2285## ----------------------------------------------------------------------
2286## functions printing or outputting HTML: navigation
2287
2288sub git_print_page_nav {
2289        my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
2290        $extra = '' if !defined $extra; # pager or formats
2291
2292        my @navs = qw(summary shortlog log commit commitdiff tree);
2293        if ($suppress) {
2294                @navs = grep { $_ ne $suppress } @navs;
2295        }
2296
2297        my %arg = map { $_ => {action=>$_} } @navs;
2298        if (defined $head) {
2299                for (qw(commit commitdiff)) {
2300                        $arg{$_}{'hash'} = $head;
2301                }
2302                if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
2303                        for (qw(shortlog log)) {
2304                                $arg{$_}{'hash'} = $head;
2305                        }
2306                }
2307        }
2308        $arg{'tree'}{'hash'} = $treehead if defined $treehead;
2309        $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
2310
2311        print "<div class=\"page_nav\">\n" .
2312                (join " | ",
2313                 map { $_ eq $current ?
2314                       $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
2315                 } @navs);
2316        print "<br/>\n$extra<br/>\n" .
2317              "</div>\n";
2318}
2319
2320sub format_paging_nav {
2321        my ($action, $hash, $head, $page, $nrevs) = @_;
2322        my $paging_nav;
2323
2324
2325        if ($hash ne $head || $page) {
2326                $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
2327        } else {
2328                $paging_nav .= "HEAD";
2329        }
2330
2331        if ($page > 0) {
2332                $paging_nav .= " &sdot; " .
2333                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
2334                                 -accesskey => "p", -title => "Alt-p"}, "prev");
2335        } else {
2336                $paging_nav .= " &sdot; prev";
2337        }
2338
2339        if ($nrevs >= (100 * ($page+1)-1)) {
2340                $paging_nav .= " &sdot; " .
2341                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
2342                                 -accesskey => "n", -title => "Alt-n"}, "next");
2343        } else {
2344                $paging_nav .= " &sdot; next";
2345        }
2346
2347        return $paging_nav;
2348}
2349
2350## ......................................................................
2351## functions printing or outputting HTML: div
2352
2353sub git_print_header_div {
2354        my ($action, $title, $hash, $hash_base) = @_;
2355        my %args = ();
2356
2357        $args{'action'} = $action;
2358        $args{'hash'} = $hash if $hash;
2359        $args{'hash_base'} = $hash_base if $hash_base;
2360
2361        print "<div class=\"header\">\n" .
2362              $cgi->a({-href => href(%args), -class => "title"},
2363              $title ? $title : $action) .
2364              "\n</div>\n";
2365}
2366
2367#sub git_print_authorship (\%) {
2368sub git_print_authorship {
2369        my $co = shift;
2370
2371        my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
2372        print "<div class=\"author_date\">" .
2373              esc_html($co->{'author_name'}) .
2374              " [$ad{'rfc2822'}";
2375        if ($ad{'hour_local'} < 6) {
2376                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2377                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2378        } else {
2379                printf(" (%02d:%02d %s)",
2380                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2381        }
2382        print "]</div>\n";
2383}
2384
2385sub git_print_page_path {
2386        my $name = shift;
2387        my $type = shift;
2388        my $hb = shift;
2389
2390
2391        print "<div class=\"page_path\">";
2392        print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
2393                      -title => 'tree root'}, to_utf8("[$project]"));
2394        print " / ";
2395        if (defined $name) {
2396                my @dirname = split '/', $name;
2397                my $basename = pop @dirname;
2398                my $fullname = '';
2399
2400                foreach my $dir (@dirname) {
2401                        $fullname .= ($fullname ? '/' : '') . $dir;
2402                        print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
2403                                                     hash_base=>$hb),
2404                                      -title => $fullname}, esc_path($dir));
2405                        print " / ";
2406                }
2407                if (defined $type && $type eq 'blob') {
2408                        print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
2409                                                     hash_base=>$hb),
2410                                      -title => $name}, esc_path($basename));
2411                } elsif (defined $type && $type eq 'tree') {
2412                        print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
2413                                                     hash_base=>$hb),
2414                                      -title => $name}, esc_path($basename));
2415                        print " / ";
2416                } else {
2417                        print esc_path($basename);
2418                }
2419        }
2420        print "<br/></div>\n";
2421}
2422
2423# sub git_print_log (\@;%) {
2424sub git_print_log ($;%) {
2425        my $log = shift;
2426        my %opts = @_;
2427
2428        if ($opts{'-remove_title'}) {
2429                # remove title, i.e. first line of log
2430                shift @$log;
2431        }
2432        # remove leading empty lines
2433        while (defined $log->[0] && $log->[0] eq "") {
2434                shift @$log;
2435        }
2436
2437        # print log
2438        my $signoff = 0;
2439        my $empty = 0;
2440        foreach my $line (@$log) {
2441                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2442                        $signoff = 1;
2443                        $empty = 0;
2444                        if (! $opts{'-remove_signoff'}) {
2445                                print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
2446                                next;
2447                        } else {
2448                                # remove signoff lines
2449                                next;
2450                        }
2451                } else {
2452                        $signoff = 0;
2453                }
2454
2455                # print only one empty line
2456                # do not print empty line after signoff
2457                if ($line eq "") {
2458                        next if ($empty || $signoff);
2459                        $empty = 1;
2460                } else {
2461                        $empty = 0;
2462                }
2463
2464                print format_log_line_html($line) . "<br/>\n";
2465        }
2466
2467        if ($opts{'-final_empty_line'}) {
2468                # end with single empty line
2469                print "<br/>\n" unless $empty;
2470        }
2471}
2472
2473# return link target (what link points to)
2474sub git_get_link_target {
2475        my $hash = shift;
2476        my $link_target;
2477
2478        # read link
2479        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2480                or return;
2481        {
2482                local $/;
2483                $link_target = <$fd>;
2484        }
2485        close $fd
2486                or return;
2487
2488        return $link_target;
2489}
2490
2491# given link target, and the directory (basedir) the link is in,
2492# return target of link relative to top directory (top tree);
2493# return undef if it is not possible (including absolute links).
2494sub normalize_link_target {
2495        my ($link_target, $basedir, $hash_base) = @_;
2496
2497        # we can normalize symlink target only if $hash_base is provided
2498        return unless $hash_base;
2499
2500        # absolute symlinks (beginning with '/') cannot be normalized
2501        return if (substr($link_target, 0, 1) eq '/');
2502
2503        # normalize link target to path from top (root) tree (dir)
2504        my $path;
2505        if ($basedir) {
2506                $path = $basedir . '/' . $link_target;
2507        } else {
2508                # we are in top (root) tree (dir)
2509                $path = $link_target;
2510        }
2511
2512        # remove //, /./, and /../
2513        my @path_parts;
2514        foreach my $part (split('/', $path)) {
2515                # discard '.' and ''
2516                next if (!$part || $part eq '.');
2517                # handle '..'
2518                if ($part eq '..') {
2519                        if (@path_parts) {
2520                                pop @path_parts;
2521                        } else {
2522                                # link leads outside repository (outside top dir)
2523                                return;
2524                        }
2525                } else {
2526                        push @path_parts, $part;
2527                }
2528        }
2529        $path = join('/', @path_parts);
2530
2531        return $path;
2532}
2533
2534# print tree entry (row of git_tree), but without encompassing <tr> element
2535sub git_print_tree_entry {
2536        my ($t, $basedir, $hash_base, $have_blame) = @_;
2537
2538        my %base_key = ();
2539        $base_key{'hash_base'} = $hash_base if defined $hash_base;
2540
2541        # The format of a table row is: mode list link.  Where mode is
2542        # the mode of the entry, list is the name of the entry, an href,
2543        # and link is the action links of the entry.
2544
2545        print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
2546        if ($t->{'type'} eq "blob") {
2547                print "<td class=\"list\">" .
2548                        $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2549                                               file_name=>"$basedir$t->{'name'}", %base_key),
2550                                -class => "list"}, esc_path($t->{'name'}));
2551                if (S_ISLNK(oct $t->{'mode'})) {
2552                        my $link_target = git_get_link_target($t->{'hash'});
2553                        if ($link_target) {
2554                                my $norm_target = normalize_link_target($link_target, $basedir, $hash_base);
2555                                if (defined $norm_target) {
2556                                        print " -> " .
2557                                              $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
2558                                                                     file_name=>$norm_target),
2559                                                       -title => $norm_target}, esc_path($link_target));
2560                                } else {
2561                                        print " -> " . esc_path($link_target);
2562                                }
2563                        }
2564                }
2565                print "</td>\n";
2566                print "<td class=\"link\">";
2567                print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2568                                             file_name=>"$basedir$t->{'name'}", %base_key)},
2569                              "blob");
2570                if ($have_blame) {
2571                        print " | " .
2572                              $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
2573                                                     file_name=>"$basedir$t->{'name'}", %base_key)},
2574                                      "blame");
2575                }
2576                if (defined $hash_base) {
2577                        print " | " .
2578                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2579                                                     hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
2580                                      "history");
2581                }
2582                print " | " .
2583                        $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
2584                                               file_name=>"$basedir$t->{'name'}")},
2585                                "raw");
2586                print "</td>\n";
2587
2588        } elsif ($t->{'type'} eq "tree") {
2589                print "<td class=\"list\">";
2590                print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2591                                             file_name=>"$basedir$t->{'name'}", %base_key)},
2592                              esc_path($t->{'name'}));
2593                print "</td>\n";
2594                print "<td class=\"link\">";
2595                print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2596                                             file_name=>"$basedir$t->{'name'}", %base_key)},
2597                              "tree");
2598                if (defined $hash_base) {
2599                        print " | " .
2600                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2601                                                     file_name=>"$basedir$t->{'name'}")},
2602                                      "history");
2603                }
2604                print "</td>\n";
2605        }
2606}
2607
2608## ......................................................................
2609## functions printing large fragments of HTML
2610
2611sub fill_from_file_info {
2612        my ($diff, @parents) = @_;
2613
2614        $diff->{'from_file'} = [ ];
2615        $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
2616        for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
2617                if ($diff->{'status'}[$i] eq 'R' ||
2618                    $diff->{'status'}[$i] eq 'C') {
2619                        $diff->{'from_file'}[$i] =
2620                                git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
2621                }
2622        }
2623
2624        return $diff;
2625}
2626
2627# parameters can be strings, or references to arrays of strings
2628sub from_ids_eq {
2629        my ($a, $b) = @_;
2630
2631        if (ref($a) eq "ARRAY" && ref($b) eq "ARRAY" && @$a == @$b) {
2632                for (my $i = 0; $i < @$a; ++$i) {
2633                        return 0 unless ($a->[$i] eq $b->[$i]);
2634                }
2635                return 1;
2636        } elsif (!ref($a) && !ref($b)) {
2637                return $a eq $b;
2638        } else {
2639                return 0;
2640        }
2641}
2642
2643sub is_deleted {
2644        my $diffinfo = shift;
2645
2646        return $diffinfo->{'to_id'} eq ('0' x 40);
2647}
2648
2649sub git_difftree_body {
2650        my ($difftree, $hash, @parents) = @_;
2651        my ($parent) = $parents[0];
2652        my ($have_blame) = gitweb_check_feature('blame');
2653        print "<div class=\"list_head\">\n";
2654        if ($#{$difftree} > 10) {
2655                print(($#{$difftree} + 1) . " files changed:\n");
2656        }
2657        print "</div>\n";
2658
2659        print "<table class=\"" .
2660              (@parents > 1 ? "combined " : "") .
2661              "diff_tree\">\n";
2662
2663        # header only for combined diff in 'commitdiff' view
2664        my $has_header = @parents > 1 && $action eq 'commitdiff';
2665        if ($has_header) {
2666                # table header
2667                print "<thead><tr>\n" .
2668                       "<th></th><th></th>\n"; # filename, patchN link
2669                for (my $i = 0; $i < @parents; $i++) {
2670                        my $par = $parents[$i];
2671                        print "<th>" .
2672                              $cgi->a({-href => href(action=>"commitdiff",
2673                                                     hash=>$hash, hash_parent=>$par),
2674                                       -title => 'commitdiff to parent number ' .
2675                                                  ($i+1) . ': ' . substr($par,0,7)},
2676                                      $i+1) .
2677                              "&nbsp;</th>\n";
2678                }
2679                print "</tr></thead>\n<tbody>\n";
2680        }
2681
2682        my $alternate = 1;
2683        my $patchno = 0;
2684        foreach my $line (@{$difftree}) {
2685                my $diff;
2686                if (ref($line) eq "HASH") {
2687                        # pre-parsed (or generated by hand)
2688                        $diff = $line;
2689                } else {
2690                        $diff = parse_difftree_raw_line($line);
2691                }
2692
2693                if ($alternate) {
2694                        print "<tr class=\"dark\">\n";
2695                } else {
2696                        print "<tr class=\"light\">\n";
2697                }
2698                $alternate ^= 1;
2699
2700                if (exists $diff->{'nparents'}) { # combined diff
2701
2702                        fill_from_file_info($diff, @parents)
2703                                unless exists $diff->{'from_file'};
2704
2705                        if (!is_deleted($diff)) {
2706                                # file exists in the result (child) commit
2707                                print "<td>" .
2708                                      $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2709                                                             file_name=>$diff->{'to_file'},
2710                                                             hash_base=>$hash),
2711                                              -class => "list"}, esc_path($diff->{'to_file'})) .
2712                                      "</td>\n";
2713                        } else {
2714                                print "<td>" .
2715                                      esc_path($diff->{'to_file'}) .
2716                                      "</td>\n";
2717                        }
2718
2719                        if ($action eq 'commitdiff') {
2720                                # link to patch
2721                                $patchno++;
2722                                print "<td class=\"link\">" .
2723                                      $cgi->a({-href => "#patch$patchno"}, "patch") .
2724                                      " | " .
2725                                      "</td>\n";
2726                        }
2727
2728                        my $has_history = 0;
2729                        my $not_deleted = 0;
2730                        for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
2731                                my $hash_parent = $parents[$i];
2732                                my $from_hash = $diff->{'from_id'}[$i];
2733                                my $from_path = $diff->{'from_file'}[$i];
2734                                my $status = $diff->{'status'}[$i];
2735
2736                                $has_history ||= ($status ne 'A');
2737                                $not_deleted ||= ($status ne 'D');
2738
2739                                if ($status eq 'A') {
2740                                        print "<td  class=\"link\" align=\"right\"> | </td>\n";
2741                                } elsif ($status eq 'D') {
2742                                        print "<td class=\"link\">" .
2743                                              $cgi->a({-href => href(action=>"blob",
2744                                                                     hash_base=>$hash,
2745                                                                     hash=>$from_hash,
2746                                                                     file_name=>$from_path)},
2747                                                      "blob" . ($i+1)) .
2748                                              " | </td>\n";
2749                                } else {
2750                                        if ($diff->{'to_id'} eq $from_hash) {
2751                                                print "<td class=\"link nochange\">";
2752                                        } else {
2753                                                print "<td class=\"link\">";
2754                                        }
2755                                        print $cgi->a({-href => href(action=>"blobdiff",
2756                                                                     hash=>$diff->{'to_id'},
2757                                                                     hash_parent=>$from_hash,
2758                                                                     hash_base=>$hash,
2759                                                                     hash_parent_base=>$hash_parent,
2760                                                                     file_name=>$diff->{'to_file'},
2761                                                                     file_parent=>$from_path)},
2762                                                      "diff" . ($i+1)) .
2763                                              " | </td>\n";
2764                                }
2765                        }
2766
2767                        print "<td class=\"link\">";
2768                        if ($not_deleted) {
2769                                print $cgi->a({-href => href(action=>"blob",
2770                                                             hash=>$diff->{'to_id'},
2771                                                             file_name=>$diff->{'to_file'},
2772                                                             hash_base=>$hash)},
2773                                              "blob");
2774                                print " | " if ($has_history);
2775                        }
2776                        if ($has_history) {
2777                                print $cgi->a({-href => href(action=>"history",
2778                                                             file_name=>$diff->{'to_file'},
2779                                                             hash_base=>$hash)},
2780                                              "history");
2781                        }
2782                        print "</td>\n";
2783
2784                        print "</tr>\n";
2785                        next; # instead of 'else' clause, to avoid extra indent
2786                }
2787                # else ordinary diff
2788
2789                my ($to_mode_oct, $to_mode_str, $to_file_type);
2790                my ($from_mode_oct, $from_mode_str, $from_file_type);
2791                if ($diff->{'to_mode'} ne ('0' x 6)) {
2792                        $to_mode_oct = oct $diff->{'to_mode'};
2793                        if (S_ISREG($to_mode_oct)) { # only for regular file
2794                                $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
2795                        }
2796                        $to_file_type = file_type($diff->{'to_mode'});
2797                }
2798                if ($diff->{'from_mode'} ne ('0' x 6)) {
2799                        $from_mode_oct = oct $diff->{'from_mode'};
2800                        if (S_ISREG($to_mode_oct)) { # only for regular file
2801                                $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
2802                        }
2803                        $from_file_type = file_type($diff->{'from_mode'});
2804                }
2805
2806                if ($diff->{'status'} eq "A") { # created
2807                        my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
2808                        $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
2809                        $mode_chng   .= "]</span>";
2810                        print "<td>";
2811                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2812                                                     hash_base=>$hash, file_name=>$diff->{'file'}),
2813                                      -class => "list"}, esc_path($diff->{'file'}));
2814                        print "</td>\n";
2815                        print "<td>$mode_chng</td>\n";
2816                        print "<td class=\"link\">";
2817                        if ($action eq 'commitdiff') {
2818                                # link to patch
2819                                $patchno++;
2820                                print $cgi->a({-href => "#patch$patchno"}, "patch");
2821                                print " | ";
2822                        }
2823                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2824                                                     hash_base=>$hash, file_name=>$diff->{'file'})},
2825                                      "blob");
2826                        print "</td>\n";
2827
2828                } elsif ($diff->{'status'} eq "D") { # deleted
2829                        my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
2830                        print "<td>";
2831                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
2832                                                     hash_base=>$parent, file_name=>$diff->{'file'}),
2833                                       -class => "list"}, esc_path($diff->{'file'}));
2834                        print "</td>\n";
2835                        print "<td>$mode_chng</td>\n";
2836                        print "<td class=\"link\">";
2837                        if ($action eq 'commitdiff') {
2838                                # link to patch
2839                                $patchno++;
2840                                print $cgi->a({-href => "#patch$patchno"}, "patch");
2841                                print " | ";
2842                        }
2843                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
2844                                                     hash_base=>$parent, file_name=>$diff->{'file'})},
2845                                      "blob") . " | ";
2846                        if ($have_blame) {
2847                                print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
2848                                                             file_name=>$diff->{'file'})},
2849                                              "blame") . " | ";
2850                        }
2851                        print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
2852                                                     file_name=>$diff->{'file'})},
2853                                      "history");
2854                        print "</td>\n";
2855
2856                } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
2857                        my $mode_chnge = "";
2858                        if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
2859                                $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
2860                                if ($from_file_type ne $to_file_type) {
2861                                        $mode_chnge .= " from $from_file_type to $to_file_type";
2862                                }
2863                                if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
2864                                        if ($from_mode_str && $to_mode_str) {
2865                                                $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
2866                                        } elsif ($to_mode_str) {
2867                                                $mode_chnge .= " mode: $to_mode_str";
2868                                        }
2869                                }
2870                                $mode_chnge .= "]</span>\n";
2871                        }
2872                        print "<td>";
2873                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2874                                                     hash_base=>$hash, file_name=>$diff->{'file'}),
2875                                      -class => "list"}, esc_path($diff->{'file'}));
2876                        print "</td>\n";
2877                        print "<td>$mode_chnge</td>\n";
2878                        print "<td class=\"link\">";
2879                        if ($action eq 'commitdiff') {
2880                                # link to patch
2881                                $patchno++;
2882                                print $cgi->a({-href => "#patch$patchno"}, "patch") .
2883                                      " | ";
2884                        } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
2885                                # "commit" view and modified file (not onlu mode changed)
2886                                print $cgi->a({-href => href(action=>"blobdiff",
2887                                                             hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
2888                                                             hash_base=>$hash, hash_parent_base=>$parent,
2889                                                             file_name=>$diff->{'file'})},
2890                                              "diff") .
2891                                      " | ";
2892                        }
2893                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2894                                                     hash_base=>$hash, file_name=>$diff->{'file'})},
2895                                       "blob") . " | ";
2896                        if ($have_blame) {
2897                                print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
2898                                                             file_name=>$diff->{'file'})},
2899                                              "blame") . " | ";
2900                        }
2901                        print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
2902                                                     file_name=>$diff->{'file'})},
2903                                      "history");
2904                        print "</td>\n";
2905
2906                } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
2907                        my %status_name = ('R' => 'moved', 'C' => 'copied');
2908                        my $nstatus = $status_name{$diff->{'status'}};
2909                        my $mode_chng = "";
2910                        if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
2911                                # mode also for directories, so we cannot use $to_mode_str
2912                                $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
2913                        }
2914                        print "<td>" .
2915                              $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2916                                                     hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
2917                                      -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
2918                              "<td><span class=\"file_status $nstatus\">[$nstatus from " .
2919                              $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
2920                                                     hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
2921                                      -class => "list"}, esc_path($diff->{'from_file'})) .
2922                              " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
2923                              "<td class=\"link\">";
2924                        if ($action eq 'commitdiff') {
2925                                # link to patch
2926                                $patchno++;
2927                                print $cgi->a({-href => "#patch$patchno"}, "patch") .
2928                                      " | ";
2929                        } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
2930                                # "commit" view and modified file (not only pure rename or copy)
2931                                print $cgi->a({-href => href(action=>"blobdiff",
2932                                                             hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
2933                                                             hash_base=>$hash, hash_parent_base=>$parent,
2934                                                             file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
2935                                              "diff") .
2936                                      " | ";
2937                        }
2938                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2939                                                     hash_base=>$parent, file_name=>$diff->{'to_file'})},
2940                                      "blob") . " | ";
2941                        if ($have_blame) {
2942                                print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
2943                                                             file_name=>$diff->{'to_file'})},
2944                                              "blame") . " | ";
2945                        }
2946                        print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
2947                                                    file_name=>$diff->{'to_file'})},
2948                                      "history");
2949                        print "</td>\n";
2950
2951                } # we should not encounter Unmerged (U) or Unknown (X) status
2952                print "</tr>\n";
2953        }
2954        print "</tbody>" if $has_header;
2955        print "</table>\n";
2956}
2957
2958sub git_patchset_body {
2959        my ($fd, $difftree, $hash, @hash_parents) = @_;
2960        my ($hash_parent) = $hash_parents[0];
2961
2962        my $patch_idx = 0;
2963        my $patch_number = 0;
2964        my $patch_line;
2965        my $diffinfo;
2966        my (%from, %to);
2967
2968        print "<div class=\"patchset\">\n";
2969
2970        # skip to first patch
2971        while ($patch_line = <$fd>) {
2972                chomp $patch_line;
2973
2974                last if ($patch_line =~ m/^diff /);
2975        }
2976
2977 PATCH:
2978        while ($patch_line) {
2979                my @diff_header;
2980                my ($from_id, $to_id);
2981
2982                # git diff header
2983                #assert($patch_line =~ m/^diff /) if DEBUG;
2984                #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
2985                $patch_number++;
2986                push @diff_header, $patch_line;
2987
2988                # extended diff header
2989        EXTENDED_HEADER:
2990                while ($patch_line = <$fd>) {
2991                        chomp $patch_line;
2992
2993                        last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
2994
2995                        if ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
2996                                $from_id = $1;
2997                                $to_id   = $2;
2998                        } elsif ($patch_line =~ m/^index ((?:[0-9a-fA-F]{40},)+[0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
2999                                $from_id = [ split(',', $1) ];
3000                                $to_id   = $2;
3001                        }
3002
3003                        push @diff_header, $patch_line;
3004                }
3005                my $last_patch_line = $patch_line;
3006
3007                # check if current patch belong to current raw line
3008                # and parse raw git-diff line if needed
3009                if (defined $diffinfo &&
3010                    defined $from_id && defined $to_id &&
3011                    from_ids_eq($diffinfo->{'from_id'}, $from_id) &&
3012                    $diffinfo->{'to_id'} eq $to_id) {
3013                        # this is continuation of a split patch
3014                        print "<div class=\"patch cont\">\n";
3015                } else {
3016                        # advance raw git-diff output if needed
3017                        $patch_idx++ if defined $diffinfo;
3018
3019                        # compact combined diff output can have some patches skipped
3020                        # find which patch (using pathname of result) we are at now
3021                        my $to_name;
3022                        if ($diff_header[0] =~ m!^diff --cc "?(.*)"?$!) {
3023                                $to_name = $1;
3024                        }
3025
3026                        do {
3027                                # read and prepare patch information
3028                                if (ref($difftree->[$patch_idx]) eq "HASH") {
3029                                        # pre-parsed (or generated by hand)
3030                                        $diffinfo = $difftree->[$patch_idx];
3031                                } else {
3032                                        $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
3033                                }
3034
3035                                # check if current raw line has no patch (it got simplified)
3036                                if (defined $to_name && $to_name ne $diffinfo->{'to_file'}) {
3037                                        print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3038                                              format_diff_cc_simplified($diffinfo, @hash_parents) .
3039                                              "</div>\n";  # class="patch"
3040
3041                                        $patch_idx++;
3042                                        $patch_number++;
3043                                }
3044                        } until (!defined $to_name || $to_name eq $diffinfo->{'to_file'} ||
3045                                 $patch_idx > $#$difftree);
3046                        # modifies %from, %to hashes
3047                        parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
3048                        if ($diffinfo->{'nparents'}) {
3049                                # combined diff
3050                                $from{'file'} = [];
3051                                $from{'href'} = [];
3052                                fill_from_file_info($diffinfo, @hash_parents)
3053                                        unless exists $diffinfo->{'from_file'};
3054                                for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3055                                        $from{'file'}[$i] = $diffinfo->{'from_file'}[$i] || $diffinfo->{'to_file'};
3056                                        if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3057                                                $from{'href'}[$i] = href(action=>"blob",
3058                                                                         hash_base=>$hash_parents[$i],
3059                                                                         hash=>$diffinfo->{'from_id'}[$i],
3060                                                                         file_name=>$from{'file'}[$i]);
3061                                        } else {
3062                                                $from{'href'}[$i] = undef;
3063                                        }
3064                                }
3065                        } else {
3066                                $from{'file'} = $diffinfo->{'from_file'} || $diffinfo->{'file'};
3067                                if ($diffinfo->{'status'} ne "A") { # not new (added) file
3068                                        $from{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3069                                                             hash=>$diffinfo->{'from_id'},
3070                                                             file_name=>$from{'file'});
3071                                } else {
3072                                        delete $from{'href'};
3073                                }
3074                        }
3075
3076                        $to{'file'} = $diffinfo->{'to_file'} || $diffinfo->{'file'};
3077                        if (!is_deleted($diffinfo)) { # file exists in result
3078                                $to{'href'} = href(action=>"blob", hash_base=>$hash,
3079                                                   hash=>$diffinfo->{'to_id'},
3080                                                   file_name=>$to{'file'});
3081                        } else {
3082                                delete $to{'href'};
3083                        }
3084                        # this is first patch for raw difftree line with $patch_idx index
3085                        # we index @$difftree array from 0, but number patches from 1
3086                        print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
3087                }
3088
3089                # print "git diff" header
3090                $patch_line = shift @diff_header;
3091                print format_git_diff_header_line($patch_line, $diffinfo,
3092                                                  \%from, \%to);
3093
3094                # print extended diff header
3095                print "<div class=\"diff extended_header\">\n" if (@diff_header > 0);
3096        EXTENDED_HEADER:
3097                foreach $patch_line (@diff_header) {
3098                        print format_extended_diff_header_line($patch_line, $diffinfo,
3099                                                               \%from, \%to);
3100                }
3101                print "</div>\n"  if (@diff_header > 0); # class="diff extended_header"
3102
3103                # from-file/to-file diff header
3104                $patch_line = $last_patch_line;
3105                if (! $patch_line) {
3106                        print "</div>\n"; # class="patch"
3107                        last PATCH;
3108                }
3109                next PATCH if ($patch_line =~ m/^diff /);
3110                #assert($patch_line =~ m/^---/) if DEBUG;
3111                #assert($patch_line eq $last_patch_line) if DEBUG;
3112
3113                $patch_line = <$fd>;
3114                chomp $patch_line;
3115                #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
3116
3117                print format_diff_from_to_header($last_patch_line, $patch_line,
3118                                                 $diffinfo, \%from, \%to,
3119                                                 @hash_parents);
3120
3121                # the patch itself
3122        LINE:
3123                while ($patch_line = <$fd>) {
3124                        chomp $patch_line;
3125
3126                        next PATCH if ($patch_line =~ m/^diff /);
3127
3128                        print format_diff_line($patch_line, \%from, \%to);
3129                }
3130
3131        } continue {
3132                print "</div>\n"; # class="patch"
3133        }
3134
3135        # for compact combined (--cc) format, with chunk and patch simpliciaction
3136        # patchset might be empty, but there might be unprocessed raw lines
3137        for ($patch_idx++ if $patch_number > 0;
3138             $patch_idx < @$difftree;
3139             $patch_idx++) {
3140                # read and prepare patch information
3141                if (ref($difftree->[$patch_idx]) eq "HASH") {
3142                        # pre-parsed (or generated by hand)
3143                        $diffinfo = $difftree->[$patch_idx];
3144                } else {
3145                        $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
3146                }
3147
3148                # generate anchor for "patch" links in difftree / whatchanged part
3149                print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3150                      format_diff_cc_simplified($diffinfo, @hash_parents) .
3151                      "</div>\n";  # class="patch"
3152
3153                $patch_number++;
3154        }
3155
3156        if ($patch_number == 0) {
3157                if (@hash_parents > 1) {
3158                        print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
3159                } else {
3160                        print "<div class=\"diff nodifferences\">No differences found</div>\n";
3161                }
3162        }
3163
3164        print "</div>\n"; # class="patchset"
3165}
3166
3167# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3168
3169sub git_project_list_body {
3170        my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
3171
3172        my ($check_forks) = gitweb_check_feature('forks');
3173
3174        my @projects;
3175        foreach my $pr (@$projlist) {
3176                my (@aa) = git_get_last_activity($pr->{'path'});
3177                unless (@aa) {
3178                        next;
3179                }
3180                ($pr->{'age'}, $pr->{'age_string'}) = @aa;
3181                if (!defined $pr->{'descr'}) {
3182                        my $descr = git_get_project_description($pr->{'path'}) || "";
3183                        $pr->{'descr_long'} = to_utf8($descr);
3184                        $pr->{'descr'} = chop_str($descr, 25, 5);
3185                }
3186                if (!defined $pr->{'owner'}) {
3187                        $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
3188                }
3189                if ($check_forks) {
3190                        my $pname = $pr->{'path'};
3191                        if (($pname =~ s/\.git$//) &&
3192                            ($pname !~ /\/$/) &&
3193                            (-d "$projectroot/$pname")) {
3194                                $pr->{'forks'} = "-d $projectroot/$pname";
3195                        }
3196                        else {
3197                                $pr->{'forks'} = 0;
3198                        }
3199                }
3200                push @projects, $pr;
3201        }
3202
3203        $order ||= $default_projects_order;
3204        $from = 0 unless defined $from;
3205        $to = $#projects if (!defined $to || $#projects < $to);
3206
3207        print "<table class=\"project_list\">\n";
3208        unless ($no_header) {
3209                print "<tr>\n";
3210                if ($check_forks) {
3211                        print "<th></th>\n";
3212                }
3213                if ($order eq "project") {
3214                        @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
3215                        print "<th>Project</th>\n";
3216                } else {
3217                        print "<th>" .
3218                              $cgi->a({-href => href(project=>undef, order=>'project'),
3219                                       -class => "header"}, "Project") .
3220                              "</th>\n";
3221                }
3222                if ($order eq "descr") {
3223                        @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
3224                        print "<th>Description</th>\n";
3225                } else {
3226                        print "<th>" .
3227                              $cgi->a({-href => href(project=>undef, order=>'descr'),
3228                                       -class => "header"}, "Description") .
3229                              "</th>\n";
3230                }
3231                if ($order eq "owner") {
3232                        @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
3233                        print "<th>Owner</th>\n";
3234                } else {
3235                        print "<th>" .
3236                              $cgi->a({-href => href(project=>undef, order=>'owner'),
3237                                       -class => "header"}, "Owner") .
3238                              "</th>\n";
3239                }
3240                if ($order eq "age") {
3241                        @projects = sort {$a->{'age'} <=> $b->{'age'}} @projects;
3242                        print "<th>Last Change</th>\n";
3243                } else {
3244                        print "<th>" .
3245                              $cgi->a({-href => href(project=>undef, order=>'age'),
3246                                       -class => "header"}, "Last Change") .
3247                              "</th>\n";
3248                }
3249                print "<th></th>\n" .
3250                      "</tr>\n";
3251        }
3252        my $alternate = 1;
3253        for (my $i = $from; $i <= $to; $i++) {
3254                my $pr = $projects[$i];
3255                if ($alternate) {
3256                        print "<tr class=\"dark\">\n";
3257                } else {
3258                        print "<tr class=\"light\">\n";
3259                }
3260                $alternate ^= 1;
3261                if ($check_forks) {
3262                        print "<td>";
3263                        if ($pr->{'forks'}) {
3264                                print "<!-- $pr->{'forks'} -->\n";
3265                                print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
3266                        }
3267                        print "</td>\n";
3268                }
3269                print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3270                                        -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
3271                      "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3272                                        -class => "list", -title => $pr->{'descr_long'}},
3273                                        esc_html($pr->{'descr'})) . "</td>\n" .
3274                      "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
3275                print "<td class=\"". age_class($pr->{'age'}) . "\">" .
3276                      (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
3277                      "<td class=\"link\">" .
3278                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
3279                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
3280                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
3281                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
3282                      ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
3283                      "</td>\n" .
3284                      "</tr>\n";
3285        }
3286        if (defined $extra) {
3287                print "<tr>\n";
3288                if ($check_forks) {
3289                        print "<td></td>\n";
3290                }
3291                print "<td colspan=\"5\">$extra</td>\n" .
3292                      "</tr>\n";
3293        }
3294        print "</table>\n";
3295}
3296
3297sub git_shortlog_body {
3298        # uses global variable $project
3299        my ($commitlist, $from, $to, $refs, $extra) = @_;
3300
3301        my $have_snapshot = gitweb_have_snapshot();
3302
3303        $from = 0 unless defined $from;
3304        $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3305
3306        print "<table class=\"shortlog\" cellspacing=\"0\">\n";
3307        my $alternate = 1;
3308        for (my $i = $from; $i <= $to; $i++) {
3309                my %co = %{$commitlist->[$i]};
3310                my $commit = $co{'id'};
3311                my $ref = format_ref_marker($refs, $commit);
3312                if ($alternate) {
3313                        print "<tr class=\"dark\">\n";
3314                } else {
3315                        print "<tr class=\"light\">\n";
3316                }
3317                $alternate ^= 1;
3318                # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
3319                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3320                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
3321                      "<td>";
3322                print format_subject_html($co{'title'}, $co{'title_short'},
3323                                          href(action=>"commit", hash=>$commit), $ref);
3324                print "</td>\n" .
3325                      "<td class=\"link\">" .
3326                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
3327                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
3328                      $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
3329                if ($have_snapshot) {
3330                        print " | " . $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
3331                }
3332                print "</td>\n" .
3333                      "</tr>\n";
3334        }
3335        if (defined $extra) {
3336                print "<tr>\n" .
3337                      "<td colspan=\"4\">$extra</td>\n" .
3338                      "</tr>\n";
3339        }
3340        print "</table>\n";
3341}
3342
3343sub git_history_body {
3344        # Warning: assumes constant type (blob or tree) during history
3345        my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
3346
3347        $from = 0 unless defined $from;
3348        $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
3349
3350        print "<table class=\"history\" cellspacing=\"0\">\n";
3351        my $alternate = 1;
3352        for (my $i = $from; $i <= $to; $i++) {
3353                my %co = %{$commitlist->[$i]};
3354                if (!%co) {
3355                        next;
3356                }
3357                my $commit = $co{'id'};
3358
3359                my $ref = format_ref_marker($refs, $commit);
3360
3361                if ($alternate) {
3362                        print "<tr class=\"dark\">\n";
3363                } else {
3364                        print "<tr class=\"light\">\n";
3365                }
3366                $alternate ^= 1;
3367                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3368                      # shortlog uses      chop_str($co{'author_name'}, 10)
3369                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
3370                      "<td>";
3371                # originally git_history used chop_str($co{'title'}, 50)
3372                print format_subject_html($co{'title'}, $co{'title_short'},
3373                                          href(action=>"commit", hash=>$commit), $ref);
3374                print "</td>\n" .
3375                      "<td class=\"link\">" .
3376                      $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
3377                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
3378
3379                if ($ftype eq 'blob') {
3380                        my $blob_current = git_get_hash_by_path($hash_base, $file_name);
3381                        my $blob_parent  = git_get_hash_by_path($commit, $file_name);
3382                        if (defined $blob_current && defined $blob_parent &&
3383                                        $blob_current ne $blob_parent) {
3384                                print " | " .
3385                                        $cgi->a({-href => href(action=>"blobdiff",
3386                                                               hash=>$blob_current, hash_parent=>$blob_parent,
3387                                                               hash_base=>$hash_base, hash_parent_base=>$commit,
3388                                                               file_name=>$file_name)},
3389                                                "diff to current");
3390                        }
3391                }
3392                print "</td>\n" .
3393                      "</tr>\n";
3394        }
3395        if (defined $extra) {
3396                print "<tr>\n" .
3397                      "<td colspan=\"4\">$extra</td>\n" .
3398                      "</tr>\n";
3399        }
3400        print "</table>\n";
3401}
3402
3403sub git_tags_body {
3404        # uses global variable $project
3405        my ($taglist, $from, $to, $extra) = @_;
3406        $from = 0 unless defined $from;
3407        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
3408
3409        print "<table class=\"tags\" cellspacing=\"0\">\n";
3410        my $alternate = 1;
3411        for (my $i = $from; $i <= $to; $i++) {
3412                my $entry = $taglist->[$i];
3413                my %tag = %$entry;
3414                my $comment = $tag{'subject'};
3415                my $comment_short;
3416                if (defined $comment) {
3417                        $comment_short = chop_str($comment, 30, 5);
3418                }
3419                if ($alternate) {
3420                        print "<tr class=\"dark\">\n";
3421                } else {
3422                        print "<tr class=\"light\">\n";
3423                }
3424                $alternate ^= 1;
3425                if (defined $tag{'age'}) {
3426                        print "<td><i>$tag{'age'}</i></td>\n";
3427                } else {
3428                        print "<td></td>\n";
3429                }
3430                print "<td>" .
3431                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
3432                               -class => "list name"}, esc_html($tag{'name'})) .
3433                      "</td>\n" .
3434                      "<td>";
3435                if (defined $comment) {
3436                        print format_subject_html($comment, $comment_short,
3437                                                  href(action=>"tag", hash=>$tag{'id'}));
3438                }
3439                print "</td>\n" .
3440                      "<td class=\"selflink\">";
3441                if ($tag{'type'} eq "tag") {
3442                        print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
3443                } else {
3444                        print "&nbsp;";
3445                }
3446                print "</td>\n" .
3447                      "<td class=\"link\">" . " | " .
3448                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
3449                if ($tag{'reftype'} eq "commit") {
3450                        print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
3451                              " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log");
3452                } elsif ($tag{'reftype'} eq "blob") {
3453                        print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
3454                }
3455                print "</td>\n" .
3456                      "</tr>";
3457        }
3458        if (defined $extra) {
3459                print "<tr>\n" .
3460                      "<td colspan=\"5\">$extra</td>\n" .
3461                      "</tr>\n";
3462        }
3463        print "</table>\n";
3464}
3465
3466sub git_heads_body {
3467        # uses global variable $project
3468        my ($headlist, $head, $from, $to, $extra) = @_;
3469        $from = 0 unless defined $from;
3470        $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
3471
3472        print "<table class=\"heads\" cellspacing=\"0\">\n";
3473        my $alternate = 1;
3474        for (my $i = $from; $i <= $to; $i++) {
3475                my $entry = $headlist->[$i];
3476                my %ref = %$entry;
3477                my $curr = $ref{'id'} eq $head;
3478                if ($alternate) {
3479                        print "<tr class=\"dark\">\n";
3480                } else {
3481                        print "<tr class=\"light\">\n";
3482                }
3483                $alternate ^= 1;
3484                print "<td><i>$ref{'age'}</i></td>\n" .
3485                      ($curr ? "<td class=\"current_head\">" : "<td>") .
3486                      $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'}),
3487                               -class => "list name"},esc_html($ref{'name'})) .
3488                      "</td>\n" .
3489                      "<td class=\"link\">" .
3490                      $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'})}, "shortlog") . " | " .
3491                      $cgi->a({-href => href(action=>"log", hash=>$ref{'name'})}, "log") . " | " .
3492                      $cgi->a({-href => href(action=>"tree", hash=>$ref{'name'}, hash_base=>$ref{'name'})}, "tree") .
3493                      "</td>\n" .
3494                      "</tr>";
3495        }
3496        if (defined $extra) {
3497                print "<tr>\n" .
3498                      "<td colspan=\"3\">$extra</td>\n" .
3499                      "</tr>\n";
3500        }
3501        print "</table>\n";
3502}
3503
3504sub git_search_grep_body {
3505        my ($commitlist, $from, $to, $extra) = @_;
3506        $from = 0 unless defined $from;
3507        $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3508
3509        print "<table class=\"grep\" cellspacing=\"0\">\n";
3510        my $alternate = 1;
3511        for (my $i = $from; $i <= $to; $i++) {
3512                my %co = %{$commitlist->[$i]};
3513                if (!%co) {
3514                        next;
3515                }
3516                my $commit = $co{'id'};
3517                if ($alternate) {
3518                        print "<tr class=\"dark\">\n";
3519                } else {
3520                        print "<tr class=\"light\">\n";
3521                }
3522                $alternate ^= 1;
3523                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3524                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3525                      "<td>" .
3526                      $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3527                               esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3528                my $comment = $co{'comment'};
3529                foreach my $line (@$comment) {
3530                        if ($line =~ m/^(.*)($search_regexp)(.*)$/i) {
3531                                my $lead = esc_html($1) || "";
3532                                $lead = chop_str($lead, 30, 10);
3533                                my $match = esc_html($2) || "";
3534                                my $trail = esc_html($3) || "";
3535                                $trail = chop_str($trail, 30, 10);
3536                                my $text = "$lead<span class=\"match\">$match</span>$trail";
3537                                print chop_str($text, 80, 5) . "<br/>\n";
3538                        }
3539                }
3540                print "</td>\n" .
3541                      "<td class=\"link\">" .
3542                      $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3543                      " | " .
3544                      $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3545                print "</td>\n" .
3546                      "</tr>\n";
3547        }
3548        if (defined $extra) {
3549                print "<tr>\n" .
3550                      "<td colspan=\"3\">$extra</td>\n" .
3551                      "</tr>\n";
3552        }
3553        print "</table>\n";
3554}
3555
3556## ======================================================================
3557## ======================================================================
3558## actions
3559
3560sub git_project_list {
3561        my $order = $cgi->param('o');
3562        if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3563                die_error(undef, "Unknown order parameter");
3564        }
3565
3566        my @list = git_get_projects_list();
3567        if (!@list) {
3568                die_error(undef, "No projects found");
3569        }
3570
3571        git_header_html();
3572        if (-f $home_text) {
3573                print "<div class=\"index_include\">\n";
3574                open (my $fd, $home_text);
3575                print <$fd>;
3576                close $fd;
3577                print "</div>\n";
3578        }
3579        git_project_list_body(\@list, $order);
3580        git_footer_html();
3581}
3582
3583sub git_forks {
3584        my $order = $cgi->param('o');
3585        if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3586                die_error(undef, "Unknown order parameter");
3587        }
3588
3589        my @list = git_get_projects_list($project);
3590        if (!@list) {
3591                die_error(undef, "No forks found");
3592        }
3593
3594        git_header_html();
3595        git_print_page_nav('','');
3596        git_print_header_div('summary', "$project forks");
3597        git_project_list_body(\@list, $order);
3598        git_footer_html();
3599}
3600
3601sub git_project_index {
3602        my @projects = git_get_projects_list($project);
3603
3604        print $cgi->header(
3605                -type => 'text/plain',
3606                -charset => 'utf-8',
3607                -content_disposition => 'inline; filename="index.aux"');
3608
3609        foreach my $pr (@projects) {
3610                if (!exists $pr->{'owner'}) {
3611                        $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
3612                }
3613
3614                my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
3615                # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
3616                $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3617                $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3618                $path  =~ s/ /\+/g;
3619                $owner =~ s/ /\+/g;
3620
3621                print "$path $owner\n";
3622        }
3623}
3624
3625sub git_summary {
3626        my $descr = git_get_project_description($project) || "none";
3627        my %co = parse_commit("HEAD");
3628        my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
3629        my $head = $co{'id'};
3630
3631        my $owner = git_get_project_owner($project);
3632
3633        my $refs = git_get_references();
3634        # These get_*_list functions return one more to allow us to see if
3635        # there are more ...
3636        my @taglist  = git_get_tags_list(16);
3637        my @headlist = git_get_heads_list(16);
3638        my @forklist;
3639        my ($check_forks) = gitweb_check_feature('forks');
3640
3641        if ($check_forks) {
3642                @forklist = git_get_projects_list($project);
3643        }
3644
3645        git_header_html();
3646        git_print_page_nav('summary','', $head);
3647
3648        print "<div class=\"title\">&nbsp;</div>\n";
3649        print "<table cellspacing=\"0\">\n" .
3650              "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
3651              "<tr><td>owner</td><td>$owner</td></tr>\n";
3652        if (defined $cd{'rfc2822'}) {
3653                print "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
3654        }
3655
3656        # use per project git URL list in $projectroot/$project/cloneurl
3657        # or make project git URL from git base URL and project name
3658        my $url_tag = "URL";
3659        my @url_list = git_get_project_url_list($project);
3660        @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
3661        foreach my $git_url (@url_list) {
3662                next unless $git_url;
3663                print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
3664                $url_tag = "";
3665        }
3666        print "</table>\n";
3667
3668        if (-s "$projectroot/$project/README.html") {
3669                if (open my $fd, "$projectroot/$project/README.html") {
3670                        print "<div class=\"title\">readme</div>\n";
3671                        print $_ while (<$fd>);
3672                        close $fd;
3673                }
3674        }
3675
3676        # we need to request one more than 16 (0..15) to check if
3677        # those 16 are all
3678        my @commitlist = $head ? parse_commits($head, 17) : ();
3679        if (@commitlist) {
3680                git_print_header_div('shortlog');
3681                git_shortlog_body(\@commitlist, 0, 15, $refs,
3682                                  $#commitlist <=  15 ? undef :
3683                                  $cgi->a({-href => href(action=>"shortlog")}, "..."));
3684        }
3685
3686        if (@taglist) {
3687                git_print_header_div('tags');
3688                git_tags_body(\@taglist, 0, 15,
3689                              $#taglist <=  15 ? undef :
3690                              $cgi->a({-href => href(action=>"tags")}, "..."));
3691        }
3692
3693        if (@headlist) {
3694                git_print_header_div('heads');
3695                git_heads_body(\@headlist, $head, 0, 15,
3696                               $#headlist <= 15 ? undef :
3697                               $cgi->a({-href => href(action=>"heads")}, "..."));
3698        }
3699
3700        if (@forklist) {
3701                git_print_header_div('forks');
3702                git_project_list_body(\@forklist, undef, 0, 15,
3703                                      $#forklist <= 15 ? undef :
3704                                      $cgi->a({-href => href(action=>"forks")}, "..."),
3705                                      'noheader');
3706        }
3707
3708        git_footer_html();
3709}
3710
3711sub git_tag {
3712        my $head = git_get_head_hash($project);
3713        git_header_html();
3714        git_print_page_nav('','', $head,undef,$head);
3715        my %tag = parse_tag($hash);
3716
3717        if (! %tag) {
3718                die_error(undef, "Unknown tag object");
3719        }
3720
3721        git_print_header_div('commit', esc_html($tag{'name'}), $hash);
3722        print "<div class=\"title_text\">\n" .
3723              "<table cellspacing=\"0\">\n" .
3724              "<tr>\n" .
3725              "<td>object</td>\n" .
3726              "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3727                               $tag{'object'}) . "</td>\n" .
3728              "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3729                                              $tag{'type'}) . "</td>\n" .
3730              "</tr>\n";
3731        if (defined($tag{'author'})) {
3732                my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
3733                print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
3734                print "<tr><td></td><td>" . $ad{'rfc2822'} .
3735                        sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
3736                        "</td></tr>\n";
3737        }
3738        print "</table>\n\n" .
3739              "</div>\n";
3740        print "<div class=\"page_body\">";
3741        my $comment = $tag{'comment'};
3742        foreach my $line (@$comment) {
3743                chomp $line;
3744                print esc_html($line, -nbsp=>1) . "<br/>\n";
3745        }
3746        print "</div>\n";
3747        git_footer_html();
3748}
3749
3750sub git_blame2 {
3751        my $fd;
3752        my $ftype;
3753
3754        my ($have_blame) = gitweb_check_feature('blame');
3755        if (!$have_blame) {
3756                die_error('403 Permission denied', "Permission denied");
3757        }
3758        die_error('404 Not Found', "File name not defined") if (!$file_name);
3759        $hash_base ||= git_get_head_hash($project);
3760        die_error(undef, "Couldn't find base commit") unless ($hash_base);
3761        my %co = parse_commit($hash_base)
3762                or die_error(undef, "Reading commit failed");
3763        if (!defined $hash) {
3764                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3765                        or die_error(undef, "Error looking up file");
3766        }
3767        $ftype = git_get_type($hash);
3768        if ($ftype !~ "blob") {
3769                die_error('400 Bad Request', "Object is not a blob");
3770        }
3771        open ($fd, "-|", git_cmd(), "blame", '-p', '--',
3772              $file_name, $hash_base)
3773                or die_error(undef, "Open git-blame failed");
3774        git_header_html();
3775        my $formats_nav =
3776                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3777                        "blob") .
3778                " | " .
3779                $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3780                        "history") .
3781                " | " .
3782                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3783                        "HEAD");
3784        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3785        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3786        git_print_page_path($file_name, $ftype, $hash_base);
3787        my @rev_color = (qw(light2 dark2));
3788        my $num_colors = scalar(@rev_color);
3789        my $current_color = 0;
3790        my $last_rev;
3791        print <<HTML;
3792<div class="page_body">
3793<table class="blame">
3794<tr><th>Commit</th><th>Line</th><th>Data</th></tr>
3795HTML
3796        my %metainfo = ();
3797        while (1) {
3798                $_ = <$fd>;
3799                last unless defined $_;
3800                my ($full_rev, $orig_lineno, $lineno, $group_size) =
3801                    /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
3802                if (!exists $metainfo{$full_rev}) {
3803                        $metainfo{$full_rev} = {};
3804                }
3805                my $meta = $metainfo{$full_rev};
3806                while (<$fd>) {
3807                        last if (s/^\t//);
3808                        if (/^(\S+) (.*)$/) {
3809                                $meta->{$1} = $2;
3810                        }
3811                }
3812                my $data = $_;
3813                chomp $data;
3814                my $rev = substr($full_rev, 0, 8);
3815                my $author = $meta->{'author'};
3816                my %date = parse_date($meta->{'author-time'},
3817                                      $meta->{'author-tz'});
3818                my $date = $date{'iso-tz'};
3819                if ($group_size) {
3820                        $current_color = ++$current_color % $num_colors;
3821                }
3822                print "<tr class=\"$rev_color[$current_color]\">\n";
3823                if ($group_size) {
3824                        print "<td class=\"sha1\"";
3825                        print " title=\"". esc_html($author) . ", $date\"";
3826                        print " rowspan=\"$group_size\"" if ($group_size > 1);
3827                        print ">";
3828                        print $cgi->a({-href => href(action=>"commit",
3829                                                     hash=>$full_rev,
3830                                                     file_name=>$file_name)},
3831                                      esc_html($rev));
3832                        print "</td>\n";
3833                }
3834                open (my $dd, "-|", git_cmd(), "rev-parse", "$full_rev^")
3835                        or die_error(undef, "Open git-rev-parse failed");
3836                my $parent_commit = <$dd>;
3837                close $dd;
3838                chomp($parent_commit);
3839                my $blamed = href(action => 'blame',
3840                                  file_name => $meta->{'filename'},
3841                                  hash_base => $parent_commit);
3842                print "<td class=\"linenr\">";
3843                print $cgi->a({ -href => "$blamed#l$orig_lineno",
3844                                -id => "l$lineno",
3845                                -class => "linenr" },
3846                              esc_html($lineno));
3847                print "</td>";
3848                print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
3849                print "</tr>\n";
3850        }
3851        print "</table>\n";
3852        print "</div>";
3853        close $fd
3854                or print "Reading blob failed\n";
3855        git_footer_html();
3856}
3857
3858sub git_blame {
3859        my $fd;
3860
3861        my ($have_blame) = gitweb_check_feature('blame');
3862        if (!$have_blame) {
3863                die_error('403 Permission denied', "Permission denied");
3864        }
3865        die_error('404 Not Found', "File name not defined") if (!$file_name);
3866        $hash_base ||= git_get_head_hash($project);
3867        die_error(undef, "Couldn't find base commit") unless ($hash_base);
3868        my %co = parse_commit($hash_base)
3869                or die_error(undef, "Reading commit failed");
3870        if (!defined $hash) {
3871                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3872                        or die_error(undef, "Error lookup file");
3873        }
3874        open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
3875                or die_error(undef, "Open git-annotate failed");
3876        git_header_html();
3877        my $formats_nav =
3878                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3879                        "blob") .
3880                " | " .
3881                $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3882                        "history") .
3883                " | " .
3884                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3885                        "HEAD");
3886        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3887        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3888        git_print_page_path($file_name, 'blob', $hash_base);
3889        print "<div class=\"page_body\">\n";
3890        print <<HTML;
3891<table class="blame">
3892  <tr>
3893    <th>Commit</th>
3894    <th>Age</th>
3895    <th>Author</th>
3896    <th>Line</th>
3897    <th>Data</th>
3898  </tr>
3899HTML
3900        my @line_class = (qw(light dark));
3901        my $line_class_len = scalar (@line_class);
3902        my $line_class_num = $#line_class;
3903        while (my $line = <$fd>) {
3904                my $long_rev;
3905                my $short_rev;
3906                my $author;
3907                my $time;
3908                my $lineno;
3909                my $data;
3910                my $age;
3911                my $age_str;
3912                my $age_class;
3913
3914                chomp $line;
3915                $line_class_num = ($line_class_num + 1) % $line_class_len;
3916
3917                if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
3918                        $long_rev = $1;
3919                        $author   = $2;
3920                        $time     = $3;
3921                        $lineno   = $4;
3922                        $data     = $5;
3923                } else {
3924                        print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
3925                        next;
3926                }
3927                $short_rev  = substr ($long_rev, 0, 8);
3928                $age        = time () - $time;
3929                $age_str    = age_string ($age);
3930                $age_str    =~ s/ /&nbsp;/g;
3931                $age_class  = age_class($age);
3932                $author     = esc_html ($author);
3933                $author     =~ s/ /&nbsp;/g;
3934
3935                $data = untabify($data);
3936                $data = esc_html ($data);
3937
3938                print <<HTML;
3939  <tr class="$line_class[$line_class_num]">
3940    <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
3941    <td class="$age_class">$age_str</td>
3942    <td>$author</td>
3943    <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
3944    <td class="pre">$data</td>
3945  </tr>
3946HTML
3947        } # while (my $line = <$fd>)
3948        print "</table>\n\n";
3949        close $fd
3950                or print "Reading blob failed.\n";
3951        print "</div>";
3952        git_footer_html();
3953}
3954
3955sub git_tags {
3956        my $head = git_get_head_hash($project);
3957        git_header_html();
3958        git_print_page_nav('','', $head,undef,$head);
3959        git_print_header_div('summary', $project);
3960
3961        my @tagslist = git_get_tags_list();
3962        if (@tagslist) {
3963                git_tags_body(\@tagslist);
3964        }
3965        git_footer_html();
3966}
3967
3968sub git_heads {
3969        my $head = git_get_head_hash($project);
3970        git_header_html();
3971        git_print_page_nav('','', $head,undef,$head);
3972        git_print_header_div('summary', $project);
3973
3974        my @headslist = git_get_heads_list();
3975        if (@headslist) {
3976                git_heads_body(\@headslist, $head);
3977        }
3978        git_footer_html();
3979}
3980
3981sub git_blob_plain {
3982        my $expires;
3983
3984        if (!defined $hash) {
3985                if (defined $file_name) {
3986                        my $base = $hash_base || git_get_head_hash($project);
3987                        $hash = git_get_hash_by_path($base, $file_name, "blob")
3988                                or die_error(undef, "Error lookup file");
3989                } else {
3990                        die_error(undef, "No file name defined");
3991                }
3992        } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3993                # blobs defined by non-textual hash id's can be cached
3994                $expires = "+1d";
3995        }
3996
3997        my $type = shift;
3998        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3999                or die_error(undef, "Couldn't cat $file_name, $hash");
4000
4001        $type ||= blob_mimetype($fd, $file_name);
4002
4003        # save as filename, even when no $file_name is given
4004        my $save_as = "$hash";
4005        if (defined $file_name) {
4006                $save_as = $file_name;
4007        } elsif ($type =~ m/^text\//) {
4008                $save_as .= '.txt';
4009        }
4010
4011        print $cgi->header(
4012                -type => "$type",
4013                -expires=>$expires,
4014                -content_disposition => 'inline; filename="' . "$save_as" . '"');
4015        undef $/;
4016        binmode STDOUT, ':raw';
4017        print <$fd>;
4018        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4019        $/ = "\n";
4020        close $fd;
4021}
4022
4023sub git_blob {
4024        my $expires;
4025
4026        if (!defined $hash) {
4027                if (defined $file_name) {
4028                        my $base = $hash_base || git_get_head_hash($project);
4029                        $hash = git_get_hash_by_path($base, $file_name, "blob")
4030                                or die_error(undef, "Error lookup file");
4031                } else {
4032                        die_error(undef, "No file name defined");
4033                }
4034        } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4035                # blobs defined by non-textual hash id's can be cached
4036                $expires = "+1d";
4037        }
4038
4039        my ($have_blame) = gitweb_check_feature('blame');
4040        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4041                or die_error(undef, "Couldn't cat $file_name, $hash");
4042        my $mimetype = blob_mimetype($fd, $file_name);
4043        if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)!) {
4044                close $fd;
4045                return git_blob_plain($mimetype);
4046        }
4047        # we can have blame only for text/* mimetype
4048        $have_blame &&= ($mimetype =~ m!^text/!);
4049
4050        git_header_html(undef, $expires);
4051        my $formats_nav = '';
4052        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4053                if (defined $file_name) {
4054                        if ($have_blame) {
4055                                $formats_nav .=
4056                                        $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
4057                                                               hash=>$hash, file_name=>$file_name)},
4058                                                "blame") .
4059                                        " | ";
4060                        }
4061                        $formats_nav .=
4062                                $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4063                                                       hash=>$hash, file_name=>$file_name)},
4064                                        "history") .
4065                                " | " .
4066                                $cgi->a({-href => href(action=>"blob_plain",
4067                                                       hash=>$hash, file_name=>$file_name)},
4068                                        "raw") .
4069                                " | " .
4070                                $cgi->a({-href => href(action=>"blob",
4071                                                       hash_base=>"HEAD", file_name=>$file_name)},
4072                                        "HEAD");
4073                } else {
4074                        $formats_nav .=
4075                                $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
4076                }
4077                git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4078                git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4079        } else {
4080                print "<div class=\"page_nav\">\n" .
4081                      "<br/><br/></div>\n" .
4082                      "<div class=\"title\">$hash</div>\n";
4083        }
4084        git_print_page_path($file_name, "blob", $hash_base);
4085        print "<div class=\"page_body\">\n";
4086        if ($mimetype =~ m!^text/!) {
4087                my $nr;
4088                while (my $line = <$fd>) {
4089                        chomp $line;
4090                        $nr++;
4091                        $line = untabify($line);
4092                        printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
4093                               $nr, $nr, $nr, esc_html($line, -nbsp=>1);
4094                }
4095        } elsif ($mimetype =~ m!^image/!) {
4096                print qq!<img type="$mimetype"!;
4097                if ($file_name) {
4098                        print qq! alt="$file_name" title="$file_name"!;
4099                }
4100                print qq! src="! .
4101                      href(action=>"blob_plain", hash=>$hash,
4102                           hash_base=>$hash_base, file_name=>$file_name) .
4103                      qq!" />\n!;
4104        }
4105        close $fd
4106                or print "Reading blob failed.\n";
4107        print "</div>";
4108        git_footer_html();
4109}
4110
4111sub git_tree {
4112        my $have_snapshot = gitweb_have_snapshot();
4113
4114        if (!defined $hash_base) {
4115                $hash_base = "HEAD";
4116        }
4117        if (!defined $hash) {
4118                if (defined $file_name) {
4119                        $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
4120                } else {
4121                        $hash = $hash_base;
4122                }
4123        }
4124        $/ = "\0";
4125        open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
4126                or die_error(undef, "Open git-ls-tree failed");
4127        my @entries = map { chomp; $_ } <$fd>;
4128        close $fd or die_error(undef, "Reading tree failed");
4129        $/ = "\n";
4130
4131        my $refs = git_get_references();
4132        my $ref = format_ref_marker($refs, $hash_base);
4133        git_header_html();
4134        my $basedir = '';
4135        my ($have_blame) = gitweb_check_feature('blame');
4136        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4137                my @views_nav = ();
4138                if (defined $file_name) {
4139                        push @views_nav,
4140                                $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4141                                                       hash=>$hash, file_name=>$file_name)},
4142                                        "history"),
4143                                $cgi->a({-href => href(action=>"tree",
4144                                                       hash_base=>"HEAD", file_name=>$file_name)},
4145                                        "HEAD"),
4146                }
4147                if ($have_snapshot) {
4148                        # FIXME: Should be available when we have no hash base as well.
4149                        push @views_nav,
4150                                $cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
4151                                        "snapshot");
4152                }
4153                git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
4154                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
4155        } else {
4156                undef $hash_base;
4157                print "<div class=\"page_nav\">\n";
4158                print "<br/><br/></div>\n";
4159                print "<div class=\"title\">$hash</div>\n";
4160        }
4161        if (defined $file_name) {
4162                $basedir = $file_name;
4163                if ($basedir ne '' && substr($basedir, -1) ne '/') {
4164                        $basedir .= '/';
4165                }
4166        }
4167        git_print_page_path($file_name, 'tree', $hash_base);
4168        print "<div class=\"page_body\">\n";
4169        print "<table cellspacing=\"0\">\n";
4170        my $alternate = 1;
4171        # '..' (top directory) link if possible
4172        if (defined $hash_base &&
4173            defined $file_name && $file_name =~ m![^/]+$!) {
4174                if ($alternate) {
4175                        print "<tr class=\"dark\">\n";
4176                } else {
4177                        print "<tr class=\"light\">\n";
4178                }
4179                $alternate ^= 1;
4180
4181                my $up = $file_name;
4182                $up =~ s!/?[^/]+$!!;
4183                undef $up unless $up;
4184                # based on git_print_tree_entry
4185                print '<td class="mode">' . mode_str('040000') . "</td>\n";
4186                print '<td class="list">';
4187                print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
4188                                             file_name=>$up)},
4189                              "..");
4190                print "</td>\n";
4191                print "<td class=\"link\"></td>\n";
4192
4193                print "</tr>\n";
4194        }
4195        foreach my $line (@entries) {
4196                my %t = parse_ls_tree_line($line, -z => 1);
4197
4198                if ($alternate) {
4199                        print "<tr class=\"dark\">\n";
4200                } else {
4201                        print "<tr class=\"light\">\n";
4202                }
4203                $alternate ^= 1;
4204
4205                git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
4206
4207                print "</tr>\n";
4208        }
4209        print "</table>\n" .
4210              "</div>";
4211        git_footer_html();
4212}
4213
4214sub git_snapshot {
4215        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
4216        my $have_snapshot = (defined $ctype && defined $suffix);
4217        if (!$have_snapshot) {
4218                die_error('403 Permission denied', "Permission denied");
4219        }
4220
4221        if (!defined $hash) {
4222                $hash = git_get_head_hash($project);
4223        }
4224
4225        my $git = git_cmd_str();
4226        my $name = $project;
4227        $name =~ s,([^/])/*\.git$,$1,;
4228        $name = basename($name);
4229        my $filename = to_utf8($name);
4230        $name =~ s/\047/\047\\\047\047/g;
4231        my $cmd;
4232        if ($suffix eq 'zip') {
4233                $filename .= "-$hash.$suffix";
4234                $cmd = "$git archive --format=zip --prefix=\'$name\'/ $hash";
4235        } else {
4236                $filename .= "-$hash.tar.$suffix";
4237                $cmd = "$git archive --format=tar --prefix=\'$name\'/ $hash | $command";
4238        }
4239
4240        print $cgi->header(
4241                -type => "application/$ctype",
4242                -content_disposition => 'inline; filename="' . "$filename" . '"',
4243                -status => '200 OK');
4244
4245        open my $fd, "-|", $cmd
4246                or die_error(undef, "Execute git-archive failed");
4247        binmode STDOUT, ':raw';
4248        print <$fd>;
4249        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4250        close $fd;
4251
4252}
4253
4254sub git_log {
4255        my $head = git_get_head_hash($project);
4256        if (!defined $hash) {
4257                $hash = $head;
4258        }
4259        if (!defined $page) {
4260                $page = 0;
4261        }
4262        my $refs = git_get_references();
4263
4264        my @commitlist = parse_commits($hash, 101, (100 * $page));
4265
4266        my $paging_nav = format_paging_nav('log', $hash, $head, $page, (100 * ($page+1)));
4267
4268        git_header_html();
4269        git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
4270
4271        if (!@commitlist) {
4272                my %co = parse_commit($hash);
4273
4274                git_print_header_div('summary', $project);
4275                print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
4276        }
4277        my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
4278        for (my $i = 0; $i <= $to; $i++) {
4279                my %co = %{$commitlist[$i]};
4280                next if !%co;
4281                my $commit = $co{'id'};
4282                my $ref = format_ref_marker($refs, $commit);
4283                my %ad = parse_date($co{'author_epoch'});
4284                git_print_header_div('commit',
4285                               "<span class=\"age\">$co{'age_string'}</span>" .
4286                               esc_html($co{'title'}) . $ref,
4287                               $commit);
4288                print "<div class=\"title_text\">\n" .
4289                      "<div class=\"log_link\">\n" .
4290                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4291                      " | " .
4292                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4293                      " | " .
4294                      $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4295                      "<br/>\n" .
4296                      "</div>\n" .
4297                      "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
4298                      "</div>\n";
4299
4300                print "<div class=\"log_body\">\n";
4301                git_print_log($co{'comment'}, -final_empty_line=> 1);
4302                print "</div>\n";
4303        }
4304        if ($#commitlist >= 100) {
4305                print "<div class=\"page_nav\">\n";
4306                print $cgi->a({-href => href(action=>"log", hash=>$hash, page=>$page+1),
4307                               -accesskey => "n", -title => "Alt-n"}, "next");
4308                print "</div>\n";
4309        }
4310        git_footer_html();
4311}
4312
4313sub git_commit {
4314        $hash ||= $hash_base || "HEAD";
4315        my %co = parse_commit($hash);
4316        if (!%co) {
4317                die_error(undef, "Unknown commit object");
4318        }
4319        my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4320        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
4321
4322        my $parent  = $co{'parent'};
4323        my $parents = $co{'parents'}; # listref
4324
4325        # we need to prepare $formats_nav before any parameter munging
4326        my $formats_nav;
4327        if (!defined $parent) {
4328                # --root commitdiff
4329                $formats_nav .= '(initial)';
4330        } elsif (@$parents == 1) {
4331                # single parent commit
4332                $formats_nav .=
4333                        '(parent: ' .
4334                        $cgi->a({-href => href(action=>"commit",
4335                                               hash=>$parent)},
4336                                esc_html(substr($parent, 0, 7))) .
4337                        ')';
4338        } else {
4339                # merge commit
4340                $formats_nav .=
4341                        '(merge: ' .
4342                        join(' ', map {
4343                                $cgi->a({-href => href(action=>"commit",
4344                                                       hash=>$_)},
4345                                        esc_html(substr($_, 0, 7)));
4346                        } @$parents ) .
4347                        ')';
4348        }
4349
4350        if (!defined $parent) {
4351                $parent = "--root";
4352        }
4353        my @difftree;
4354        open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
4355                @diff_opts,
4356                (@$parents <= 1 ? $parent : '-c'),
4357                $hash, "--"
4358                or die_error(undef, "Open git-diff-tree failed");
4359        @difftree = map { chomp; $_ } <$fd>;
4360        close $fd or die_error(undef, "Reading git-diff-tree failed");
4361
4362        # non-textual hash id's can be cached
4363        my $expires;
4364        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4365                $expires = "+1d";
4366        }
4367        my $refs = git_get_references();
4368        my $ref = format_ref_marker($refs, $co{'id'});
4369
4370        my $have_snapshot = gitweb_have_snapshot();
4371
4372        git_header_html(undef, $expires);
4373        git_print_page_nav('commit', '',
4374                           $hash, $co{'tree'}, $hash,
4375                           $formats_nav);
4376
4377        if (defined $co{'parent'}) {
4378                git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
4379        } else {
4380                git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
4381        }
4382        print "<div class=\"title_text\">\n" .
4383              "<table cellspacing=\"0\">\n";
4384        print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
4385              "<tr>" .
4386              "<td></td><td> $ad{'rfc2822'}";
4387        if ($ad{'hour_local'} < 6) {
4388                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4389                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4390        } else {
4391                printf(" (%02d:%02d %s)",
4392                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4393        }
4394        print "</td>" .
4395              "</tr>\n";
4396        print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
4397        print "<tr><td></td><td> $cd{'rfc2822'}" .
4398              sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
4399              "</td></tr>\n";
4400        print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
4401        print "<tr>" .
4402              "<td>tree</td>" .
4403              "<td class=\"sha1\">" .
4404              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
4405                       class => "list"}, $co{'tree'}) .
4406              "</td>" .
4407              "<td class=\"link\">" .
4408              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
4409                      "tree");
4410        if ($have_snapshot) {
4411                print " | " .
4412                      $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
4413        }
4414        print "</td>" .
4415              "</tr>\n";
4416
4417        foreach my $par (@$parents) {
4418                print "<tr>" .
4419                      "<td>parent</td>" .
4420                      "<td class=\"sha1\">" .
4421                      $cgi->a({-href => href(action=>"commit", hash=>$par),
4422                               class => "list"}, $par) .
4423                      "</td>" .
4424                      "<td class=\"link\">" .
4425                      $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
4426                      " | " .
4427                      $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
4428                      "</td>" .
4429                      "</tr>\n";
4430        }
4431        print "</table>".
4432              "</div>\n";
4433
4434        print "<div class=\"page_body\">\n";
4435        git_print_log($co{'comment'});
4436        print "</div>\n";
4437
4438        git_difftree_body(\@difftree, $hash, @$parents);
4439
4440        git_footer_html();
4441}
4442
4443sub git_object {
4444        # object is defined by:
4445        # - hash or hash_base alone
4446        # - hash_base and file_name
4447        my $type;
4448
4449        # - hash or hash_base alone
4450        if ($hash || ($hash_base && !defined $file_name)) {
4451                my $object_id = $hash || $hash_base;
4452
4453                my $git_command = git_cmd_str();
4454                open my $fd, "-|", "$git_command cat-file -t $object_id 2>/dev/null"
4455                        or die_error('404 Not Found', "Object does not exist");
4456                $type = <$fd>;
4457                chomp $type;
4458                close $fd
4459                        or die_error('404 Not Found', "Object does not exist");
4460
4461        # - hash_base and file_name
4462        } elsif ($hash_base && defined $file_name) {
4463                $file_name =~ s,/+$,,;
4464
4465                system(git_cmd(), "cat-file", '-e', $hash_base) == 0
4466                        or die_error('404 Not Found', "Base object does not exist");
4467
4468                # here errors should not hapen
4469                open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
4470                        or die_error(undef, "Open git-ls-tree failed");
4471                my $line = <$fd>;
4472                close $fd;
4473
4474                #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
4475                unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
4476                        die_error('404 Not Found', "File or directory for given base does not exist");
4477                }
4478                $type = $2;
4479                $hash = $3;
4480        } else {
4481                die_error('404 Not Found', "Not enough information to find object");
4482        }
4483
4484        print $cgi->redirect(-uri => href(action=>$type, -full=>1,
4485                                          hash=>$hash, hash_base=>$hash_base,
4486                                          file_name=>$file_name),
4487                             -status => '302 Found');
4488}
4489
4490sub git_blobdiff {
4491        my $format = shift || 'html';
4492
4493        my $fd;
4494        my @difftree;
4495        my %diffinfo;
4496        my $expires;
4497
4498        # preparing $fd and %diffinfo for git_patchset_body
4499        # new style URI
4500        if (defined $hash_base && defined $hash_parent_base) {
4501                if (defined $file_name) {
4502                        # read raw output
4503                        open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4504                                $hash_parent_base, $hash_base,
4505                                "--", (defined $file_parent ? $file_parent : ()), $file_name
4506                                or die_error(undef, "Open git-diff-tree failed");
4507                        @difftree = map { chomp; $_ } <$fd>;
4508                        close $fd
4509                                or die_error(undef, "Reading git-diff-tree failed");
4510                        @difftree
4511                                or die_error('404 Not Found', "Blob diff not found");
4512
4513                } elsif (defined $hash &&
4514                         $hash =~ /[0-9a-fA-F]{40}/) {
4515                        # try to find filename from $hash
4516
4517                        # read filtered raw output
4518                        open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4519                                $hash_parent_base, $hash_base, "--"
4520                                or die_error(undef, "Open git-diff-tree failed");
4521                        @difftree =
4522                                # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
4523                                # $hash == to_id
4524                                grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
4525                                map { chomp; $_ } <$fd>;
4526                        close $fd
4527                                or die_error(undef, "Reading git-diff-tree failed");
4528                        @difftree
4529                                or die_error('404 Not Found', "Blob diff not found");
4530
4531                } else {
4532                        die_error('404 Not Found', "Missing one of the blob diff parameters");
4533                }
4534
4535                if (@difftree > 1) {
4536                        die_error('404 Not Found', "Ambiguous blob diff specification");
4537                }
4538
4539                %diffinfo = parse_difftree_raw_line($difftree[0]);
4540                $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
4541                $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
4542
4543                $hash_parent ||= $diffinfo{'from_id'};
4544                $hash        ||= $diffinfo{'to_id'};
4545
4546                # non-textual hash id's can be cached
4547                if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
4548                    $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
4549                        $expires = '+1d';
4550                }
4551
4552                # open patch output
4553                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4554                        '-p', ($format eq 'html' ? "--full-index" : ()),
4555                        $hash_parent_base, $hash_base,
4556                        "--", (defined $file_parent ? $file_parent : ()), $file_name
4557                        or die_error(undef, "Open git-diff-tree failed");
4558        }
4559
4560        # old/legacy style URI
4561        if (!%diffinfo && # if new style URI failed
4562            defined $hash && defined $hash_parent) {
4563                # fake git-diff-tree raw output
4564                $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
4565                $diffinfo{'from_id'} = $hash_parent;
4566                $diffinfo{'to_id'}   = $hash;
4567                if (defined $file_name) {
4568                        if (defined $file_parent) {
4569                                $diffinfo{'status'} = '2';
4570                                $diffinfo{'from_file'} = $file_parent;
4571                                $diffinfo{'to_file'}   = $file_name;
4572                        } else { # assume not renamed
4573                                $diffinfo{'status'} = '1';
4574                                $diffinfo{'from_file'} = $file_name;
4575                                $diffinfo{'to_file'}   = $file_name;
4576                        }
4577                } else { # no filename given
4578                        $diffinfo{'status'} = '2';
4579                        $diffinfo{'from_file'} = $hash_parent;
4580                        $diffinfo{'to_file'}   = $hash;
4581                }
4582
4583                # non-textual hash id's can be cached
4584                if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
4585                    $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4586                        $expires = '+1d';
4587                }
4588
4589                # open patch output
4590                open $fd, "-|", git_cmd(), "diff", @diff_opts,
4591                        '-p', ($format eq 'html' ? "--full-index" : ()),
4592                        $hash_parent, $hash, "--"
4593                        or die_error(undef, "Open git-diff failed");
4594        } else  {
4595                die_error('404 Not Found', "Missing one of the blob diff parameters")
4596                        unless %diffinfo;
4597        }
4598
4599        # header
4600        if ($format eq 'html') {
4601                my $formats_nav =
4602                        $cgi->a({-href => href(action=>"blobdiff_plain",
4603                                               hash=>$hash, hash_parent=>$hash_parent,
4604                                               hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
4605                                               file_name=>$file_name, file_parent=>$file_parent)},
4606                                "raw");
4607                git_header_html(undef, $expires);
4608                if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4609                        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4610                        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4611                } else {
4612                        print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
4613                        print "<div class=\"title\">$hash vs $hash_parent</div>\n";
4614                }
4615                if (defined $file_name) {
4616                        git_print_page_path($file_name, "blob", $hash_base);
4617                } else {
4618                        print "<div class=\"page_path\"></div>\n";
4619                }
4620
4621        } elsif ($format eq 'plain') {
4622                print $cgi->header(
4623                        -type => 'text/plain',
4624                        -charset => 'utf-8',
4625                        -expires => $expires,
4626                        -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
4627
4628                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4629
4630        } else {
4631                die_error(undef, "Unknown blobdiff format");
4632        }
4633
4634        # patch
4635        if ($format eq 'html') {
4636                print "<div class=\"page_body\">\n";
4637
4638                git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
4639                close $fd;
4640
4641                print "</div>\n"; # class="page_body"
4642                git_footer_html();
4643
4644        } else {
4645                while (my $line = <$fd>) {
4646                        $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
4647                        $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
4648
4649                        print $line;
4650
4651                        last if $line =~ m!^\+\+\+!;
4652                }
4653                local $/ = undef;
4654                print <$fd>;
4655                close $fd;
4656        }
4657}
4658
4659sub git_blobdiff_plain {
4660        git_blobdiff('plain');
4661}
4662
4663sub git_commitdiff {
4664        my $format = shift || 'html';
4665        $hash ||= $hash_base || "HEAD";
4666        my %co = parse_commit($hash);
4667        if (!%co) {
4668                die_error(undef, "Unknown commit object");
4669        }
4670
4671        # choose format for commitdiff for merge
4672        if (! defined $hash_parent && @{$co{'parents'}} > 1) {
4673                $hash_parent = '--cc';
4674        }
4675        # we need to prepare $formats_nav before almost any parameter munging
4676        my $formats_nav;
4677        if ($format eq 'html') {
4678                $formats_nav =
4679                        $cgi->a({-href => href(action=>"commitdiff_plain",
4680                                               hash=>$hash, hash_parent=>$hash_parent)},
4681                                "raw");
4682
4683                if (defined $hash_parent &&
4684                    $hash_parent ne '-c' && $hash_parent ne '--cc') {
4685                        # commitdiff with two commits given
4686                        my $hash_parent_short = $hash_parent;
4687                        if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4688                                $hash_parent_short = substr($hash_parent, 0, 7);
4689                        }
4690                        $formats_nav .=
4691                                ' (from';
4692                        for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
4693                                if ($co{'parents'}[$i] eq $hash_parent) {
4694                                        $formats_nav .= ' parent ' . ($i+1);
4695                                        last;
4696                                }
4697                        }
4698                        $formats_nav .= ': ' .
4699                                $cgi->a({-href => href(action=>"commitdiff",
4700                                                       hash=>$hash_parent)},
4701                                        esc_html($hash_parent_short)) .
4702                                ')';
4703                } elsif (!$co{'parent'}) {
4704                        # --root commitdiff
4705                        $formats_nav .= ' (initial)';
4706                } elsif (scalar @{$co{'parents'}} == 1) {
4707                        # single parent commit
4708                        $formats_nav .=
4709                                ' (parent: ' .
4710                                $cgi->a({-href => href(action=>"commitdiff",
4711                                                       hash=>$co{'parent'})},
4712                                        esc_html(substr($co{'parent'}, 0, 7))) .
4713                                ')';
4714                } else {
4715                        # merge commit
4716                        if ($hash_parent eq '--cc') {
4717                                $formats_nav .= ' | ' .
4718                                        $cgi->a({-href => href(action=>"commitdiff",
4719                                                               hash=>$hash, hash_parent=>'-c')},
4720                                                'combined');
4721                        } else { # $hash_parent eq '-c'
4722                                $formats_nav .= ' | ' .
4723                                        $cgi->a({-href => href(action=>"commitdiff",
4724                                                               hash=>$hash, hash_parent=>'--cc')},
4725                                                'compact');
4726                        }
4727                        $formats_nav .=
4728                                ' (merge: ' .
4729                                join(' ', map {
4730                                        $cgi->a({-href => href(action=>"commitdiff",
4731                                                               hash=>$_)},
4732                                                esc_html(substr($_, 0, 7)));
4733                                } @{$co{'parents'}} ) .
4734                                ')';
4735                }
4736        }
4737
4738        my $hash_parent_param = $hash_parent;
4739        if (!defined $hash_parent_param) {
4740                # --cc for multiple parents, --root for parentless
4741                $hash_parent_param =
4742                        @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
4743        }
4744
4745        # read commitdiff
4746        my $fd;
4747        my @difftree;
4748        if ($format eq 'html') {
4749                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4750                        "--no-commit-id", "--patch-with-raw", "--full-index",
4751                        $hash_parent_param, $hash, "--"
4752                        or die_error(undef, "Open git-diff-tree failed");
4753
4754                while (my $line = <$fd>) {
4755                        chomp $line;
4756                        # empty line ends raw part of diff-tree output
4757                        last unless $line;
4758                        push @difftree, scalar parse_difftree_raw_line($line);
4759                }
4760
4761        } elsif ($format eq 'plain') {
4762                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4763                        '-p', $hash_parent_param, $hash, "--"
4764                        or die_error(undef, "Open git-diff-tree failed");
4765
4766        } else {
4767                die_error(undef, "Unknown commitdiff format");
4768        }
4769
4770        # non-textual hash id's can be cached
4771        my $expires;
4772        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4773                $expires = "+1d";
4774        }
4775
4776        # write commit message
4777        if ($format eq 'html') {
4778                my $refs = git_get_references();
4779                my $ref = format_ref_marker($refs, $co{'id'});
4780
4781                git_header_html(undef, $expires);
4782                git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
4783                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
4784                git_print_authorship(\%co);
4785                print "<div class=\"page_body\">\n";
4786                if (@{$co{'comment'}} > 1) {
4787                        print "<div class=\"log\">\n";
4788                        git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
4789                        print "</div>\n"; # class="log"
4790                }
4791
4792        } elsif ($format eq 'plain') {
4793                my $refs = git_get_references("tags");
4794                my $tagname = git_get_rev_name_tags($hash);
4795                my $filename = basename($project) . "-$hash.patch";
4796
4797                print $cgi->header(
4798                        -type => 'text/plain',
4799                        -charset => 'utf-8',
4800                        -expires => $expires,
4801                        -content_disposition => 'inline; filename="' . "$filename" . '"');
4802                my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4803                print <<TEXT;
4804From: $co{'author'}
4805Date: $ad{'rfc2822'} ($ad{'tz_local'})
4806Subject: $co{'title'}
4807TEXT
4808                print "X-Git-Tag: $tagname\n" if $tagname;
4809                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4810
4811                foreach my $line (@{$co{'comment'}}) {
4812                        print "$line\n";
4813                }
4814                print "---\n\n";
4815        }
4816
4817        # write patch
4818        if ($format eq 'html') {
4819                my $use_parents = !defined $hash_parent ||
4820                        $hash_parent eq '-c' || $hash_parent eq '--cc';
4821                git_difftree_body(\@difftree, $hash,
4822                                  $use_parents ? @{$co{'parents'}} : $hash_parent);
4823                print "<br/>\n";
4824
4825                git_patchset_body($fd, \@difftree, $hash,
4826                                  $use_parents ? @{$co{'parents'}} : $hash_parent);
4827                close $fd;
4828                print "</div>\n"; # class="page_body"
4829                git_footer_html();
4830
4831        } elsif ($format eq 'plain') {
4832                local $/ = undef;
4833                print <$fd>;
4834                close $fd
4835                        or print "Reading git-diff-tree failed\n";
4836        }
4837}
4838
4839sub git_commitdiff_plain {
4840        git_commitdiff('plain');
4841}
4842
4843sub git_history {
4844        if (!defined $hash_base) {
4845                $hash_base = git_get_head_hash($project);
4846        }
4847        if (!defined $page) {
4848                $page = 0;
4849        }
4850        my $ftype;
4851        my %co = parse_commit($hash_base);
4852        if (!%co) {
4853                die_error(undef, "Unknown commit object");
4854        }
4855
4856        my $refs = git_get_references();
4857        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
4858
4859        if (!defined $hash && defined $file_name) {
4860                $hash = git_get_hash_by_path($hash_base, $file_name);
4861        }
4862        if (defined $hash) {
4863                $ftype = git_get_type($hash);
4864        }
4865
4866        my @commitlist = parse_commits($hash_base, 101, (100 * $page), "--full-history", $file_name);
4867
4868        my $paging_nav = '';
4869        if ($page > 0) {
4870                $paging_nav .=
4871                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4872                                               file_name=>$file_name)},
4873                                "first");
4874                $paging_nav .= " &sdot; " .
4875                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4876                                               file_name=>$file_name, page=>$page-1),
4877                                 -accesskey => "p", -title => "Alt-p"}, "prev");
4878        } else {
4879                $paging_nav .= "first";
4880                $paging_nav .= " &sdot; prev";
4881        }
4882        if ($#commitlist >= 100) {
4883                $paging_nav .= " &sdot; " .
4884                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4885                                               file_name=>$file_name, page=>$page+1),
4886                                 -accesskey => "n", -title => "Alt-n"}, "next");
4887        } else {
4888                $paging_nav .= " &sdot; next";
4889        }
4890        my $next_link = '';
4891        if ($#commitlist >= 100) {
4892                $next_link =
4893                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4894                                               file_name=>$file_name, page=>$page+1),
4895                                 -accesskey => "n", -title => "Alt-n"}, "next");
4896        }
4897
4898        git_header_html();
4899        git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
4900        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4901        git_print_page_path($file_name, $ftype, $hash_base);
4902
4903        git_history_body(\@commitlist, 0, 99,
4904                         $refs, $hash_base, $ftype, $next_link);
4905
4906        git_footer_html();
4907}
4908
4909sub git_search {
4910        my ($have_search) = gitweb_check_feature('search');
4911        if (!$have_search) {
4912                die_error('403 Permission denied', "Permission denied");
4913        }
4914        if (!defined $searchtext) {
4915                die_error(undef, "Text field empty");
4916        }
4917        if (!defined $hash) {
4918                $hash = git_get_head_hash($project);
4919        }
4920        my %co = parse_commit($hash);
4921        if (!%co) {
4922                die_error(undef, "Unknown commit object");
4923        }
4924        if (!defined $page) {
4925                $page = 0;
4926        }
4927
4928        $searchtype ||= 'commit';
4929        if ($searchtype eq 'pickaxe') {
4930                # pickaxe may take all resources of your box and run for several minutes
4931                # with every query - so decide by yourself how public you make this feature
4932                my ($have_pickaxe) = gitweb_check_feature('pickaxe');
4933                if (!$have_pickaxe) {
4934                        die_error('403 Permission denied', "Permission denied");
4935                }
4936        }
4937        if ($searchtype eq 'grep') {
4938                my ($have_grep) = gitweb_check_feature('grep');
4939                if (!$have_grep) {
4940                        die_error('403 Permission denied', "Permission denied");
4941                }
4942        }
4943
4944        git_header_html();
4945
4946        if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
4947                my $greptype;
4948                if ($searchtype eq 'commit') {
4949                        $greptype = "--grep=";
4950                } elsif ($searchtype eq 'author') {
4951                        $greptype = "--author=";
4952                } elsif ($searchtype eq 'committer') {
4953                        $greptype = "--committer=";
4954                }
4955                $greptype .= $search_regexp;
4956                my @commitlist = parse_commits($hash, 101, (100 * $page), $greptype);
4957
4958                my $paging_nav = '';
4959                if ($page > 0) {
4960                        $paging_nav .=
4961                                $cgi->a({-href => href(action=>"search", hash=>$hash,
4962                                                       searchtext=>$searchtext, searchtype=>$searchtype)},
4963                                        "first");
4964                        $paging_nav .= " &sdot; " .
4965                                $cgi->a({-href => href(action=>"search", hash=>$hash,
4966                                                       searchtext=>$searchtext, searchtype=>$searchtype,
4967                                                       page=>$page-1),
4968                                         -accesskey => "p", -title => "Alt-p"}, "prev");
4969                } else {
4970                        $paging_nav .= "first";
4971                        $paging_nav .= " &sdot; prev";
4972                }
4973                if ($#commitlist >= 100) {
4974                        $paging_nav .= " &sdot; " .
4975                                $cgi->a({-href => href(action=>"search", hash=>$hash,
4976                                                       searchtext=>$searchtext, searchtype=>$searchtype,
4977                                                       page=>$page+1),
4978                                         -accesskey => "n", -title => "Alt-n"}, "next");
4979                } else {
4980                        $paging_nav .= " &sdot; next";
4981                }
4982                my $next_link = '';
4983                if ($#commitlist >= 100) {
4984                        $next_link =
4985                                $cgi->a({-href => href(action=>"search", hash=>$hash,
4986                                                       searchtext=>$searchtext, searchtype=>$searchtype,
4987                                                       page=>$page+1),
4988                                         -accesskey => "n", -title => "Alt-n"}, "next");
4989                }
4990
4991                git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
4992                git_print_header_div('commit', esc_html($co{'title'}), $hash);
4993                git_search_grep_body(\@commitlist, 0, 99, $next_link);
4994        }
4995
4996        if ($searchtype eq 'pickaxe') {
4997                git_print_page_nav('','', $hash,$co{'tree'},$hash);
4998                git_print_header_div('commit', esc_html($co{'title'}), $hash);
4999
5000                print "<table cellspacing=\"0\">\n";
5001                my $alternate = 1;
5002                $/ = "\n";
5003                my $git_command = git_cmd_str();
5004                my $searchqtext = $searchtext;
5005                $searchqtext =~ s/'/'\\''/;
5006                open my $fd, "-|", "$git_command rev-list $hash | " .
5007                        "$git_command diff-tree -r --stdin -S\'$searchqtext\'";
5008                undef %co;
5009                my @files;
5010                while (my $line = <$fd>) {
5011                        if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
5012                                my %set;
5013                                $set{'file'} = $6;
5014                                $set{'from_id'} = $3;
5015                                $set{'to_id'} = $4;
5016                                $set{'id'} = $set{'to_id'};
5017                                if ($set{'id'} =~ m/0{40}/) {
5018                                        $set{'id'} = $set{'from_id'};
5019                                }
5020                                if ($set{'id'} =~ m/0{40}/) {
5021                                        next;
5022                                }
5023                                push @files, \%set;
5024                        } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
5025                                if (%co) {
5026                                        if ($alternate) {
5027                                                print "<tr class=\"dark\">\n";
5028                                        } else {
5029                                                print "<tr class=\"light\">\n";
5030                                        }
5031                                        $alternate ^= 1;
5032                                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5033                                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
5034                                              "<td>" .
5035                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5036                                                      -class => "list subject"},
5037                                                      esc_html(chop_str($co{'title'}, 50)) . "<br/>");
5038                                        while (my $setref = shift @files) {
5039                                                my %set = %$setref;
5040                                                print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
5041                                                                             hash=>$set{'id'}, file_name=>$set{'file'}),
5042                                                              -class => "list"},
5043                                                              "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
5044                                                      "<br/>\n";
5045                                        }
5046                                        print "</td>\n" .
5047                                              "<td class=\"link\">" .
5048                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5049                                              " | " .
5050                                              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5051                                        print "</td>\n" .
5052                                              "</tr>\n";
5053                                }
5054                                %co = parse_commit($1);
5055                        }
5056                }
5057                close $fd;
5058
5059                print "</table>\n";
5060        }
5061
5062        if ($searchtype eq 'grep') {
5063                git_print_page_nav('','', $hash,$co{'tree'},$hash);
5064                git_print_header_div('commit', esc_html($co{'title'}), $hash);
5065
5066                print "<table cellspacing=\"0\">\n";
5067                my $alternate = 1;
5068                my $matches = 0;
5069                $/ = "\n";
5070                open my $fd, "-|", git_cmd(), 'grep', '-n', '-i', '-E', $searchtext, $co{'tree'};
5071                my $lastfile = '';
5072                while (my $line = <$fd>) {
5073                        chomp $line;
5074                        my ($file, $lno, $ltext, $binary);
5075                        last if ($matches++ > 1000);
5076                        if ($line =~ /^Binary file (.+) matches$/) {
5077                                $file = $1;
5078                                $binary = 1;
5079                        } else {
5080                                (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
5081                        }
5082                        if ($file ne $lastfile) {
5083                                $lastfile and print "</td></tr>\n";
5084                                if ($alternate++) {
5085                                        print "<tr class=\"dark\">\n";
5086                                } else {
5087                                        print "<tr class=\"light\">\n";
5088                                }
5089                                print "<td class=\"list\">".
5090                                        $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5091                                                               file_name=>"$file"),
5092                                                -class => "list"}, esc_path($file));
5093                                print "</td><td>\n";
5094                                $lastfile = $file;
5095                        }
5096                        if ($binary) {
5097                                print "<div class=\"binary\">Binary file</div>\n";
5098                        } else {
5099                                $ltext = untabify($ltext);
5100                                if ($ltext =~ m/^(.*)($searchtext)(.*)$/i) {
5101                                        $ltext = esc_html($1, -nbsp=>1);
5102                                        $ltext .= '<span class="match">';
5103                                        $ltext .= esc_html($2, -nbsp=>1);
5104                                        $ltext .= '</span>';
5105                                        $ltext .= esc_html($3, -nbsp=>1);
5106                                } else {
5107                                        $ltext = esc_html($ltext, -nbsp=>1);
5108                                }
5109                                print "<div class=\"pre\">" .
5110                                        $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5111                                                               file_name=>"$file").'#l'.$lno,
5112                                                -class => "linenr"}, sprintf('%4i', $lno))
5113                                        . ' ' .  $ltext . "</div>\n";
5114                        }
5115                }
5116                if ($lastfile) {
5117                        print "</td></tr>\n";
5118                        if ($matches > 1000) {
5119                                print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
5120                        }
5121                } else {
5122                        print "<div class=\"diff nodifferences\">No matches found</div>\n";
5123                }
5124                close $fd;
5125
5126                print "</table>\n";
5127        }
5128        git_footer_html();
5129}
5130
5131sub git_search_help {
5132        git_header_html();
5133        git_print_page_nav('','', $hash,$hash,$hash);
5134        print <<EOT;
5135<dl>
5136<dt><b>commit</b></dt>
5137<dd>The commit messages and authorship information will be scanned for the given string.</dd>
5138EOT
5139        my ($have_grep) = gitweb_check_feature('grep');
5140        if ($have_grep) {
5141                print <<EOT;
5142<dt><b>grep</b></dt>
5143<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
5144    a different one) are searched for the given
5145<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a>
5146(POSIX extended) and the matches are listed. On large
5147trees, this search can take a while and put some strain on the server, so please use it with
5148some consideration.</dd>
5149EOT
5150        }
5151        print <<EOT;
5152<dt><b>author</b></dt>
5153<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given string.</dd>
5154<dt><b>committer</b></dt>
5155<dd>Name and e-mail of the committer and date of commit will be scanned for the given string.</dd>
5156EOT
5157        my ($have_pickaxe) = gitweb_check_feature('pickaxe');
5158        if ($have_pickaxe) {
5159                print <<EOT;
5160<dt><b>pickaxe</b></dt>
5161<dd>All commits that caused the string to appear or disappear from any file (changes that
5162added, removed or "modified" the string) will be listed. This search can take a while and
5163takes a lot of strain on the server, so please use it wisely.</dd>
5164EOT
5165        }
5166        print "</dl>\n";
5167        git_footer_html();
5168}
5169
5170sub git_shortlog {
5171        my $head = git_get_head_hash($project);
5172        if (!defined $hash) {
5173                $hash = $head;
5174        }
5175        if (!defined $page) {
5176                $page = 0;
5177        }
5178        my $refs = git_get_references();
5179
5180        my @commitlist = parse_commits($hash, 101, (100 * $page));
5181
5182        my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, (100 * ($page+1)));
5183        my $next_link = '';
5184        if ($#commitlist >= 100) {
5185                $next_link =
5186                        $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
5187                                 -accesskey => "n", -title => "Alt-n"}, "next");
5188        }
5189
5190        git_header_html();
5191        git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
5192        git_print_header_div('summary', $project);
5193
5194        git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
5195
5196        git_footer_html();
5197}
5198
5199## ......................................................................
5200## feeds (RSS, Atom; OPML)
5201
5202sub git_feed {
5203        my $format = shift || 'atom';
5204        my ($have_blame) = gitweb_check_feature('blame');
5205
5206        # Atom: http://www.atomenabled.org/developers/syndication/
5207        # RSS:  http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
5208        if ($format ne 'rss' && $format ne 'atom') {
5209                die_error(undef, "Unknown web feed format");
5210        }
5211
5212        # log/feed of current (HEAD) branch, log of given branch, history of file/directory
5213        my $head = $hash || 'HEAD';
5214        my @commitlist = parse_commits($head, 150);
5215
5216        my %latest_commit;
5217        my %latest_date;
5218        my $content_type = "application/$format+xml";
5219        if (defined $cgi->http('HTTP_ACCEPT') &&
5220                 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
5221                # browser (feed reader) prefers text/xml
5222                $content_type = 'text/xml';
5223        }
5224        if (defined($commitlist[0])) {
5225                %latest_commit = %{$commitlist[0]};
5226                %latest_date   = parse_date($latest_commit{'author_epoch'});
5227                print $cgi->header(
5228                        -type => $content_type,
5229                        -charset => 'utf-8',
5230                        -last_modified => $latest_date{'rfc2822'});
5231        } else {
5232                print $cgi->header(
5233                        -type => $content_type,
5234                        -charset => 'utf-8');
5235        }
5236
5237        # Optimization: skip generating the body if client asks only
5238        # for Last-Modified date.
5239        return if ($cgi->request_method() eq 'HEAD');
5240
5241        # header variables
5242        my $title = "$site_name - $project/$action";
5243        my $feed_type = 'log';
5244        if (defined $hash) {
5245                $title .= " - '$hash'";
5246                $feed_type = 'branch log';
5247                if (defined $file_name) {
5248                        $title .= " :: $file_name";
5249                        $feed_type = 'history';
5250                }
5251        } elsif (defined $file_name) {
5252                $title .= " - $file_name";
5253                $feed_type = 'history';
5254        }
5255        $title .= " $feed_type";
5256        my $descr = git_get_project_description($project);
5257        if (defined $descr) {
5258                $descr = esc_html($descr);
5259        } else {
5260                $descr = "$project " .
5261                         ($format eq 'rss' ? 'RSS' : 'Atom') .
5262                         " feed";
5263        }
5264        my $owner = git_get_project_owner($project);
5265        $owner = esc_html($owner);
5266
5267        #header
5268        my $alt_url;
5269        if (defined $file_name) {
5270                $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
5271        } elsif (defined $hash) {
5272                $alt_url = href(-full=>1, action=>"log", hash=>$hash);
5273        } else {
5274                $alt_url = href(-full=>1, action=>"summary");
5275        }
5276        print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
5277        if ($format eq 'rss') {
5278                print <<XML;
5279<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
5280<channel>
5281XML
5282                print "<title>$title</title>\n" .
5283                      "<link>$alt_url</link>\n" .
5284                      "<description>$descr</description>\n" .
5285                      "<language>en</language>\n";
5286        } elsif ($format eq 'atom') {
5287                print <<XML;
5288<feed xmlns="http://www.w3.org/2005/Atom">
5289XML
5290                print "<title>$title</title>\n" .
5291                      "<subtitle>$descr</subtitle>\n" .
5292                      '<link rel="alternate" type="text/html" href="' .
5293                      $alt_url . '" />' . "\n" .
5294                      '<link rel="self" type="' . $content_type . '" href="' .
5295                      $cgi->self_url() . '" />' . "\n" .
5296                      "<id>" . href(-full=>1) . "</id>\n" .
5297                      # use project owner for feed author
5298                      "<author><name>$owner</name></author>\n";
5299                if (defined $favicon) {
5300                        print "<icon>" . esc_url($favicon) . "</icon>\n";
5301                }
5302                if (defined $logo_url) {
5303                        # not twice as wide as tall: 72 x 27 pixels
5304                        print "<logo>" . esc_url($logo) . "</logo>\n";
5305                }
5306                if (! %latest_date) {
5307                        # dummy date to keep the feed valid until commits trickle in:
5308                        print "<updated>1970-01-01T00:00:00Z</updated>\n";
5309                } else {
5310                        print "<updated>$latest_date{'iso-8601'}</updated>\n";
5311                }
5312        }
5313
5314        # contents
5315        for (my $i = 0; $i <= $#commitlist; $i++) {
5316                my %co = %{$commitlist[$i]};
5317                my $commit = $co{'id'};
5318                # we read 150, we always show 30 and the ones more recent than 48 hours
5319                if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
5320                        last;
5321                }
5322                my %cd = parse_date($co{'author_epoch'});
5323
5324                # get list of changed files
5325                open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5326                        $co{'parent'} || "--root",
5327                        $co{'id'}, "--", (defined $file_name ? $file_name : ())
5328                        or next;
5329                my @difftree = map { chomp; $_ } <$fd>;
5330                close $fd
5331                        or next;
5332
5333                # print element (entry, item)
5334                my $co_url = href(-full=>1, action=>"commit", hash=>$commit);
5335                if ($format eq 'rss') {
5336                        print "<item>\n" .
5337                              "<title>" . esc_html($co{'title'}) . "</title>\n" .
5338                              "<author>" . esc_html($co{'author'}) . "</author>\n" .
5339                              "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
5340                              "<guid isPermaLink=\"true\">$co_url</guid>\n" .
5341                              "<link>$co_url</link>\n" .
5342                              "<description>" . esc_html($co{'title'}) . "</description>\n" .
5343                              "<content:encoded>" .
5344                              "<![CDATA[\n";
5345                } elsif ($format eq 'atom') {
5346                        print "<entry>\n" .
5347                              "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
5348                              "<updated>$cd{'iso-8601'}</updated>\n" .
5349                              "<author>\n" .
5350                              "  <name>" . esc_html($co{'author_name'}) . "</name>\n";
5351                        if ($co{'author_email'}) {
5352                                print "  <email>" . esc_html($co{'author_email'}) . "</email>\n";
5353                        }
5354                        print "</author>\n" .
5355                              # use committer for contributor
5356                              "<contributor>\n" .
5357                              "  <name>" . esc_html($co{'committer_name'}) . "</name>\n";
5358                        if ($co{'committer_email'}) {
5359                                print "  <email>" . esc_html($co{'committer_email'}) . "</email>\n";
5360                        }
5361                        print "</contributor>\n" .
5362                              "<published>$cd{'iso-8601'}</published>\n" .
5363                              "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
5364                              "<id>$co_url</id>\n" .
5365                              "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
5366                              "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
5367                }
5368                my $comment = $co{'comment'};
5369                print "<pre>\n";
5370                foreach my $line (@$comment) {
5371                        $line = esc_html($line);
5372                        print "$line\n";
5373                }
5374                print "</pre><ul>\n";
5375                foreach my $difftree_line (@difftree) {
5376                        my %difftree = parse_difftree_raw_line($difftree_line);
5377                        next if !$difftree{'from_id'};
5378
5379                        my $file = $difftree{'file'} || $difftree{'to_file'};
5380
5381                        print "<li>" .
5382                              "[" .
5383                              $cgi->a({-href => href(-full=>1, action=>"blobdiff",
5384                                                     hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
5385                                                     hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
5386                                                     file_name=>$file, file_parent=>$difftree{'from_file'}),
5387                                      -title => "diff"}, 'D');
5388                        if ($have_blame) {
5389                                print $cgi->a({-href => href(-full=>1, action=>"blame",
5390                                                             file_name=>$file, hash_base=>$commit),
5391                                              -title => "blame"}, 'B');
5392                        }
5393                        # if this is not a feed of a file history
5394                        if (!defined $file_name || $file_name ne $file) {
5395                                print $cgi->a({-href => href(-full=>1, action=>"history",
5396                                                             file_name=>$file, hash=>$commit),
5397                                              -title => "history"}, 'H');
5398                        }
5399                        $file = esc_path($file);
5400                        print "] ".
5401                              "$file</li>\n";
5402                }
5403                if ($format eq 'rss') {
5404                        print "</ul>]]>\n" .
5405                              "</content:encoded>\n" .
5406                              "</item>\n";
5407                } elsif ($format eq 'atom') {
5408                        print "</ul>\n</div>\n" .
5409                              "</content>\n" .
5410                              "</entry>\n";
5411                }
5412        }
5413
5414        # end of feed
5415        if ($format eq 'rss') {
5416                print "</channel>\n</rss>\n";
5417        }       elsif ($format eq 'atom') {
5418                print "</feed>\n";
5419        }
5420}
5421
5422sub git_rss {
5423        git_feed('rss');
5424}
5425
5426sub git_atom {
5427        git_feed('atom');
5428}
5429
5430sub git_opml {
5431        my @list = git_get_projects_list();
5432
5433        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
5434        print <<XML;
5435<?xml version="1.0" encoding="utf-8"?>
5436<opml version="1.0">
5437<head>
5438  <title>$site_name OPML Export</title>
5439</head>
5440<body>
5441<outline text="git RSS feeds">
5442XML
5443
5444        foreach my $pr (@list) {
5445                my %proj = %$pr;
5446                my $head = git_get_head_hash($proj{'path'});
5447                if (!defined $head) {
5448                        next;
5449                }
5450                $git_dir = "$projectroot/$proj{'path'}";
5451                my %co = parse_commit($head);
5452                if (!%co) {
5453                        next;
5454                }
5455
5456                my $path = esc_html(chop_str($proj{'path'}, 25, 5));
5457                my $rss  = "$my_url?p=$proj{'path'};a=rss";
5458                my $html = "$my_url?p=$proj{'path'};a=summary";
5459                print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
5460        }
5461        print <<XML;
5462</outline>
5463</body>
5464</opml>
5465XML
5466}