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