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