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