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