gitweb / gitweb.perlon commit gitweb: Use parse_difftree_raw_line in git_difftree_body (e8e41a9)
   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# location for temporary files needed for diffs
  35our $git_temp = "/tmp/gitweb";
  36
  37# target of the home link on top of all pages
  38our $home_link = $my_uri || "/";
  39
  40# string of the home link on top of all pages
  41our $home_link_str = "++GITWEB_HOME_LINK_STR++";
  42
  43# name of your site or organization to appear in page titles
  44# replace this with something more descriptive for clearer bookmarks
  45our $site_name = "++GITWEB_SITENAME++" || $ENV{'SERVER_NAME'} || "Untitled";
  46
  47# html text to include at home page
  48our $home_text = "++GITWEB_HOMETEXT++";
  49
  50# URI of default stylesheet
  51our $stylesheet = "++GITWEB_CSS++";
  52# URI of GIT logo
  53our $logo = "++GITWEB_LOGO++";
  54
  55# source of projects list
  56our $projects_list = "++GITWEB_LIST++";
  57
  58# list of git base URLs used for URL to where fetch project from,
  59# i.e. full URL is "$git_base_url/$project"
  60our @git_base_url_list = ("++GITWEB_BASE_URL++");
  61
  62# default blob_plain mimetype and default charset for text/plain blob
  63our $default_blob_plain_mimetype = 'text/plain';
  64our $default_text_plain_charset  = undef;
  65
  66# file to use for guessing MIME types before trying /etc/mime.types
  67# (relative to the current git repository)
  68our $mimetypes_file = undef;
  69
  70# You define site-wide feature defaults here; override them with
  71# $GITWEB_CONFIG as necessary.
  72our %feature =
  73(
  74
  75# feature  => {'sub' => feature-sub, 'override' => allow-override, 'default' => [ default options...]
  76
  77'blame'         => {'sub' => \&feature_blame, 'override' => 0, 'default' => [0]},
  78'snapshot'      => {'sub' => \&feature_snapshot, 'override' => 0, 'default' => ['x-gzip', 'gz', 'gzip']},
  79
  80);
  81
  82sub gitweb_check_feature {
  83        my ($name) = @_;
  84        return undef unless exists $feature{$name};
  85        my ($sub, $override, @defaults) = ($feature{$name}{'sub'},
  86                                                $feature{$name}{'override'},
  87                                                @{$feature{$name}{'default'}});
  88        if (!$override) { return @defaults; }
  89        return $sub->(@defaults);
  90}
  91
  92# To enable system wide have in $GITWEB_CONFIG
  93# $feature{'blame'}{'default'} =  [1];
  94# To have project specific config enable override in  $GITWEB_CONFIG
  95# $feature{'blame'}{'override'} =  1;
  96# and in project config gitweb.blame = 0|1;
  97
  98sub feature_blame {
  99        my ($val) = git_get_project_config('blame', '--bool');
 100
 101        if ($val eq 'true') {
 102                return 1;
 103        } elsif ($val eq 'false') {
 104                return 0;
 105        }
 106
 107        return $_[0];
 108}
 109
 110# To disable system wide have in $GITWEB_CONFIG
 111# $feature{'snapshot'}{'default'} =  [undef];
 112# To have project specific config enable override in  $GITWEB_CONFIG
 113# $feature{'blame'}{'override'} =  1;
 114# and in project config  gitweb.snapshot = none|gzip|bzip2
 115
 116sub feature_snapshot {
 117        my ($ctype, $suffix, $command) = @_;
 118
 119        my ($val) = git_get_project_config('snapshot');
 120
 121        if ($val eq 'gzip') {
 122                return ('x-gzip', 'gz', 'gzip');
 123        } elsif ($val eq 'bzip2') {
 124                return ('x-bzip2', 'bz2', 'bzip2');
 125        } elsif ($val eq 'none') {
 126                return ();
 127        }
 128
 129        return ($ctype, $suffix, $command);
 130}
 131
 132our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
 133require $GITWEB_CONFIG if -e $GITWEB_CONFIG;
 134
 135# version of the core git binary
 136our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
 137
 138$projects_list ||= $projectroot;
 139if (! -d $git_temp) {
 140        mkdir($git_temp, 0700) || die_error(undef, "Couldn't mkdir $git_temp");
 141}
 142
 143# ======================================================================
 144# input validation and dispatch
 145our $action = $cgi->param('a');
 146if (defined $action) {
 147        if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
 148                die_error(undef, "Invalid action parameter");
 149        }
 150        # action which does not check rest of parameters
 151        if ($action eq "opml") {
 152                git_opml();
 153                exit;
 154        }
 155}
 156
 157our $project = ($cgi->param('p') || $ENV{'PATH_INFO'});
 158if (defined $project) {
 159        $project =~ s|^/||;
 160        $project =~ s|/$||;
 161        $project = undef unless $project;
 162}
 163if (defined $project) {
 164        if (!validate_input($project)) {
 165                die_error(undef, "Invalid project parameter");
 166        }
 167        if (!(-d "$projectroot/$project")) {
 168                die_error(undef, "No such directory");
 169        }
 170        if (!(-e "$projectroot/$project/HEAD")) {
 171                die_error(undef, "No such project");
 172        }
 173        $ENV{'GIT_DIR'} = "$projectroot/$project";
 174} else {
 175        git_project_list();
 176        exit;
 177}
 178
 179our $file_name = $cgi->param('f');
 180if (defined $file_name) {
 181        if (!validate_input($file_name)) {
 182                die_error(undef, "Invalid file parameter");
 183        }
 184}
 185
 186our $file_parent = $cgi->param('fp');
 187if (defined $file_parent) {
 188        if (!validate_input($file_parent)) {
 189                die_error(undef, "Invalid file parent parameter");
 190        }
 191}
 192
 193our $hash = $cgi->param('h');
 194if (defined $hash) {
 195        if (!validate_input($hash)) {
 196                die_error(undef, "Invalid hash parameter");
 197        }
 198}
 199
 200our $hash_parent = $cgi->param('hp');
 201if (defined $hash_parent) {
 202        if (!validate_input($hash_parent)) {
 203                die_error(undef, "Invalid hash parent parameter");
 204        }
 205}
 206
 207our $hash_base = $cgi->param('hb');
 208if (defined $hash_base) {
 209        if (!validate_input($hash_base)) {
 210                die_error(undef, "Invalid hash base parameter");
 211        }
 212}
 213
 214our $page = $cgi->param('pg');
 215if (defined $page) {
 216        if ($page =~ m/[^0-9]$/) {
 217                die_error(undef, "Invalid page parameter");
 218        }
 219}
 220
 221our $searchtext = $cgi->param('s');
 222if (defined $searchtext) {
 223        if ($searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
 224                die_error(undef, "Invalid search parameter");
 225        }
 226        $searchtext = quotemeta $searchtext;
 227}
 228
 229# dispatch
 230my %actions = (
 231        "blame" => \&git_blame2,
 232        "blobdiff" => \&git_blobdiff,
 233        "blobdiff_plain" => \&git_blobdiff_plain,
 234        "blob" => \&git_blob,
 235        "blob_plain" => \&git_blob_plain,
 236        "commitdiff" => \&git_commitdiff,
 237        "commitdiff_plain" => \&git_commitdiff_plain,
 238        "commit" => \&git_commit,
 239        "heads" => \&git_heads,
 240        "history" => \&git_history,
 241        "log" => \&git_log,
 242        "rss" => \&git_rss,
 243        "search" => \&git_search,
 244        "shortlog" => \&git_shortlog,
 245        "summary" => \&git_summary,
 246        "tag" => \&git_tag,
 247        "tags" => \&git_tags,
 248        "tree" => \&git_tree,
 249        "snapshot" => \&git_snapshot,
 250);
 251
 252$action = 'summary' if (!defined($action));
 253if (!defined($actions{$action})) {
 254        die_error(undef, "Unknown action");
 255}
 256$actions{$action}->();
 257exit;
 258
 259## ======================================================================
 260## action links
 261
 262sub href(%) {
 263        my %mapping = (
 264                action => "a",
 265                project => "p",
 266                file_name => "f",
 267                file_parent => "fp",
 268                hash => "h",
 269                hash_parent => "hp",
 270                hash_base => "hb",
 271                page => "pg",
 272                searchtext => "s",
 273        );
 274
 275        my %params = @_;
 276        $params{"project"} ||= $project;
 277
 278        my $href = "$my_uri?";
 279        $href .= esc_param( join(";",
 280                map {
 281                        "$mapping{$_}=$params{$_}" if defined $params{$_}
 282                } keys %params
 283        ) );
 284
 285        return $href;
 286}
 287
 288
 289## ======================================================================
 290## validation, quoting/unquoting and escaping
 291
 292sub validate_input {
 293        my $input = shift;
 294
 295        if ($input =~ m/^[0-9a-fA-F]{40}$/) {
 296                return $input;
 297        }
 298        if ($input =~ m/(^|\/)(|\.|\.\.)($|\/)/) {
 299                return undef;
 300        }
 301        if ($input =~ m/[^a-zA-Z0-9_\x80-\xff\ \t\.\/\-\+\#\~\%]/) {
 302                return undef;
 303        }
 304        return $input;
 305}
 306
 307# quote unsafe chars, but keep the slash, even when it's not
 308# correct, but quoted slashes look too horrible in bookmarks
 309sub esc_param {
 310        my $str = shift;
 311        $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
 312        $str =~ s/\+/%2B/g;
 313        $str =~ s/ /\+/g;
 314        return $str;
 315}
 316
 317# replace invalid utf8 character with SUBSTITUTION sequence
 318sub esc_html {
 319        my $str = shift;
 320        $str = decode("utf8", $str, Encode::FB_DEFAULT);
 321        $str = escapeHTML($str);
 322        $str =~ s/\014/^L/g; # escape FORM FEED (FF) character (e.g. in COPYING file)
 323        return $str;
 324}
 325
 326# git may return quoted and escaped filenames
 327sub unquote {
 328        my $str = shift;
 329        if ($str =~ m/^"(.*)"$/) {
 330                $str = $1;
 331                $str =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
 332        }
 333        return $str;
 334}
 335
 336# escape tabs (convert tabs to spaces)
 337sub untabify {
 338        my $line = shift;
 339
 340        while ((my $pos = index($line, "\t")) != -1) {
 341                if (my $count = (8 - ($pos % 8))) {
 342                        my $spaces = ' ' x $count;
 343                        $line =~ s/\t/$spaces/;
 344                }
 345        }
 346
 347        return $line;
 348}
 349
 350## ----------------------------------------------------------------------
 351## HTML aware string manipulation
 352
 353sub chop_str {
 354        my $str = shift;
 355        my $len = shift;
 356        my $add_len = shift || 10;
 357
 358        # allow only $len chars, but don't cut a word if it would fit in $add_len
 359        # if it doesn't fit, cut it if it's still longer than the dots we would add
 360        $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
 361        my $body = $1;
 362        my $tail = $2;
 363        if (length($tail) > 4) {
 364                $tail = " ...";
 365                $body =~ s/&[^;]*$//; # remove chopped character entities
 366        }
 367        return "$body$tail";
 368}
 369
 370## ----------------------------------------------------------------------
 371## functions returning short strings
 372
 373# CSS class for given age value (in seconds)
 374sub age_class {
 375        my $age = shift;
 376
 377        if ($age < 60*60*2) {
 378                return "age0";
 379        } elsif ($age < 60*60*24*2) {
 380                return "age1";
 381        } else {
 382                return "age2";
 383        }
 384}
 385
 386# convert age in seconds to "nn units ago" string
 387sub age_string {
 388        my $age = shift;
 389        my $age_str;
 390
 391        if ($age > 60*60*24*365*2) {
 392                $age_str = (int $age/60/60/24/365);
 393                $age_str .= " years ago";
 394        } elsif ($age > 60*60*24*(365/12)*2) {
 395                $age_str = int $age/60/60/24/(365/12);
 396                $age_str .= " months ago";
 397        } elsif ($age > 60*60*24*7*2) {
 398                $age_str = int $age/60/60/24/7;
 399                $age_str .= " weeks ago";
 400        } elsif ($age > 60*60*24*2) {
 401                $age_str = int $age/60/60/24;
 402                $age_str .= " days ago";
 403        } elsif ($age > 60*60*2) {
 404                $age_str = int $age/60/60;
 405                $age_str .= " hours ago";
 406        } elsif ($age > 60*2) {
 407                $age_str = int $age/60;
 408                $age_str .= " min ago";
 409        } elsif ($age > 2) {
 410                $age_str = int $age;
 411                $age_str .= " sec ago";
 412        } else {
 413                $age_str .= " right now";
 414        }
 415        return $age_str;
 416}
 417
 418# convert file mode in octal to symbolic file mode string
 419sub mode_str {
 420        my $mode = oct shift;
 421
 422        if (S_ISDIR($mode & S_IFMT)) {
 423                return 'drwxr-xr-x';
 424        } elsif (S_ISLNK($mode)) {
 425                return 'lrwxrwxrwx';
 426        } elsif (S_ISREG($mode)) {
 427                # git cares only about the executable bit
 428                if ($mode & S_IXUSR) {
 429                        return '-rwxr-xr-x';
 430                } else {
 431                        return '-rw-r--r--';
 432                };
 433        } else {
 434                return '----------';
 435        }
 436}
 437
 438# convert file mode in octal to file type string
 439sub file_type {
 440        my $mode = oct shift;
 441
 442        if (S_ISDIR($mode & S_IFMT)) {
 443                return "directory";
 444        } elsif (S_ISLNK($mode)) {
 445                return "symlink";
 446        } elsif (S_ISREG($mode)) {
 447                return "file";
 448        } else {
 449                return "unknown";
 450        }
 451}
 452
 453## ----------------------------------------------------------------------
 454## functions returning short HTML fragments, or transforming HTML fragments
 455## which don't beling to other sections
 456
 457# format line of commit message or tag comment
 458sub format_log_line_html {
 459        my $line = shift;
 460
 461        $line = esc_html($line);
 462        $line =~ s/ /&nbsp;/g;
 463        if ($line =~ m/([0-9a-fA-F]{40})/) {
 464                my $hash_text = $1;
 465                if (git_get_type($hash_text) eq "commit") {
 466                        my $link = $cgi->a({-class => "text", -href => href(action=>"commit", hash=>$hash_text)}, $hash_text);
 467                        $line =~ s/$hash_text/$link/;
 468                }
 469        }
 470        return $line;
 471}
 472
 473# format marker of refs pointing to given object
 474sub format_ref_marker {
 475        my ($refs, $id) = @_;
 476        my $markers = '';
 477
 478        if (defined $refs->{$id}) {
 479                foreach my $ref (@{$refs->{$id}}) {
 480                        my ($type, $name) = qw();
 481                        # e.g. tags/v2.6.11 or heads/next
 482                        if ($ref =~ m!^(.*?)s?/(.*)$!) {
 483                                $type = $1;
 484                                $name = $2;
 485                        } else {
 486                                $type = "ref";
 487                                $name = $ref;
 488                        }
 489
 490                        $markers .= " <span class=\"$type\">" . esc_html($name) . "</span>";
 491                }
 492        }
 493
 494        if ($markers) {
 495                return ' <span class="refs">'. $markers . '</span>';
 496        } else {
 497                return "";
 498        }
 499}
 500
 501# format, perhaps shortened and with markers, title line
 502sub format_subject_html {
 503        my ($long, $short, $href, $extra) = @_;
 504        $extra = '' unless defined($extra);
 505
 506        if (length($short) < length($long)) {
 507                return $cgi->a({-href => $href, -class => "list",
 508                                -title => $long},
 509                       esc_html($short) . $extra);
 510        } else {
 511                return $cgi->a({-href => $href, -class => "list"},
 512                       esc_html($long)  . $extra);
 513        }
 514}
 515
 516## ----------------------------------------------------------------------
 517## git utility subroutines, invoking git commands
 518
 519# get HEAD ref of given project as hash
 520sub git_get_head_hash {
 521        my $project = shift;
 522        my $oENV = $ENV{'GIT_DIR'};
 523        my $retval = undef;
 524        $ENV{'GIT_DIR'} = "$projectroot/$project";
 525        if (open my $fd, "-|", $GIT, "rev-parse", "--verify", "HEAD") {
 526                my $head = <$fd>;
 527                close $fd;
 528                if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
 529                        $retval = $1;
 530                }
 531        }
 532        if (defined $oENV) {
 533                $ENV{'GIT_DIR'} = $oENV;
 534        }
 535        return $retval;
 536}
 537
 538# get type of given object
 539sub git_get_type {
 540        my $hash = shift;
 541
 542        open my $fd, "-|", $GIT, "cat-file", '-t', $hash or return;
 543        my $type = <$fd>;
 544        close $fd or return;
 545        chomp $type;
 546        return $type;
 547}
 548
 549sub git_get_project_config {
 550        my ($key, $type) = @_;
 551
 552        return unless ($key);
 553        $key =~ s/^gitweb\.//;
 554        return if ($key =~ m/\W/);
 555
 556        my @x = ($GIT, 'repo-config');
 557        if (defined $type) { push @x, $type; }
 558        push @x, "--get";
 559        push @x, "gitweb.$key";
 560        my $val = qx(@x);
 561        chomp $val;
 562        return ($val);
 563}
 564
 565# get hash of given path at given ref
 566sub git_get_hash_by_path {
 567        my $base = shift;
 568        my $path = shift || return undef;
 569
 570        my $tree = $base;
 571
 572        open my $fd, "-|", $GIT, "ls-tree", $base, "--", $path
 573                or die_error(undef, "Open git-ls-tree failed");
 574        my $line = <$fd>;
 575        close $fd or return undef;
 576
 577        #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
 578        $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
 579        return $3;
 580}
 581
 582## ......................................................................
 583## git utility functions, directly accessing git repository
 584
 585# assumes that PATH is not symref
 586sub git_get_hash_by_ref {
 587        my $path = shift;
 588
 589        open my $fd, "$projectroot/$path" or return undef;
 590        my $head = <$fd>;
 591        close $fd;
 592        chomp $head;
 593        if ($head =~ m/^[0-9a-fA-F]{40}$/) {
 594                return $head;
 595        }
 596}
 597
 598sub git_get_project_description {
 599        my $path = shift;
 600
 601        open my $fd, "$projectroot/$path/description" or return undef;
 602        my $descr = <$fd>;
 603        close $fd;
 604        chomp $descr;
 605        return $descr;
 606}
 607
 608sub git_get_project_url_list {
 609        my $path = shift;
 610
 611        open my $fd, "$projectroot/$path/cloneurl" or return undef;
 612        my @git_project_url_list = map { chomp; $_ } <$fd>;
 613        close $fd;
 614
 615        return wantarray ? @git_project_url_list : \@git_project_url_list;
 616}
 617
 618sub git_get_projects_list {
 619        my @list;
 620
 621        if (-d $projects_list) {
 622                # search in directory
 623                my $dir = $projects_list;
 624                opendir my ($dh), $dir or return undef;
 625                while (my $dir = readdir($dh)) {
 626                        if (-e "$projectroot/$dir/HEAD") {
 627                                my $pr = {
 628                                        path => $dir,
 629                                };
 630                                push @list, $pr
 631                        }
 632                }
 633                closedir($dh);
 634        } elsif (-f $projects_list) {
 635                # read from file(url-encoded):
 636                # 'git%2Fgit.git Linus+Torvalds'
 637                # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
 638                # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
 639                open my ($fd), $projects_list or return undef;
 640                while (my $line = <$fd>) {
 641                        chomp $line;
 642                        my ($path, $owner) = split ' ', $line;
 643                        $path = unescape($path);
 644                        $owner = unescape($owner);
 645                        if (!defined $path) {
 646                                next;
 647                        }
 648                        if (-e "$projectroot/$path/HEAD") {
 649                                my $pr = {
 650                                        path => $path,
 651                                        owner => decode("utf8", $owner, Encode::FB_DEFAULT),
 652                                };
 653                                push @list, $pr
 654                        }
 655                }
 656                close $fd;
 657        }
 658        @list = sort {$a->{'path'} cmp $b->{'path'}} @list;
 659        return @list;
 660}
 661
 662sub git_get_project_owner {
 663        my $project = shift;
 664        my $owner;
 665
 666        return undef unless $project;
 667
 668        # read from file (url-encoded):
 669        # 'git%2Fgit.git Linus+Torvalds'
 670        # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
 671        # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
 672        if (-f $projects_list) {
 673                open (my $fd , $projects_list);
 674                while (my $line = <$fd>) {
 675                        chomp $line;
 676                        my ($pr, $ow) = split ' ', $line;
 677                        $pr = unescape($pr);
 678                        $ow = unescape($ow);
 679                        if ($pr eq $project) {
 680                                $owner = decode("utf8", $ow, Encode::FB_DEFAULT);
 681                                last;
 682                        }
 683                }
 684                close $fd;
 685        }
 686        if (!defined $owner) {
 687                $owner = get_file_owner("$projectroot/$project");
 688        }
 689
 690        return $owner;
 691}
 692
 693sub git_get_references {
 694        my $type = shift || "";
 695        my %refs;
 696        my $fd;
 697        # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c      refs/tags/v2.6.11
 698        # c39ae07f393806ccf406ef966e9a15afc43cc36a      refs/tags/v2.6.11^{}
 699        if (-f "$projectroot/$project/info/refs") {
 700                open $fd, "$projectroot/$project/info/refs"
 701                        or return;
 702        } else {
 703                open $fd, "-|", $GIT, "ls-remote", "."
 704                        or return;
 705        }
 706
 707        while (my $line = <$fd>) {
 708                chomp $line;
 709                if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?[^\^]+)/) {
 710                        if (defined $refs{$1}) {
 711                                push @{$refs{$1}}, $2;
 712                        } else {
 713                                $refs{$1} = [ $2 ];
 714                        }
 715                }
 716        }
 717        close $fd or return;
 718        return \%refs;
 719}
 720
 721## ----------------------------------------------------------------------
 722## parse to hash functions
 723
 724sub parse_date {
 725        my $epoch = shift;
 726        my $tz = shift || "-0000";
 727
 728        my %date;
 729        my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
 730        my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
 731        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
 732        $date{'hour'} = $hour;
 733        $date{'minute'} = $min;
 734        $date{'mday'} = $mday;
 735        $date{'day'} = $days[$wday];
 736        $date{'month'} = $months[$mon];
 737        $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000", $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
 738        $date{'mday-time'} = sprintf "%d %s %02d:%02d", $mday, $months[$mon], $hour ,$min;
 739
 740        $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
 741        my $local = $epoch + ((int $1 + ($2/60)) * 3600);
 742        ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
 743        $date{'hour_local'} = $hour;
 744        $date{'minute_local'} = $min;
 745        $date{'tz_local'} = $tz;
 746        return %date;
 747}
 748
 749sub parse_tag {
 750        my $tag_id = shift;
 751        my %tag;
 752        my @comment;
 753
 754        open my $fd, "-|", $GIT, "cat-file", "tag", $tag_id or return;
 755        $tag{'id'} = $tag_id;
 756        while (my $line = <$fd>) {
 757                chomp $line;
 758                if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
 759                        $tag{'object'} = $1;
 760                } elsif ($line =~ m/^type (.+)$/) {
 761                        $tag{'type'} = $1;
 762                } elsif ($line =~ m/^tag (.+)$/) {
 763                        $tag{'name'} = $1;
 764                } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
 765                        $tag{'author'} = $1;
 766                        $tag{'epoch'} = $2;
 767                        $tag{'tz'} = $3;
 768                } elsif ($line =~ m/--BEGIN/) {
 769                        push @comment, $line;
 770                        last;
 771                } elsif ($line eq "") {
 772                        last;
 773                }
 774        }
 775        push @comment, <$fd>;
 776        $tag{'comment'} = \@comment;
 777        close $fd or return;
 778        if (!defined $tag{'name'}) {
 779                return
 780        };
 781        return %tag
 782}
 783
 784sub parse_commit {
 785        my $commit_id = shift;
 786        my $commit_text = shift;
 787
 788        my @commit_lines;
 789        my %co;
 790
 791        if (defined $commit_text) {
 792                @commit_lines = @$commit_text;
 793        } else {
 794                $/ = "\0";
 795                open my $fd, "-|", $GIT, "rev-list", "--header", "--parents", "--max-count=1", $commit_id or return;
 796                @commit_lines = split '\n', <$fd>;
 797                close $fd or return;
 798                $/ = "\n";
 799                pop @commit_lines;
 800        }
 801        my $header = shift @commit_lines;
 802        if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
 803                return;
 804        }
 805        ($co{'id'}, my @parents) = split ' ', $header;
 806        $co{'parents'} = \@parents;
 807        $co{'parent'} = $parents[0];
 808        while (my $line = shift @commit_lines) {
 809                last if $line eq "\n";
 810                if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
 811                        $co{'tree'} = $1;
 812                } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
 813                        $co{'author'} = $1;
 814                        $co{'author_epoch'} = $2;
 815                        $co{'author_tz'} = $3;
 816                        if ($co{'author'} =~ m/^([^<]+) </) {
 817                                $co{'author_name'} = $1;
 818                        } else {
 819                                $co{'author_name'} = $co{'author'};
 820                        }
 821                } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
 822                        $co{'committer'} = $1;
 823                        $co{'committer_epoch'} = $2;
 824                        $co{'committer_tz'} = $3;
 825                        $co{'committer_name'} = $co{'committer'};
 826                        $co{'committer_name'} =~ s/ <.*//;
 827                }
 828        }
 829        if (!defined $co{'tree'}) {
 830                return;
 831        };
 832
 833        foreach my $title (@commit_lines) {
 834                $title =~ s/^    //;
 835                if ($title ne "") {
 836                        $co{'title'} = chop_str($title, 80, 5);
 837                        # remove leading stuff of merges to make the interesting part visible
 838                        if (length($title) > 50) {
 839                                $title =~ s/^Automatic //;
 840                                $title =~ s/^merge (of|with) /Merge ... /i;
 841                                if (length($title) > 50) {
 842                                        $title =~ s/(http|rsync):\/\///;
 843                                }
 844                                if (length($title) > 50) {
 845                                        $title =~ s/(master|www|rsync)\.//;
 846                                }
 847                                if (length($title) > 50) {
 848                                        $title =~ s/kernel.org:?//;
 849                                }
 850                                if (length($title) > 50) {
 851                                        $title =~ s/\/pub\/scm//;
 852                                }
 853                        }
 854                        $co{'title_short'} = chop_str($title, 50, 5);
 855                        last;
 856                }
 857        }
 858        # remove added spaces
 859        foreach my $line (@commit_lines) {
 860                $line =~ s/^    //;
 861        }
 862        $co{'comment'} = \@commit_lines;
 863
 864        my $age = time - $co{'committer_epoch'};
 865        $co{'age'} = $age;
 866        $co{'age_string'} = age_string($age);
 867        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
 868        if ($age > 60*60*24*7*2) {
 869                $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
 870                $co{'age_string_age'} = $co{'age_string'};
 871        } else {
 872                $co{'age_string_date'} = $co{'age_string'};
 873                $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
 874        }
 875        return %co;
 876}
 877
 878# parse ref from ref_file, given by ref_id, with given type
 879sub parse_ref {
 880        my $ref_file = shift;
 881        my $ref_id = shift;
 882        my $type = shift || git_get_type($ref_id);
 883        my %ref_item;
 884
 885        $ref_item{'type'} = $type;
 886        $ref_item{'id'} = $ref_id;
 887        $ref_item{'epoch'} = 0;
 888        $ref_item{'age'} = "unknown";
 889        if ($type eq "tag") {
 890                my %tag = parse_tag($ref_id);
 891                $ref_item{'comment'} = $tag{'comment'};
 892                if ($tag{'type'} eq "commit") {
 893                        my %co = parse_commit($tag{'object'});
 894                        $ref_item{'epoch'} = $co{'committer_epoch'};
 895                        $ref_item{'age'} = $co{'age_string'};
 896                } elsif (defined($tag{'epoch'})) {
 897                        my $age = time - $tag{'epoch'};
 898                        $ref_item{'epoch'} = $tag{'epoch'};
 899                        $ref_item{'age'} = age_string($age);
 900                }
 901                $ref_item{'reftype'} = $tag{'type'};
 902                $ref_item{'name'} = $tag{'name'};
 903                $ref_item{'refid'} = $tag{'object'};
 904        } elsif ($type eq "commit"){
 905                my %co = parse_commit($ref_id);
 906                $ref_item{'reftype'} = "commit";
 907                $ref_item{'name'} = $ref_file;
 908                $ref_item{'title'} = $co{'title'};
 909                $ref_item{'refid'} = $ref_id;
 910                $ref_item{'epoch'} = $co{'committer_epoch'};
 911                $ref_item{'age'} = $co{'age_string'};
 912        } else {
 913                $ref_item{'reftype'} = $type;
 914                $ref_item{'name'} = $ref_file;
 915                $ref_item{'refid'} = $ref_id;
 916        }
 917
 918        return %ref_item;
 919}
 920
 921# parse line of git-diff-tree "raw" output
 922sub parse_difftree_raw_line {
 923        my $line = shift;
 924        my %res;
 925
 926        # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
 927        # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
 928        if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
 929                $res{'from_mode'} = $1;
 930                $res{'to_mode'} = $2;
 931                $res{'from_id'} = $3;
 932                $res{'to_id'} = $4;
 933                $res{'status'} = $5;
 934                $res{'similarity'} = $6;
 935                if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
 936                        ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
 937                } else {
 938                        $res{'file'} = unquote($7);
 939                }
 940        }
 941        # 'c512b523472485aef4fff9e57b229d9d243c967f'
 942        #elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
 943        #       $res{'commit'} = $1;
 944        #}
 945
 946        return wantarray ? %res : \%res;
 947}
 948
 949## ......................................................................
 950## parse to array of hashes functions
 951
 952sub git_get_refs_list {
 953        my $ref_dir = shift;
 954        my @reflist;
 955
 956        my @refs;
 957        my $pfxlen = length("$projectroot/$project/$ref_dir");
 958        File::Find::find(sub {
 959                return if (/^\./);
 960                if (-f $_) {
 961                        push @refs, substr($File::Find::name, $pfxlen + 1);
 962                }
 963        }, "$projectroot/$project/$ref_dir");
 964
 965        foreach my $ref_file (@refs) {
 966                my $ref_id = git_get_hash_by_ref("$project/$ref_dir/$ref_file");
 967                my $type = git_get_type($ref_id) || next;
 968                my %ref_item = parse_ref($ref_file, $ref_id, $type);
 969
 970                push @reflist, \%ref_item;
 971        }
 972        # sort refs by age
 973        @reflist = sort {$b->{'epoch'} <=> $a->{'epoch'}} @reflist;
 974        return \@reflist;
 975}
 976
 977## ----------------------------------------------------------------------
 978## filesystem-related functions
 979
 980sub get_file_owner {
 981        my $path = shift;
 982
 983        my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
 984        my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
 985        if (!defined $gcos) {
 986                return undef;
 987        }
 988        my $owner = $gcos;
 989        $owner =~ s/[,;].*$//;
 990        return decode("utf8", $owner, Encode::FB_DEFAULT);
 991}
 992
 993## ......................................................................
 994## mimetype related functions
 995
 996sub mimetype_guess_file {
 997        my $filename = shift;
 998        my $mimemap = shift;
 999        -r $mimemap or return undef;
1000
1001        my %mimemap;
1002        open(MIME, $mimemap) or return undef;
1003        while (<MIME>) {
1004                next if m/^#/; # skip comments
1005                my ($mime, $exts) = split(/\t+/);
1006                if (defined $exts) {
1007                        my @exts = split(/\s+/, $exts);
1008                        foreach my $ext (@exts) {
1009                                $mimemap{$ext} = $mime;
1010                        }
1011                }
1012        }
1013        close(MIME);
1014
1015        $filename =~ /\.(.*?)$/;
1016        return $mimemap{$1};
1017}
1018
1019sub mimetype_guess {
1020        my $filename = shift;
1021        my $mime;
1022        $filename =~ /\./ or return undef;
1023
1024        if ($mimetypes_file) {
1025                my $file = $mimetypes_file;
1026                if ($file !~ m!^/!) { # if it is relative path
1027                        # it is relative to project
1028                        $file = "$projectroot/$project/$file";
1029                }
1030                $mime = mimetype_guess_file($filename, $file);
1031        }
1032        $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1033        return $mime;
1034}
1035
1036sub blob_mimetype {
1037        my $fd = shift;
1038        my $filename = shift;
1039
1040        if ($filename) {
1041                my $mime = mimetype_guess($filename);
1042                $mime and return $mime;
1043        }
1044
1045        # just in case
1046        return $default_blob_plain_mimetype unless $fd;
1047
1048        if (-T $fd) {
1049                return 'text/plain' .
1050                       ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1051        } elsif (! $filename) {
1052                return 'application/octet-stream';
1053        } elsif ($filename =~ m/\.png$/i) {
1054                return 'image/png';
1055        } elsif ($filename =~ m/\.gif$/i) {
1056                return 'image/gif';
1057        } elsif ($filename =~ m/\.jpe?g$/i) {
1058                return 'image/jpeg';
1059        } else {
1060                return 'application/octet-stream';
1061        }
1062}
1063
1064## ======================================================================
1065## functions printing HTML: header, footer, error page
1066
1067sub git_header_html {
1068        my $status = shift || "200 OK";
1069        my $expires = shift;
1070
1071        my $title = "$site_name git";
1072        if (defined $project) {
1073                $title .= " - $project";
1074                if (defined $action) {
1075                        $title .= "/$action";
1076                        if (defined $file_name) {
1077                                $title .= " - $file_name";
1078                                if ($action eq "tree" && $file_name !~ m|/$|) {
1079                                        $title .= "/";
1080                                }
1081                        }
1082                }
1083        }
1084        my $content_type;
1085        # require explicit support from the UA if we are to send the page as
1086        # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1087        # we have to do this because MSIE sometimes globs '*/*', pretending to
1088        # support xhtml+xml but choking when it gets what it asked for.
1089        if (defined $cgi->http('HTTP_ACCEPT') && $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ && $cgi->Accept('application/xhtml+xml') != 0) {
1090                $content_type = 'application/xhtml+xml';
1091        } else {
1092                $content_type = 'text/html';
1093        }
1094        print $cgi->header(-type=>$content_type, -charset => 'utf-8', -status=> $status, -expires => $expires);
1095        print <<EOF;
1096<?xml version="1.0" encoding="utf-8"?>
1097<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1098<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1099<!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1100<!-- git core binaries version $git_version -->
1101<head>
1102<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1103<meta name="generator" content="gitweb/$version git/$git_version"/>
1104<meta name="robots" content="index, nofollow"/>
1105<title>$title</title>
1106<link rel="stylesheet" type="text/css" href="$stylesheet"/>
1107EOF
1108        if (defined $project) {
1109                printf('<link rel="alternate" title="%s log" '.
1110                       'href="%s" type="application/rss+xml"/>'."\n",
1111                       esc_param($project), href(action=>"rss"));
1112        }
1113
1114        print "</head>\n" .
1115              "<body>\n" .
1116              "<div class=\"page_header\">\n" .
1117              "<a href=\"http://www.kernel.org/pub/software/scm/git/docs/\" title=\"git documentation\">" .
1118              "<img src=\"$logo\" width=\"72\" height=\"27\" alt=\"git\" style=\"float:right; border-width:0px;\"/>" .
1119              "</a>\n";
1120        print $cgi->a({-href => esc_param($home_link)}, $home_link_str) . " / ";
1121        if (defined $project) {
1122                print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1123                if (defined $action) {
1124                        print " / $action";
1125                }
1126                print "\n";
1127                if (!defined $searchtext) {
1128                        $searchtext = "";
1129                }
1130                my $search_hash;
1131                if (defined $hash_base) {
1132                        $search_hash = $hash_base;
1133                } elsif (defined $hash) {
1134                        $search_hash = $hash;
1135                } else {
1136                        $search_hash = "HEAD";
1137                }
1138                $cgi->param("a", "search");
1139                $cgi->param("h", $search_hash);
1140                print $cgi->startform(-method => "get", -action => $my_uri) .
1141                      "<div class=\"search\">\n" .
1142                      $cgi->hidden(-name => "p") . "\n" .
1143                      $cgi->hidden(-name => "a") . "\n" .
1144                      $cgi->hidden(-name => "h") . "\n" .
1145                      $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1146                      "</div>" .
1147                      $cgi->end_form() . "\n";
1148        }
1149        print "</div>\n";
1150}
1151
1152sub git_footer_html {
1153        print "<div class=\"page_footer\">\n";
1154        if (defined $project) {
1155                my $descr = git_get_project_description($project);
1156                if (defined $descr) {
1157                        print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1158                }
1159                print $cgi->a({-href => href(action=>"rss"), -class => "rss_logo"}, "RSS") . "\n";
1160        } else {
1161                print $cgi->a({-href => href(action=>"opml"), -class => "rss_logo"}, "OPML") . "\n";
1162        }
1163        print "</div>\n" .
1164              "</body>\n" .
1165              "</html>";
1166}
1167
1168sub die_error {
1169        my $status = shift || "403 Forbidden";
1170        my $error = shift || "Malformed query, file missing or permission denied";
1171
1172        git_header_html($status);
1173        print "<div class=\"page_body\">\n" .
1174              "<br/><br/>\n" .
1175              "$status - $error\n" .
1176              "<br/>\n" .
1177              "</div>\n";
1178        git_footer_html();
1179        exit;
1180}
1181
1182## ----------------------------------------------------------------------
1183## functions printing or outputting HTML: navigation
1184
1185sub git_print_page_nav {
1186        my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1187        $extra = '' if !defined $extra; # pager or formats
1188
1189        my @navs = qw(summary shortlog log commit commitdiff tree);
1190        if ($suppress) {
1191                @navs = grep { $_ ne $suppress } @navs;
1192        }
1193
1194        my %arg = map { $_ => {action=>$_} } @navs;
1195        if (defined $head) {
1196                for (qw(commit commitdiff)) {
1197                        $arg{$_}{hash} = $head;
1198                }
1199                if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1200                        for (qw(shortlog log)) {
1201                                $arg{$_}{hash} = $head;
1202                        }
1203                }
1204        }
1205        $arg{tree}{hash} = $treehead if defined $treehead;
1206        $arg{tree}{hash_base} = $treebase if defined $treebase;
1207
1208        print "<div class=\"page_nav\">\n" .
1209                (join " | ",
1210                 map { $_ eq $current ?
1211                       $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1212                 } @navs);
1213        print "<br/>\n$extra<br/>\n" .
1214              "</div>\n";
1215}
1216
1217sub format_paging_nav {
1218        my ($action, $hash, $head, $page, $nrevs) = @_;
1219        my $paging_nav;
1220
1221
1222        if ($hash ne $head || $page) {
1223                $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1224        } else {
1225                $paging_nav .= "HEAD";
1226        }
1227
1228        if ($page > 0) {
1229                $paging_nav .= " &sdot; " .
1230                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1231                                 -accesskey => "p", -title => "Alt-p"}, "prev");
1232        } else {
1233                $paging_nav .= " &sdot; prev";
1234        }
1235
1236        if ($nrevs >= (100 * ($page+1)-1)) {
1237                $paging_nav .= " &sdot; " .
1238                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1239                                 -accesskey => "n", -title => "Alt-n"}, "next");
1240        } else {
1241                $paging_nav .= " &sdot; next";
1242        }
1243
1244        return $paging_nav;
1245}
1246
1247## ......................................................................
1248## functions printing or outputting HTML: div
1249
1250sub git_print_header_div {
1251        my ($action, $title, $hash, $hash_base) = @_;
1252        my %args = ();
1253
1254        $args{action} = $action;
1255        $args{hash} = $hash if $hash;
1256        $args{hash_base} = $hash_base if $hash_base;
1257
1258        print "<div class=\"header\">\n" .
1259              $cgi->a({-href => href(%args), -class => "title"},
1260              $title ? $title : $action) .
1261              "\n</div>\n";
1262}
1263
1264sub git_print_page_path {
1265        my $name = shift;
1266        my $type = shift;
1267        my $hb = shift;
1268
1269        if (!defined $name) {
1270                print "<div class=\"page_path\"><b>/</b></div>\n";
1271        } elsif (defined $type && $type eq 'blob') {
1272                print "<div class=\"page_path\"><b>";
1273                if (defined $hb) {
1274                        print $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hb, file_name=>$file_name)}, esc_html($name));
1275                } else {
1276                        print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name)}, esc_html($name));
1277                }
1278                print "</b><br/></div>\n";
1279        } else {
1280                print "<div class=\"page_path\"><b>" . esc_html($name) . "</b><br/></div>\n";
1281        }
1282}
1283
1284sub git_print_log {
1285        my $log = shift;
1286
1287        # remove leading empty lines
1288        while (defined $log->[0] && $log->[0] eq "") {
1289                shift @$log;
1290        }
1291
1292        # print log
1293        my $signoff = 0;
1294        my $empty = 0;
1295        foreach my $line (@$log) {
1296                # print only one empty line
1297                # do not print empty line after signoff
1298                if ($line eq "") {
1299                        next if ($empty || $signoff);
1300                        $empty = 1;
1301                } else {
1302                        $empty = 0;
1303                }
1304                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1305                        $signoff = 1;
1306                        print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1307                } else {
1308                        $signoff = 0;
1309                        print format_log_line_html($line) . "<br/>\n";
1310                }
1311        }
1312}
1313
1314sub git_print_simplified_log {
1315        my $log = shift;
1316        my $remove_title = shift;
1317
1318        shift @$log if $remove_title;
1319        # remove leading empty lines
1320        while (defined $log->[0] && $log->[0] eq "") {
1321                shift @$log;
1322        }
1323
1324        # simplify and print log
1325        my $empty = 0;
1326        foreach my $line (@$log) {
1327                # remove signoff lines
1328                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1329                        next;
1330                }
1331                # print only one empty line
1332                if ($line eq "") {
1333                        next if $empty;
1334                        $empty = 1;
1335                } else {
1336                        $empty = 0;
1337                }
1338                print format_log_line_html($line) . "<br/>\n";
1339        }
1340        # end with single empty line
1341        print "<br/>\n" unless $empty;
1342}
1343
1344## ......................................................................
1345## functions printing large fragments of HTML
1346
1347sub git_difftree_body {
1348        my ($difftree, $parent) = @_;
1349
1350        print "<div class=\"list_head\">\n";
1351        if ($#{$difftree} > 10) {
1352                print(($#{$difftree} + 1) . " files changed:\n");
1353        }
1354        print "</div>\n";
1355
1356        print "<table class=\"diff_tree\">\n";
1357        my $alternate = 0;
1358        foreach my $line (@{$difftree}) {
1359                my %diff = parse_difftree_raw_line($line);
1360
1361                if ($alternate) {
1362                        print "<tr class=\"dark\">\n";
1363                } else {
1364                        print "<tr class=\"light\">\n";
1365                }
1366                $alternate ^= 1;
1367
1368                my ($to_mode_oct, $to_mode_str, $to_file_type);
1369                my ($from_mode_oct, $from_mode_str, $from_file_type);
1370                if ($diff{'to_mode'} ne ('0' x 6)) {
1371                        $to_mode_oct = oct $diff{'to_mode'};
1372                        if (S_ISREG($to_mode_oct)) { # only for regular file
1373                                $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
1374                        }
1375                        $to_file_type = file_type($diff{'to_mode'});
1376                }
1377                if ($diff{'from_mode'} ne ('0' x 6)) {
1378                        $from_mode_oct = oct $diff{'from_mode'};
1379                        if (S_ISREG($to_mode_oct)) { # only for regular file
1380                                $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
1381                        }
1382                        $from_file_type = file_type($diff{'from_mode'});
1383                }
1384
1385                if ($diff{'status'} eq "A") { # created
1386                        my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
1387                        $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
1388                        $mode_chng   .= "]</span>";
1389                        print "<td>" .
1390                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1391                                                     hash_base=>$hash, file_name=>$diff{'file'}),
1392                                      -class => "list"}, esc_html($diff{'file'})) .
1393                              "</td>\n" .
1394                              "<td>$mode_chng</td>\n" .
1395                              "<td class=\"link\">" .
1396                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1397                                                     hash_base=>$hash, file_name=>$diff{'file'})},
1398                                      "blob") .
1399                              "</td>\n";
1400
1401                } elsif ($diff{'status'} eq "D") { # deleted
1402                        my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
1403                        print "<td>" .
1404                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1405                                                     hash_base=>$parent, file_name=>$diff{'file'}),
1406                                       -class => "list"}, esc_html($diff{'file'})) .
1407                              "</td>\n" .
1408                              "<td>$mode_chng</td>\n" .
1409                              "<td class=\"link\">" .
1410                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1411                                                     hash_base=>$parent, file_name=>$diff{'file'})},
1412                                      "blob") .
1413                              " | " .
1414                              $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1415                                                     file_name=>$diff{'file'})},\
1416                                      "history") .
1417                              "</td>\n";
1418
1419                } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
1420                        my $mode_chnge = "";
1421                        if ($diff{'from_mode'} != $diff{'to_mode'}) {
1422                                $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
1423                                if ($from_file_type != $to_file_type) {
1424                                        $mode_chnge .= " from $from_file_type to $to_file_type";
1425                                }
1426                                if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
1427                                        if ($from_mode_str && $to_mode_str) {
1428                                                $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
1429                                        } elsif ($to_mode_str) {
1430                                                $mode_chnge .= " mode: $to_mode_str";
1431                                        }
1432                                }
1433                                $mode_chnge .= "]</span>\n";
1434                        }
1435                        print "<td>";
1436                        if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1437                                print $cgi->a({-href => href(action=>"blobdiff", hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1438                                                             hash_base=>$hash, file_name=>$diff{'file'}),
1439                                              -class => "list"}, esc_html($diff{'file'}));
1440                        } else { # only mode changed
1441                                print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1442                                                             hash_base=>$hash, file_name=>$diff{'file'}),
1443                                              -class => "list"}, esc_html($diff{'file'}));
1444                        }
1445                        print "</td>\n" .
1446                              "<td>$mode_chnge</td>\n" .
1447                              "<td class=\"link\">" .
1448                                $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1449                                                       hash_base=>$hash, file_name=>$diff{'file'})},
1450                                        "blob");
1451                        if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1452                                print " | " .
1453                                        $cgi->a({-href => href(action=>"blobdiff", hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1454                                                               hash_base=>$hash, file_name=>$diff{'file'})},
1455                                                "diff");
1456                        }
1457                        print " | " .
1458                                $cgi->a({-href => href(action=>"history",
1459                                                       hash_base=>$hash, file_name=>$diff{'file'})},
1460                                        "history");
1461                        print "</td>\n";
1462
1463                } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
1464                        my %status_name = ('R' => 'moved', 'C' => 'copied');
1465                        my $nstatus = $status_name{$diff{'status'}};
1466                        my $mode_chng = "";
1467                        if ($diff{'from_mode'} != $diff{'to_mode'}) {
1468                                # mode also for directories, so we cannot use $to_mode_str
1469                                $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
1470                        }
1471                        print "<td>" .
1472                              $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1473                                                     hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
1474                                      -class => "list"}, esc_html($diff{'to_file'})) . "</td>\n" .
1475                              "<td><span class=\"file_status $nstatus\">[$nstatus from " .
1476                              $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
1477                                                     hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
1478                                      -class => "list"}, esc_html($diff{'from_file'})) .
1479                              " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
1480                              "<td class=\"link\">" .
1481                              $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1482                                                     hash=>$diff{'to_id'}, file_name=>$diff{'to_file'})},
1483                                      "blob");
1484                        if ($diff{'to_id'} ne $diff{'from_id'}) {
1485                                print " | " .
1486                                        $cgi->a({-href => href(action=>"blobdiff", hash_base=>$hash,
1487                                                               hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1488                                                               file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
1489                                                "diff");
1490                        }
1491                        print "</td>\n";
1492
1493                } # we should not encounter Unmerged (U) or Unknown (X) status
1494                print "</tr>\n";
1495        }
1496        print "</table>\n";
1497}
1498
1499sub git_shortlog_body {
1500        # uses global variable $project
1501        my ($revlist, $from, $to, $refs, $extra) = @_;
1502
1503        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
1504        my $have_snapshot = (defined $ctype && defined $suffix);
1505
1506        $from = 0 unless defined $from;
1507        $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
1508
1509        print "<table class=\"shortlog\" cellspacing=\"0\">\n";
1510        my $alternate = 0;
1511        for (my $i = $from; $i <= $to; $i++) {
1512                my $commit = $revlist->[$i];
1513                #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
1514                my $ref = format_ref_marker($refs, $commit);
1515                my %co = parse_commit($commit);
1516                if ($alternate) {
1517                        print "<tr class=\"dark\">\n";
1518                } else {
1519                        print "<tr class=\"light\">\n";
1520                }
1521                $alternate ^= 1;
1522                # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
1523                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1524                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
1525                      "<td>";
1526                print format_subject_html($co{'title'}, $co{'title_short'}, href(action=>"commit", hash=>$commit), $ref);
1527                print "</td>\n" .
1528                      "<td class=\"link\">" .
1529                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1530                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
1531                if ($have_snapshot) {
1532                        print " | " .  $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
1533                }
1534                print "</td>\n" .
1535                      "</tr>\n";
1536        }
1537        if (defined $extra) {
1538                print "<tr>\n" .
1539                      "<td colspan=\"4\">$extra</td>\n" .
1540                      "</tr>\n";
1541        }
1542        print "</table>\n";
1543}
1544
1545sub git_history_body {
1546        # Warning: assumes constant type (blob or tree) during history
1547        my ($fd, $refs, $hash_base, $ftype, $extra) = @_;
1548
1549        print "<table class=\"history\" cellspacing=\"0\">\n";
1550        my $alternate = 0;
1551        while (my $line = <$fd>) {
1552                if ($line !~ m/^([0-9a-fA-F]{40})/) {
1553                        next;
1554                }
1555
1556                my $commit = $1;
1557                my %co = parse_commit($commit);
1558                if (!%co) {
1559                        next;
1560                }
1561
1562                my $ref = format_ref_marker($refs, $commit);
1563
1564                if ($alternate) {
1565                        print "<tr class=\"dark\">\n";
1566                } else {
1567                        print "<tr class=\"light\">\n";
1568                }
1569                $alternate ^= 1;
1570                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1571                      # shortlog uses      chop_str($co{'author_name'}, 10)
1572                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
1573                      "<td>";
1574                # originally git_history used chop_str($co{'title'}, 50)
1575                print format_subject_html($co{'title'}, $co{'title_short'}, href(action=>"commit", hash=>$commit), $ref);
1576                print "</td>\n" .
1577                      "<td class=\"link\">" .
1578                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1579                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
1580                      $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype);
1581
1582                if ($ftype eq 'blob') {
1583                        my $blob_current = git_get_hash_by_path($hash_base, $file_name);
1584                        my $blob_parent  = git_get_hash_by_path($commit, $file_name);
1585                        if (defined $blob_current && defined $blob_parent &&
1586                                        $blob_current ne $blob_parent) {
1587                                print " | " .
1588                                        $cgi->a({-href => href(action=>"blobdiff", hash=>$blob_current, hash_parent=>$blob_parent, hash_base=>$commit, file_name=>$file_name)},
1589                                                "diff to current");
1590                        }
1591                }
1592                print "</td>\n" .
1593                      "</tr>\n";
1594        }
1595        if (defined $extra) {
1596                print "<tr>\n" .
1597                      "<td colspan=\"4\">$extra</td>\n" .
1598                      "</tr>\n";
1599        }
1600        print "</table>\n";
1601}
1602
1603sub git_tags_body {
1604        # uses global variable $project
1605        my ($taglist, $from, $to, $extra) = @_;
1606        $from = 0 unless defined $from;
1607        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
1608
1609        print "<table class=\"tags\" cellspacing=\"0\">\n";
1610        my $alternate = 0;
1611        for (my $i = $from; $i <= $to; $i++) {
1612                my $entry = $taglist->[$i];
1613                my %tag = %$entry;
1614                my $comment_lines = $tag{'comment'};
1615                my $comment = shift @$comment_lines;
1616                my $comment_short;
1617                if (defined $comment) {
1618                        $comment_short = chop_str($comment, 30, 5);
1619                }
1620                if ($alternate) {
1621                        print "<tr class=\"dark\">\n";
1622                } else {
1623                        print "<tr class=\"light\">\n";
1624                }
1625                $alternate ^= 1;
1626                print "<td><i>$tag{'age'}</i></td>\n" .
1627                      "<td>" .
1628                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
1629                               -class => "list"}, "<b>" . esc_html($tag{'name'}) . "</b>") .
1630                      "</td>\n" .
1631                      "<td>";
1632                if (defined $comment) {
1633                        print format_subject_html($comment, $comment_short, href(action=>"tag", hash=>$tag{'id'}));
1634                }
1635                print "</td>\n" .
1636                      "<td class=\"selflink\">";
1637                if ($tag{'type'} eq "tag") {
1638                        print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
1639                } else {
1640                        print "&nbsp;";
1641                }
1642                print "</td>\n" .
1643                      "<td class=\"link\">" . " | " .
1644                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
1645                if ($tag{'reftype'} eq "commit") {
1646                        print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
1647                              " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'refid'})}, "log");
1648                } elsif ($tag{'reftype'} eq "blob") {
1649                        print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
1650                }
1651                print "</td>\n" .
1652                      "</tr>";
1653        }
1654        if (defined $extra) {
1655                print "<tr>\n" .
1656                      "<td colspan=\"5\">$extra</td>\n" .
1657                      "</tr>\n";
1658        }
1659        print "</table>\n";
1660}
1661
1662sub git_heads_body {
1663        # uses global variable $project
1664        my ($taglist, $head, $from, $to, $extra) = @_;
1665        $from = 0 unless defined $from;
1666        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
1667
1668        print "<table class=\"heads\" cellspacing=\"0\">\n";
1669        my $alternate = 0;
1670        for (my $i = $from; $i <= $to; $i++) {
1671                my $entry = $taglist->[$i];
1672                my %tag = %$entry;
1673                my $curr = $tag{'id'} eq $head;
1674                if ($alternate) {
1675                        print "<tr class=\"dark\">\n";
1676                } else {
1677                        print "<tr class=\"light\">\n";
1678                }
1679                $alternate ^= 1;
1680                print "<td><i>$tag{'age'}</i></td>\n" .
1681                      ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
1682                      $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'}),
1683                               -class => "list"}, "<b>" . esc_html($tag{'name'}) . "</b>") .
1684                      "</td>\n" .
1685                      "<td class=\"link\">" .
1686                      $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") . " | " .
1687                      $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log") .
1688                      "</td>\n" .
1689                      "</tr>";
1690        }
1691        if (defined $extra) {
1692                print "<tr>\n" .
1693                      "<td colspan=\"3\">$extra</td>\n" .
1694                      "</tr>\n";
1695        }
1696        print "</table>\n";
1697}
1698
1699## ----------------------------------------------------------------------
1700## functions printing large fragments, format as one of arguments
1701
1702sub git_diff_print {
1703        my $from = shift;
1704        my $from_name = shift;
1705        my $to = shift;
1706        my $to_name = shift;
1707        my $format = shift || "html";
1708
1709        my $from_tmp = "/dev/null";
1710        my $to_tmp = "/dev/null";
1711        my $pid = $$;
1712
1713        # create tmp from-file
1714        if (defined $from) {
1715                $from_tmp = "$git_temp/gitweb_" . $$ . "_from";
1716                open my $fd2, "> $from_tmp";
1717                open my $fd, "-|", $GIT, "cat-file", "blob", $from;
1718                my @file = <$fd>;
1719                print $fd2 @file;
1720                close $fd2;
1721                close $fd;
1722        }
1723
1724        # create tmp to-file
1725        if (defined $to) {
1726                $to_tmp = "$git_temp/gitweb_" . $$ . "_to";
1727                open my $fd2, "> $to_tmp";
1728                open my $fd, "-|", $GIT, "cat-file", "blob", $to;
1729                my @file = <$fd>;
1730                print $fd2 @file;
1731                close $fd2;
1732                close $fd;
1733        }
1734
1735        open my $fd, "-|", "/usr/bin/diff -u -p -L \'$from_name\' -L \'$to_name\' $from_tmp $to_tmp";
1736        if ($format eq "plain") {
1737                undef $/;
1738                print <$fd>;
1739                $/ = "\n";
1740        } else {
1741                while (my $line = <$fd>) {
1742                        chomp $line;
1743                        my $char = substr($line, 0, 1);
1744                        my $diff_class = "";
1745                        if ($char eq '+') {
1746                                $diff_class = " add";
1747                        } elsif ($char eq "-") {
1748                                $diff_class = " rem";
1749                        } elsif ($char eq "@") {
1750                                $diff_class = " chunk_header";
1751                        } elsif ($char eq "\\") {
1752                                # skip errors
1753                                next;
1754                        }
1755                        $line = untabify($line);
1756                        print "<div class=\"diff$diff_class\">" . esc_html($line) . "</div>\n";
1757                }
1758        }
1759        close $fd;
1760
1761        if (defined $from) {
1762                unlink($from_tmp);
1763        }
1764        if (defined $to) {
1765                unlink($to_tmp);
1766        }
1767}
1768
1769
1770## ======================================================================
1771## ======================================================================
1772## actions
1773
1774sub git_project_list {
1775        my $order = $cgi->param('o');
1776        if (defined $order && $order !~ m/project|descr|owner|age/) {
1777                die_error(undef, "Unknown order parameter");
1778        }
1779
1780        my @list = git_get_projects_list();
1781        my @projects;
1782        if (!@list) {
1783                die_error(undef, "No projects found");
1784        }
1785        foreach my $pr (@list) {
1786                my $head = git_get_head_hash($pr->{'path'});
1787                if (!defined $head) {
1788                        next;
1789                }
1790                $ENV{'GIT_DIR'} = "$projectroot/$pr->{'path'}";
1791                my %co = parse_commit($head);
1792                if (!%co) {
1793                        next;
1794                }
1795                $pr->{'commit'} = \%co;
1796                if (!defined $pr->{'descr'}) {
1797                        my $descr = git_get_project_description($pr->{'path'}) || "";
1798                        $pr->{'descr'} = chop_str($descr, 25, 5);
1799                }
1800                if (!defined $pr->{'owner'}) {
1801                        $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
1802                }
1803                push @projects, $pr;
1804        }
1805
1806        git_header_html();
1807        if (-f $home_text) {
1808                print "<div class=\"index_include\">\n";
1809                open (my $fd, $home_text);
1810                print <$fd>;
1811                close $fd;
1812                print "</div>\n";
1813        }
1814        print "<table class=\"project_list\">\n" .
1815              "<tr>\n";
1816        $order ||= "project";
1817        if ($order eq "project") {
1818                @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
1819                print "<th>Project</th>\n";
1820        } else {
1821                print "<th>" .
1822                      $cgi->a({-href => "$my_uri?" . esc_param("o=project"),
1823                               -class => "header"}, "Project") .
1824                      "</th>\n";
1825        }
1826        if ($order eq "descr") {
1827                @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
1828                print "<th>Description</th>\n";
1829        } else {
1830                print "<th>" .
1831                      $cgi->a({-href => "$my_uri?" . esc_param("o=descr"),
1832                               -class => "header"}, "Description") .
1833                      "</th>\n";
1834        }
1835        if ($order eq "owner") {
1836                @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
1837                print "<th>Owner</th>\n";
1838        } else {
1839                print "<th>" .
1840                      $cgi->a({-href => "$my_uri?" . esc_param("o=owner"),
1841                               -class => "header"}, "Owner") .
1842                      "</th>\n";
1843        }
1844        if ($order eq "age") {
1845                @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
1846                print "<th>Last Change</th>\n";
1847        } else {
1848                print "<th>" .
1849                      $cgi->a({-href => "$my_uri?" . esc_param("o=age"),
1850                               -class => "header"}, "Last Change") .
1851                      "</th>\n";
1852        }
1853        print "<th></th>\n" .
1854              "</tr>\n";
1855        my $alternate = 0;
1856        foreach my $pr (@projects) {
1857                if ($alternate) {
1858                        print "<tr class=\"dark\">\n";
1859                } else {
1860                        print "<tr class=\"light\">\n";
1861                }
1862                $alternate ^= 1;
1863                print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
1864                                        -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
1865                      "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
1866                      "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
1867                print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" .
1868                      $pr->{'commit'}{'age_string'} . "</td>\n" .
1869                      "<td class=\"link\">" .
1870                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
1871                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
1872                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") .
1873                      "</td>\n" .
1874                      "</tr>\n";
1875        }
1876        print "</table>\n";
1877        git_footer_html();
1878}
1879
1880sub git_summary {
1881        my $descr = git_get_project_description($project) || "none";
1882        my $head = git_get_head_hash($project);
1883        my %co = parse_commit($head);
1884        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
1885
1886        my $owner = git_get_project_owner($project);
1887
1888        my $refs = git_get_references();
1889        git_header_html();
1890        git_print_page_nav('summary','', $head);
1891
1892        print "<div class=\"title\">&nbsp;</div>\n";
1893        print "<table cellspacing=\"0\">\n" .
1894              "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
1895              "<tr><td>owner</td><td>$owner</td></tr>\n" .
1896              "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
1897        # use per project git URL list in $projectroot/$project/cloneurl
1898        # or make project git URL from git base URL and project name
1899        my $url_tag = "URL";
1900        my @url_list = git_get_project_url_list($project);
1901        @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
1902        foreach my $git_url (@url_list) {
1903                next unless $git_url;
1904                print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
1905                $url_tag = "";
1906        }
1907        print "</table>\n";
1908
1909        open my $fd, "-|", $GIT, "rev-list", "--max-count=17", git_get_head_hash($project)
1910                or die_error(undef, "Open git-rev-list failed");
1911        my @revlist = map { chomp; $_ } <$fd>;
1912        close $fd;
1913        git_print_header_div('shortlog');
1914        git_shortlog_body(\@revlist, 0, 15, $refs,
1915                          $cgi->a({-href => href(action=>"shortlog")}, "..."));
1916
1917        my $taglist = git_get_refs_list("refs/tags");
1918        if (defined @$taglist) {
1919                git_print_header_div('tags');
1920                git_tags_body($taglist, 0, 15,
1921                              $cgi->a({-href => href(action=>"tags")}, "..."));
1922        }
1923
1924        my $headlist = git_get_refs_list("refs/heads");
1925        if (defined @$headlist) {
1926                git_print_header_div('heads');
1927                git_heads_body($headlist, $head, 0, 15,
1928                               $cgi->a({-href => href(action=>"heads")}, "..."));
1929        }
1930
1931        git_footer_html();
1932}
1933
1934sub git_tag {
1935        my $head = git_get_head_hash($project);
1936        git_header_html();
1937        git_print_page_nav('','', $head,undef,$head);
1938        my %tag = parse_tag($hash);
1939        git_print_header_div('commit', esc_html($tag{'name'}), $hash);
1940        print "<div class=\"title_text\">\n" .
1941              "<table cellspacing=\"0\">\n" .
1942              "<tr>\n" .
1943              "<td>object</td>\n" .
1944              "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})}, $tag{'object'}) . "</td>\n" .
1945              "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})}, $tag{'type'}) . "</td>\n" .
1946              "</tr>\n";
1947        if (defined($tag{'author'})) {
1948                my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
1949                print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
1950                print "<tr><td></td><td>" . $ad{'rfc2822'} . sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) . "</td></tr>\n";
1951        }
1952        print "</table>\n\n" .
1953              "</div>\n";
1954        print "<div class=\"page_body\">";
1955        my $comment = $tag{'comment'};
1956        foreach my $line (@$comment) {
1957                print esc_html($line) . "<br/>\n";
1958        }
1959        print "</div>\n";
1960        git_footer_html();
1961}
1962
1963sub git_blame2 {
1964        my $fd;
1965        my $ftype;
1966
1967        if (!gitweb_check_feature('blame')) {
1968                die_error('403 Permission denied', "Permission denied");
1969        }
1970        die_error('404 Not Found', "File name not defined") if (!$file_name);
1971        $hash_base ||= git_get_head_hash($project);
1972        die_error(undef, "Couldn't find base commit") unless ($hash_base);
1973        my %co = parse_commit($hash_base)
1974                or die_error(undef, "Reading commit failed");
1975        if (!defined $hash) {
1976                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
1977                        or die_error(undef, "Error looking up file");
1978        }
1979        $ftype = git_get_type($hash);
1980        if ($ftype !~ "blob") {
1981                die_error("400 Bad Request", "Object is not a blob");
1982        }
1983        open ($fd, "-|", $GIT, "blame", '-l', $file_name, $hash_base)
1984                or die_error(undef, "Open git-blame failed");
1985        git_header_html();
1986        my $formats_nav =
1987                $cgi->a({-href => href(action=>"blobl", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)}, "blob") .
1988                " | " . $cgi->a({-href => href(action=>"blame", file_name=>$file_name)}, "head");
1989        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
1990        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
1991        git_print_page_path($file_name, $ftype, $hash_base);
1992        my @rev_color = (qw(light2 dark2));
1993        my $num_colors = scalar(@rev_color);
1994        my $current_color = 0;
1995        my $last_rev;
1996        print "<div class=\"page_body\">\n";
1997        print "<table class=\"blame\">\n";
1998        print "<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n";
1999        while (<$fd>) {
2000                /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
2001                my $full_rev = $1;
2002                my $rev = substr($full_rev, 0, 8);
2003                my $lineno = $2;
2004                my $data = $3;
2005
2006                if (!defined $last_rev) {
2007                        $last_rev = $full_rev;
2008                } elsif ($last_rev ne $full_rev) {
2009                        $last_rev = $full_rev;
2010                        $current_color = ++$current_color % $num_colors;
2011                }
2012                print "<tr class=\"$rev_color[$current_color]\">\n";
2013                print "<td class=\"sha1\">" .
2014                        $cgi->a({-href => href(action=>"commit", hash=>$full_rev, file_name=>$file_name)}, esc_html($rev)) . "</td>\n";
2015                print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" . esc_html($lineno) . "</a></td>\n";
2016                print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
2017                print "</tr>\n";
2018        }
2019        print "</table>\n";
2020        print "</div>";
2021        close $fd or print "Reading blob failed\n";
2022        git_footer_html();
2023}
2024
2025sub git_blame {
2026        my $fd;
2027
2028        if (!gitweb_check_feature('blame')) {
2029                die_error('403 Permission denied', "Permission denied");
2030        }
2031        die_error('404 Not Found', "File name not defined") if (!$file_name);
2032        $hash_base ||= git_get_head_hash($project);
2033        die_error(undef, "Couldn't find base commit") unless ($hash_base);
2034        my %co = parse_commit($hash_base)
2035                or die_error(undef, "Reading commit failed");
2036        if (!defined $hash) {
2037                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2038                        or die_error(undef, "Error lookup file");
2039        }
2040        open ($fd, "-|", $GIT, "annotate", '-l', '-t', '-r', $file_name, $hash_base)
2041                or die_error(undef, "Open git-annotate failed");
2042        git_header_html();
2043        my $formats_nav =
2044                $cgi->a({-href => href(action=>"blobl", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)}, "blob") .
2045                " | " . $cgi->a({-href => href(action=>"blame", file_name=>$file_name)}, "head");
2046        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2047        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2048        git_print_page_path($file_name, 'blob', $hash_base);
2049        print "<div class=\"page_body\">\n";
2050        print <<HTML;
2051<table class="blame">
2052  <tr>
2053    <th>Commit</th>
2054    <th>Age</th>
2055    <th>Author</th>
2056    <th>Line</th>
2057    <th>Data</th>
2058  </tr>
2059HTML
2060        my @line_class = (qw(light dark));
2061        my $line_class_len = scalar (@line_class);
2062        my $line_class_num = $#line_class;
2063        while (my $line = <$fd>) {
2064                my $long_rev;
2065                my $short_rev;
2066                my $author;
2067                my $time;
2068                my $lineno;
2069                my $data;
2070                my $age;
2071                my $age_str;
2072                my $age_class;
2073
2074                chomp $line;
2075                $line_class_num = ($line_class_num + 1) % $line_class_len;
2076
2077                if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) \+\d\d\d\d\t(\d+)\)(.*)$/) {
2078                        $long_rev = $1;
2079                        $author   = $2;
2080                        $time     = $3;
2081                        $lineno   = $4;
2082                        $data     = $5;
2083                } else {
2084                        print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
2085                        next;
2086                }
2087                $short_rev  = substr ($long_rev, 0, 8);
2088                $age        = time () - $time;
2089                $age_str    = age_string ($age);
2090                $age_str    =~ s/ /&nbsp;/g;
2091                $age_class  = age_class($age);
2092                $author     = esc_html ($author);
2093                $author     =~ s/ /&nbsp;/g;
2094
2095                $data = untabify($data);
2096                $data = esc_html ($data);
2097
2098                print <<HTML;
2099  <tr class="$line_class[$line_class_num]">
2100    <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
2101    <td class="$age_class">$age_str</td>
2102    <td>$author</td>
2103    <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
2104    <td class="pre">$data</td>
2105  </tr>
2106HTML
2107        } # while (my $line = <$fd>)
2108        print "</table>\n\n";
2109        close $fd or print "Reading blob failed.\n";
2110        print "</div>";
2111        git_footer_html();
2112}
2113
2114sub git_tags {
2115        my $head = git_get_head_hash($project);
2116        git_header_html();
2117        git_print_page_nav('','', $head,undef,$head);
2118        git_print_header_div('summary', $project);
2119
2120        my $taglist = git_get_refs_list("refs/tags");
2121        if (defined @$taglist) {
2122                git_tags_body($taglist);
2123        }
2124        git_footer_html();
2125}
2126
2127sub git_heads {
2128        my $head = git_get_head_hash($project);
2129        git_header_html();
2130        git_print_page_nav('','', $head,undef,$head);
2131        git_print_header_div('summary', $project);
2132
2133        my $taglist = git_get_refs_list("refs/heads");
2134        if (defined @$taglist) {
2135                git_heads_body($taglist, $head);
2136        }
2137        git_footer_html();
2138}
2139
2140sub git_blob_plain {
2141        if (!defined $hash) {
2142                if (defined $file_name) {
2143                        my $base = $hash_base || git_get_head_hash($project);
2144                        $hash = git_get_hash_by_path($base, $file_name, "blob")
2145                                or die_error(undef, "Error lookup file");
2146                } else {
2147                        die_error(undef, "No file name defined");
2148                }
2149        }
2150        my $type = shift;
2151        open my $fd, "-|", $GIT, "cat-file", "blob", $hash
2152                or die_error(undef, "Couldn't cat $file_name, $hash");
2153
2154        $type ||= blob_mimetype($fd, $file_name);
2155
2156        # save as filename, even when no $file_name is given
2157        my $save_as = "$hash";
2158        if (defined $file_name) {
2159                $save_as = $file_name;
2160        } elsif ($type =~ m/^text\//) {
2161                $save_as .= '.txt';
2162        }
2163
2164        print $cgi->header(-type => "$type", '-content-disposition' => "inline; filename=\"$save_as\"");
2165        undef $/;
2166        binmode STDOUT, ':raw';
2167        print <$fd>;
2168        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2169        $/ = "\n";
2170        close $fd;
2171}
2172
2173sub git_blob {
2174        if (!defined $hash) {
2175                if (defined $file_name) {
2176                        my $base = $hash_base || git_get_head_hash($project);
2177                        $hash = git_get_hash_by_path($base, $file_name, "blob")
2178                                or die_error(undef, "Error lookup file");
2179                } else {
2180                        die_error(undef, "No file name defined");
2181                }
2182        }
2183        my $have_blame = gitweb_check_feature('blame');
2184        open my $fd, "-|", $GIT, "cat-file", "blob", $hash
2185                or die_error(undef, "Couldn't cat $file_name, $hash");
2186        my $mimetype = blob_mimetype($fd, $file_name);
2187        if ($mimetype !~ m/^text\//) {
2188                close $fd;
2189                return git_blob_plain($mimetype);
2190        }
2191        git_header_html();
2192        my $formats_nav = '';
2193        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2194                if (defined $file_name) {
2195                        if ($have_blame) {
2196                                $formats_nav .= $cgi->a({-href => href(action=>"blame", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)}, "blame") . " | ";
2197                        }
2198                        $formats_nav .=
2199                                $cgi->a({-href => href(action=>"blob_plain", hash=>$hash, file_name=>$file_name)}, "plain") .
2200                                " | " . $cgi->a({-href => href(action=>"blob", hash_base=>"HEAD", file_name=>$file_name)}, "head");
2201                } else {
2202                        $formats_nav .= $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "plain");
2203                }
2204                git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2205                git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2206        } else {
2207                print "<div class=\"page_nav\">\n" .
2208                      "<br/><br/></div>\n" .
2209                      "<div class=\"title\">$hash</div>\n";
2210        }
2211        git_print_page_path($file_name, "blob", $hash_base);
2212        print "<div class=\"page_body\">\n";
2213        my $nr;
2214        while (my $line = <$fd>) {
2215                chomp $line;
2216                $nr++;
2217                $line = untabify($line);
2218                printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n", $nr, $nr, $nr, esc_html($line);
2219        }
2220        close $fd or print "Reading blob failed.\n";
2221        print "</div>";
2222        git_footer_html();
2223}
2224
2225sub git_tree {
2226        if (!defined $hash) {
2227                $hash = git_get_head_hash($project);
2228                if (defined $file_name) {
2229                        my $base = $hash_base || $hash;
2230                        $hash = git_get_hash_by_path($base, $file_name, "tree");
2231                }
2232                if (!defined $hash_base) {
2233                        $hash_base = $hash;
2234                }
2235        }
2236        $/ = "\0";
2237        open my $fd, "-|", $GIT, "ls-tree", '-z', $hash
2238                or die_error(undef, "Open git-ls-tree failed");
2239        my @entries = map { chomp; $_ } <$fd>;
2240        close $fd or die_error(undef, "Reading tree failed");
2241        $/ = "\n";
2242
2243        my $refs = git_get_references();
2244        my $ref = format_ref_marker($refs, $hash_base);
2245        git_header_html();
2246        my %base_key = ();
2247        my $base = "";
2248        my $have_blame = gitweb_check_feature('blame');
2249        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2250                $base_key{hash_base} = $hash_base;
2251                git_print_page_nav('tree','', $hash_base);
2252                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
2253        } else {
2254                print "<div class=\"page_nav\">\n";
2255                print "<br/><br/></div>\n";
2256                print "<div class=\"title\">$hash</div>\n";
2257        }
2258        if (defined $file_name) {
2259                $base = esc_html("$file_name/");
2260        }
2261        git_print_page_path($file_name, 'tree', $hash_base);
2262        print "<div class=\"page_body\">\n";
2263        print "<table cellspacing=\"0\">\n";
2264        my $alternate = 0;
2265        foreach my $line (@entries) {
2266                #'100644        blob    0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa        panic.c'
2267                $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
2268                my $t_mode = $1;
2269                my $t_type = $2;
2270                my $t_hash = $3;
2271                my $t_name = validate_input($4);
2272                if ($alternate) {
2273                        print "<tr class=\"dark\">\n";
2274                } else {
2275                        print "<tr class=\"light\">\n";
2276                }
2277                $alternate ^= 1;
2278                print "<td class=\"mode\">" . mode_str($t_mode) . "</td>\n";
2279                if ($t_type eq "blob") {
2280                        print "<td class=\"list\">" .
2281                              $cgi->a({-href => href(action=>"blob", hash=>$t_hash, file_name=>"$base$t_name", %base_key), -class => "list"}, esc_html($t_name)) .
2282                              "</td>\n" .
2283                              "<td class=\"link\">" .
2284                              $cgi->a({-href => href(action=>"blob", hash=>$t_hash, file_name=>"$base$t_name", %base_key)}, "blob");
2285                        if ($have_blame) {
2286                                print " | " . $cgi->a({-href => href(action=>"blame", hash=>$t_hash, file_name=>"$base$t_name", %base_key)}, "blame");
2287                        }
2288                        print " | " . $cgi->a({-href => href(action=>"history", hash=>$t_hash, hash_base=>$hash_base, file_name=>"$base$t_name")}, "history") .
2289                              " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$t_hash, file_name=>"$base$t_name")}, "raw") .
2290                              "</td>\n";
2291                } elsif ($t_type eq "tree") {
2292                        print "<td class=\"list\">" .
2293                              $cgi->a({-href => href(action=>"tree", hash=>$t_hash, file_name=>"$base$t_name", %base_key)}, esc_html($t_name)) .
2294                              "</td>\n" .
2295                              "<td class=\"link\">" .
2296                              $cgi->a({-href => href(action=>"tree", hash=>$t_hash, file_name=>"$base$t_name", %base_key)}, "tree") .
2297                              " | " . $cgi->a({-href => href(action=>"history", hash_base=>$hash_base, file_name=>"$base$t_name")}, "history") .
2298                              "</td>\n";
2299                }
2300                print "</tr>\n";
2301        }
2302        print "</table>\n" .
2303              "</div>";
2304        git_footer_html();
2305}
2306
2307sub git_snapshot {
2308
2309        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2310        my $have_snapshot = (defined $ctype && defined $suffix);
2311        if (!$have_snapshot) {
2312                die_error('403 Permission denied', "Permission denied");
2313        }
2314
2315        if (!defined $hash) {
2316                $hash = git_get_head_hash($project);
2317        }
2318
2319        my $filename = basename($project) . "-$hash.tar.$suffix";
2320
2321        print $cgi->header(-type => 'application/x-tar',
2322                           -content-encoding => $ctype,
2323                           '-content-disposition' =>
2324                           "inline; filename=\"$filename\"",
2325                           -status => '200 OK');
2326
2327        open my $fd, "-|", "$GIT tar-tree $hash \'$project\' | $command" or
2328                die_error(undef, "Execute git-tar-tree failed.");
2329        binmode STDOUT, ':raw';
2330        print <$fd>;
2331        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2332        close $fd;
2333
2334}
2335
2336sub git_log {
2337        my $head = git_get_head_hash($project);
2338        if (!defined $hash) {
2339                $hash = $head;
2340        }
2341        if (!defined $page) {
2342                $page = 0;
2343        }
2344        my $refs = git_get_references();
2345
2346        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2347        open my $fd, "-|", $GIT, "rev-list", $limit, $hash
2348                or die_error(undef, "Open git-rev-list failed");
2349        my @revlist = map { chomp; $_ } <$fd>;
2350        close $fd;
2351
2352        my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
2353
2354        git_header_html();
2355        git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
2356
2357        if (!@revlist) {
2358                my %co = parse_commit($hash);
2359
2360                git_print_header_div('summary', $project);
2361                print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
2362        }
2363        for (my $i = ($page * 100); $i <= $#revlist; $i++) {
2364                my $commit = $revlist[$i];
2365                my $ref = format_ref_marker($refs, $commit);
2366                my %co = parse_commit($commit);
2367                next if !%co;
2368                my %ad = parse_date($co{'author_epoch'});
2369                git_print_header_div('commit',
2370                               "<span class=\"age\">$co{'age_string'}</span>" .
2371                               esc_html($co{'title'}) . $ref,
2372                               $commit);
2373                print "<div class=\"title_text\">\n" .
2374                      "<div class=\"log_link\">\n" .
2375                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
2376                      " | " . $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
2377                      "<br/>\n" .
2378                      "</div>\n" .
2379                      "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
2380                      "</div>\n";
2381
2382                print "<div class=\"log_body\">\n";
2383                git_print_simplified_log($co{'comment'});
2384                print "</div>\n";
2385        }
2386        git_footer_html();
2387}
2388
2389sub git_commit {
2390        my %co = parse_commit($hash);
2391        if (!%co) {
2392                die_error(undef, "Unknown commit object");
2393        }
2394        my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2395        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2396
2397        my $parent = $co{'parent'};
2398        if (!defined $parent) {
2399                $parent = "--root";
2400        }
2401        open my $fd, "-|", $GIT, "diff-tree", '-r', '-M', $parent, $hash
2402                or die_error(undef, "Open git-diff-tree failed");
2403        my @difftree = map { chomp; $_ } <$fd>;
2404        close $fd or die_error(undef, "Reading git-diff-tree failed");
2405
2406        # non-textual hash id's can be cached
2407        my $expires;
2408        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2409                $expires = "+1d";
2410        }
2411        my $refs = git_get_references();
2412        my $ref = format_ref_marker($refs, $co{'id'});
2413
2414        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2415        my $have_snapshot = (defined $ctype && defined $suffix);
2416
2417        my $formats_nav = '';
2418        if (defined $file_name && defined $co{'parent'}) {
2419                my $parent = $co{'parent'};
2420                $formats_nav .= $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)}, "blame");
2421        }
2422        git_header_html(undef, $expires);
2423        git_print_page_nav('commit', defined $co{'parent'} ? '' : 'commitdiff',
2424                     $hash, $co{'tree'}, $hash,
2425                     $formats_nav);
2426
2427        if (defined $co{'parent'}) {
2428                git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
2429        } else {
2430                git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
2431        }
2432        print "<div class=\"title_text\">\n" .
2433              "<table cellspacing=\"0\">\n";
2434        print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
2435              "<tr>" .
2436              "<td></td><td> $ad{'rfc2822'}";
2437        if ($ad{'hour_local'} < 6) {
2438                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2439        } else {
2440                printf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2441        }
2442        print "</td>" .
2443              "</tr>\n";
2444        print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
2445        print "<tr><td></td><td> $cd{'rfc2822'}" . sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) . "</td></tr>\n";
2446        print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
2447        print "<tr>" .
2448              "<td>tree</td>" .
2449              "<td class=\"sha1\">" .
2450              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash), class => "list"}, $co{'tree'}) .
2451              "</td>" .
2452              "<td class=\"link\">" . $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)}, "tree");
2453        if ($have_snapshot) {
2454                print " | " .  $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
2455        }
2456        print "</td>" .
2457              "</tr>\n";
2458        my $parents = $co{'parents'};
2459        foreach my $par (@$parents) {
2460                print "<tr>" .
2461                      "<td>parent</td>" .
2462                      "<td class=\"sha1\">" . $cgi->a({-href => href(action=>"commit", hash=>$par), class => "list"}, $par) . "</td>" .
2463                      "<td class=\"link\">" .
2464                      $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
2465                      " | " . $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "commitdiff") .
2466                      "</td>" .
2467                      "</tr>\n";
2468        }
2469        print "</table>".
2470              "</div>\n";
2471
2472        print "<div class=\"page_body\">\n";
2473        git_print_log($co{'comment'});
2474        print "</div>\n";
2475
2476        git_difftree_body(\@difftree, $parent);
2477
2478        git_footer_html();
2479}
2480
2481sub git_blobdiff {
2482        mkdir($git_temp, 0700);
2483        git_header_html();
2484        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2485                my $formats_nav =
2486                        $cgi->a({-href => href(action=>"blobdiff_plain", hash=>$hash, hash_parent=>$hash_parent)}, "plain");
2487                git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2488                git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2489        } else {
2490                print "<div class=\"page_nav\">\n" .
2491                      "<br/><br/></div>\n" .
2492                      "<div class=\"title\">$hash vs $hash_parent</div>\n";
2493        }
2494        git_print_page_path($file_name, "blob", $hash_base);
2495        print "<div class=\"page_body\">\n" .
2496              "<div class=\"diff_info\">blob:" .
2497              $cgi->a({-href => href(action=>"blob", hash=>$hash_parent, hash_base=>$hash_base, file_name=>($file_parent || $file_name))}, $hash_parent) .
2498              " -> blob:" .
2499              $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)}, $hash) .
2500              "</div>\n";
2501        git_diff_print($hash_parent, $file_name || $hash_parent, $hash, $file_name || $hash);
2502        print "</div>";
2503        git_footer_html();
2504}
2505
2506sub git_blobdiff_plain {
2507        mkdir($git_temp, 0700);
2508        print $cgi->header(-type => "text/plain", -charset => 'utf-8');
2509        git_diff_print($hash_parent, $file_name || $hash_parent, $hash, $file_name || $hash, "plain");
2510}
2511
2512sub git_commitdiff {
2513        mkdir($git_temp, 0700);
2514        my %co = parse_commit($hash);
2515        if (!%co) {
2516                die_error(undef, "Unknown commit object");
2517        }
2518        if (!defined $hash_parent) {
2519                $hash_parent = $co{'parent'} || '--root';
2520        }
2521        open my $fd, "-|", $GIT, "diff-tree", '-r', $hash_parent, $hash
2522                or die_error(undef, "Open git-diff-tree failed");
2523        my @difftree = map { chomp; $_ } <$fd>;
2524        close $fd or die_error(undef, "Reading git-diff-tree failed");
2525
2526        # non-textual hash id's can be cached
2527        my $expires;
2528        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2529                $expires = "+1d";
2530        }
2531        my $refs = git_get_references();
2532        my $ref = format_ref_marker($refs, $co{'id'});
2533        my $formats_nav =
2534                $cgi->a({-href => href(action=>"commitdiff_plain", hash=>$hash, hash_parent=>$hash_parent)}, "plain");
2535        git_header_html(undef, $expires);
2536        git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
2537        git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
2538        print "<div class=\"page_body\">\n";
2539        git_print_simplified_log($co{'comment'}, 1); # skip title
2540        print "<br/>\n";
2541        foreach my $line (@difftree) {
2542                # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M      ls-files.c'
2543                # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M      rev-tree.c'
2544                if ($line !~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
2545                        next;
2546                }
2547                my $from_mode = $1;
2548                my $to_mode = $2;
2549                my $from_id = $3;
2550                my $to_id = $4;
2551                my $status = $5;
2552                my $file = validate_input(unquote($6));
2553                if ($status eq "A") {
2554                        print "<div class=\"diff_info\">" . file_type($to_mode) . ":" .
2555                              $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$file)}, $to_id) . "(new)" .
2556                              "</div>\n";
2557                        git_diff_print(undef, "/dev/null", $to_id, "b/$file");
2558                } elsif ($status eq "D") {
2559                        print "<div class=\"diff_info\">" . file_type($from_mode) . ":" .
2560                              $cgi->a({-href => href(action=>"blob", hash=>$from_id, hash_base=>$hash_parent, file_name=>$file)}, $from_id) . "(deleted)" .
2561                              "</div>\n";
2562                        git_diff_print($from_id, "a/$file", undef, "/dev/null");
2563                } elsif ($status eq "M") {
2564                        if ($from_id ne $to_id) {
2565                                print "<div class=\"diff_info\">" .
2566                                      file_type($from_mode) . ":" .
2567                                      $cgi->a({-href => href(action=>"blob", hash=>$from_id, hash_base=>$hash_parent, file_name=>$file)}, $from_id) .
2568                                      " -> " .
2569                                      file_type($to_mode) . ":" .
2570                                      $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$file)}, $to_id);
2571                                print "</div>\n";
2572                                git_diff_print($from_id, "a/$file",  $to_id, "b/$file");
2573                        }
2574                }
2575        }
2576        print "<br/>\n" .
2577              "</div>";
2578        git_footer_html();
2579}
2580
2581sub git_commitdiff_plain {
2582        mkdir($git_temp, 0700);
2583        my %co = parse_commit($hash);
2584        if (!%co) {
2585                die_error(undef, "Unknown commit object");
2586        }
2587        if (!defined $hash_parent) {
2588                $hash_parent = $co{'parent'} || '--root';
2589        }
2590        open my $fd, "-|", $GIT, "diff-tree", '-r', $hash_parent, $hash
2591                or die_error(undef, "Open git-diff-tree failed");
2592        my @difftree = map { chomp; $_ } <$fd>;
2593        close $fd or die_error(undef, "Reading diff-tree failed");
2594
2595        # try to figure out the next tag after this commit
2596        my $tagname;
2597        my $refs = git_get_references("tags");
2598        open $fd, "-|", $GIT, "rev-list", "HEAD";
2599        my @commits = map { chomp; $_ } <$fd>;
2600        close $fd;
2601        foreach my $commit (@commits) {
2602                if (defined $refs->{$commit}) {
2603                        $tagname = $refs->{$commit}
2604                }
2605                if ($commit eq $hash) {
2606                        last;
2607                }
2608        }
2609
2610        print $cgi->header(-type => "text/plain", -charset => 'utf-8', '-content-disposition' => "inline; filename=\"git-$hash.patch\"");
2611        my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2612        my $comment = $co{'comment'};
2613        print "From: $co{'author'}\n" .
2614              "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n".
2615              "Subject: $co{'title'}\n";
2616        if (defined $tagname) {
2617                print "X-Git-Tag: $tagname\n";
2618        }
2619        print "X-Git-Url: $my_url?p=$project;a=commitdiff;h=$hash\n" .
2620              "\n";
2621
2622        foreach my $line (@$comment) {;
2623                print "$line\n";
2624        }
2625        print "---\n\n";
2626
2627        foreach my $line (@difftree) {
2628                if ($line !~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
2629                        next;
2630                }
2631                my $from_id = $3;
2632                my $to_id = $4;
2633                my $status = $5;
2634                my $file = $6;
2635                if ($status eq "A") {
2636                        git_diff_print(undef, "/dev/null", $to_id, "b/$file", "plain");
2637                } elsif ($status eq "D") {
2638                        git_diff_print($from_id, "a/$file", undef, "/dev/null", "plain");
2639                } elsif ($status eq "M") {
2640                        git_diff_print($from_id, "a/$file",  $to_id, "b/$file", "plain");
2641                }
2642        }
2643}
2644
2645sub git_history {
2646        if (!defined $hash_base) {
2647                $hash_base = git_get_head_hash($project);
2648        }
2649        my $ftype;
2650        my %co = parse_commit($hash_base);
2651        if (!%co) {
2652                die_error(undef, "Unknown commit object");
2653        }
2654        my $refs = git_get_references();
2655        git_header_html();
2656        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base);
2657        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2658        if (!defined $hash && defined $file_name) {
2659                $hash = git_get_hash_by_path($hash_base, $file_name);
2660        }
2661        if (defined $hash) {
2662                $ftype = git_get_type($hash);
2663        }
2664        git_print_page_path($file_name, $ftype, $hash_base);
2665
2666        open my $fd, "-|",
2667                $GIT, "rev-list", "--full-history", $hash_base, "--", $file_name;
2668        git_history_body($fd, $refs, $hash_base, $ftype);
2669
2670        close $fd;
2671        git_footer_html();
2672}
2673
2674sub git_search {
2675        if (!defined $searchtext) {
2676                die_error(undef, "Text field empty");
2677        }
2678        if (!defined $hash) {
2679                $hash = git_get_head_hash($project);
2680        }
2681        my %co = parse_commit($hash);
2682        if (!%co) {
2683                die_error(undef, "Unknown commit object");
2684        }
2685        # pickaxe may take all resources of your box and run for several minutes
2686        # with every query - so decide by yourself how public you make this feature :)
2687        my $commit_search = 1;
2688        my $author_search = 0;
2689        my $committer_search = 0;
2690        my $pickaxe_search = 0;
2691        if ($searchtext =~ s/^author\\://i) {
2692                $author_search = 1;
2693        } elsif ($searchtext =~ s/^committer\\://i) {
2694                $committer_search = 1;
2695        } elsif ($searchtext =~ s/^pickaxe\\://i) {
2696                $commit_search = 0;
2697                $pickaxe_search = 1;
2698        }
2699        git_header_html();
2700        git_print_page_nav('','', $hash,$co{'tree'},$hash);
2701        git_print_header_div('commit', esc_html($co{'title'}), $hash);
2702
2703        print "<table cellspacing=\"0\">\n";
2704        my $alternate = 0;
2705        if ($commit_search) {
2706                $/ = "\0";
2707                open my $fd, "-|", $GIT, "rev-list", "--header", "--parents", $hash or next;
2708                while (my $commit_text = <$fd>) {
2709                        if (!grep m/$searchtext/i, $commit_text) {
2710                                next;
2711                        }
2712                        if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
2713                                next;
2714                        }
2715                        if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
2716                                next;
2717                        }
2718                        my @commit_lines = split "\n", $commit_text;
2719                        my %co = parse_commit(undef, \@commit_lines);
2720                        if (!%co) {
2721                                next;
2722                        }
2723                        if ($alternate) {
2724                                print "<tr class=\"dark\">\n";
2725                        } else {
2726                                print "<tr class=\"light\">\n";
2727                        }
2728                        $alternate ^= 1;
2729                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2730                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
2731                              "<td>" .
2732                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}) -class => "list"}, "<b>" . esc_html(chop_str($co{'title'}, 50)) . "</b><br/>");
2733                        my $comment = $co{'comment'};
2734                        foreach my $line (@$comment) {
2735                                if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
2736                                        my $lead = esc_html($1) || "";
2737                                        $lead = chop_str($lead, 30, 10);
2738                                        my $match = esc_html($2) || "";
2739                                        my $trail = esc_html($3) || "";
2740                                        $trail = chop_str($trail, 30, 10);
2741                                        my $text = "$lead<span class=\"match\">$match</span>$trail";
2742                                        print chop_str($text, 80, 5) . "<br/>\n";
2743                                }
2744                        }
2745                        print "</td>\n" .
2746                              "<td class=\"link\">" .
2747                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
2748                              " | " . $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
2749                        print "</td>\n" .
2750                              "</tr>\n";
2751                }
2752                close $fd;
2753        }
2754
2755        if ($pickaxe_search) {
2756                $/ = "\n";
2757                open my $fd, "-|", "$GIT rev-list $hash | $GIT diff-tree -r --stdin -S\'$searchtext\'";
2758                undef %co;
2759                my @files;
2760                while (my $line = <$fd>) {
2761                        if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
2762                                my %set;
2763                                $set{'file'} = $6;
2764                                $set{'from_id'} = $3;
2765                                $set{'to_id'} = $4;
2766                                $set{'id'} = $set{'to_id'};
2767                                if ($set{'id'} =~ m/0{40}/) {
2768                                        $set{'id'} = $set{'from_id'};
2769                                }
2770                                if ($set{'id'} =~ m/0{40}/) {
2771                                        next;
2772                                }
2773                                push @files, \%set;
2774                        } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
2775                                if (%co) {
2776                                        if ($alternate) {
2777                                                print "<tr class=\"dark\">\n";
2778                                        } else {
2779                                                print "<tr class=\"light\">\n";
2780                                        }
2781                                        $alternate ^= 1;
2782                                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2783                                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
2784                                              "<td>" .
2785                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list"}, "<b>" .
2786                                              esc_html(chop_str($co{'title'}, 50)) . "</b><br/>");
2787                                        while (my $setref = shift @files) {
2788                                                my %set = %$setref;
2789                                                print $cgi->a({-href => href(action=>"blob", hash=>$set{'id'}, hash_base=>$co{'id'}, file_name=>$set{'file'}), class => "list"},
2790                                                      "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
2791                                                      "<br/>\n";
2792                                        }
2793                                        print "</td>\n" .
2794                                              "<td class=\"link\">" .
2795                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
2796                                              " | " . $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
2797                                        print "</td>\n" .
2798                                              "</tr>\n";
2799                                }
2800                                %co = parse_commit($1);
2801                        }
2802                }
2803                close $fd;
2804        }
2805        print "</table>\n";
2806        git_footer_html();
2807}
2808
2809sub git_shortlog {
2810        my $head = git_get_head_hash($project);
2811        if (!defined $hash) {
2812                $hash = $head;
2813        }
2814        if (!defined $page) {
2815                $page = 0;
2816        }
2817        my $refs = git_get_references();
2818
2819        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2820        open my $fd, "-|", $GIT, "rev-list", $limit, $hash
2821                or die_error(undef, "Open git-rev-list failed");
2822        my @revlist = map { chomp; $_ } <$fd>;
2823        close $fd;
2824
2825        my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
2826        my $next_link = '';
2827        if ($#revlist >= (100 * ($page+1)-1)) {
2828                $next_link =
2829                        $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
2830                                 -title => "Alt-n"}, "next");
2831        }
2832
2833
2834        git_header_html();
2835        git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
2836        git_print_header_div('summary', $project);
2837
2838        git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
2839
2840        git_footer_html();
2841}
2842
2843## ......................................................................
2844## feeds (RSS, OPML)
2845
2846sub git_rss {
2847        # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
2848        open my $fd, "-|", $GIT, "rev-list", "--max-count=150", git_get_head_hash($project)
2849                or die_error(undef, "Open git-rev-list failed");
2850        my @revlist = map { chomp; $_ } <$fd>;
2851        close $fd or die_error(undef, "Reading git-rev-list failed");
2852        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
2853        print "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".
2854              "<rss version=\"2.0\" xmlns:content=\"http://purl.org/rss/1.0/modules/content/\">\n";
2855        print "<channel>\n";
2856        print "<title>$project</title>\n".
2857              "<link>" . esc_html("$my_url?p=$project;a=summary") . "</link>\n".
2858              "<description>$project log</description>\n".
2859              "<language>en</language>\n";
2860
2861        for (my $i = 0; $i <= $#revlist; $i++) {
2862                my $commit = $revlist[$i];
2863                my %co = parse_commit($commit);
2864                # we read 150, we always show 30 and the ones more recent than 48 hours
2865                if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
2866                        last;
2867                }
2868                my %cd = parse_date($co{'committer_epoch'});
2869                open $fd, "-|", $GIT, "diff-tree", '-r', $co{'parent'}, $co{'id'} or next;
2870                my @difftree = map { chomp; $_ } <$fd>;
2871                close $fd or next;
2872                print "<item>\n" .
2873                      "<title>" .
2874                      sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
2875                      "</title>\n" .
2876                      "<author>" . esc_html($co{'author'}) . "</author>\n" .
2877                      "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
2878                      "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
2879                      "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
2880                      "<description>" . esc_html($co{'title'}) . "</description>\n" .
2881                      "<content:encoded>" .
2882                      "<![CDATA[\n";
2883                my $comment = $co{'comment'};
2884                foreach my $line (@$comment) {
2885                        $line = decode("utf8", $line, Encode::FB_DEFAULT);
2886                        print "$line<br/>\n";
2887                }
2888                print "<br/>\n";
2889                foreach my $line (@difftree) {
2890                        if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
2891                                next;
2892                        }
2893                        my $file = validate_input(unquote($7));
2894                        $file = decode("utf8", $file, Encode::FB_DEFAULT);
2895                        print "$file<br/>\n";
2896                }
2897                print "]]>\n" .
2898                      "</content:encoded>\n" .
2899                      "</item>\n";
2900        }
2901        print "</channel></rss>";
2902}
2903
2904sub git_opml {
2905        my @list = git_get_projects_list();
2906
2907        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
2908        print "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".
2909              "<opml version=\"1.0\">\n".
2910              "<head>".
2911              "  <title>$site_name Git OPML Export</title>\n".
2912              "</head>\n".
2913              "<body>\n".
2914              "<outline text=\"git RSS feeds\">\n";
2915
2916        foreach my $pr (@list) {
2917                my %proj = %$pr;
2918                my $head = git_get_head_hash($proj{'path'});
2919                if (!defined $head) {
2920                        next;
2921                }
2922                $ENV{'GIT_DIR'} = "$projectroot/$proj{'path'}";
2923                my %co = parse_commit($head);
2924                if (!%co) {
2925                        next;
2926                }
2927
2928                my $path = esc_html(chop_str($proj{'path'}, 25, 5));
2929                my $rss  = "$my_url?p=$proj{'path'};a=rss";
2930                my $html = "$my_url?p=$proj{'path'};a=summary";
2931                print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
2932        }
2933        print "</outline>\n".
2934              "</body>\n".
2935              "</opml>\n";
2936}