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