f8d1036744a38a1aa69b8bbe47dd33c90a3c414b
   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        my $hb = shift;
1181
1182        if (!defined $name) {
1183                print "<div class=\"page_path\"><b>/</b></div>\n";
1184        } elsif (defined $type && $type eq 'blob') {
1185                print "<div class=\"page_path\"><b>";
1186                if (defined $hb) {
1187                        print $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hb, file_name=>$file_name)}, esc_html($name));
1188                } else {
1189                        print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name)}, esc_html($name));
1190                }
1191                print "</b><br/></div>\n";
1192        } else {
1193                print "<div class=\"page_path\"><b>" . esc_html($name) . "</b><br/></div>\n";
1194        }
1195}
1196
1197sub git_print_log {
1198        my $log = shift;
1199
1200        # remove leading empty lines
1201        while (defined $log->[0] && $log->[0] eq "") {
1202                shift @$log;
1203        }
1204
1205        # print log
1206        my $signoff = 0;
1207        my $empty = 0;
1208        foreach my $line (@$log) {
1209                # print only one empty line
1210                # do not print empty line after signoff
1211                if ($line eq "") {
1212                        next if ($empty || $signoff);
1213                        $empty = 1;
1214                } else {
1215                        $empty = 0;
1216                }
1217                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1218                        $signoff = 1;
1219                        print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1220                } else {
1221                        $signoff = 0;
1222                        print format_log_line_html($line) . "<br/>\n";
1223                }
1224        }
1225}
1226
1227sub git_print_simplified_log {
1228        my $log = shift;
1229        my $remove_title = shift;
1230
1231        shift @$log if $remove_title;
1232        # remove leading empty lines
1233        while (defined $log->[0] && $log->[0] eq "") {
1234                shift @$log;
1235        }
1236
1237        # simplify and print log
1238        my $empty = 0;
1239        foreach my $line (@$log) {
1240                # remove signoff lines
1241                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1242                        next;
1243                }
1244                # print only one empty line
1245                if ($line eq "") {
1246                        next if $empty;
1247                        $empty = 1;
1248                } else {
1249                        $empty = 0;
1250                }
1251                print format_log_line_html($line) . "<br/>\n";
1252        }
1253        # end with single empty line
1254        print "<br/>\n" unless $empty;
1255}
1256
1257## ......................................................................
1258## functions printing large fragments of HTML
1259
1260sub git_difftree_body {
1261        my ($difftree, $parent) = @_;
1262
1263        print "<div class=\"list_head\">\n";
1264        if ($#{$difftree} > 10) {
1265                print(($#{$difftree} + 1) . " files changed:\n");
1266        }
1267        print "</div>\n";
1268
1269        print "<table class=\"diff_tree\">\n";
1270        my $alternate = 0;
1271        foreach my $line (@{$difftree}) {
1272                # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1273                # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1274                if ($line !~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1275                        next;
1276                }
1277                my $from_mode = $1;
1278                my $to_mode = $2;
1279                my $from_id = $3;
1280                my $to_id = $4;
1281                my $status = $5;
1282                my $similarity = $6; # score
1283                my $file = validate_input(unquote($7));
1284
1285                if ($alternate) {
1286                        print "<tr class=\"dark\">\n";
1287                } else {
1288                        print "<tr class=\"light\">\n";
1289                }
1290                $alternate ^= 1;
1291
1292                if ($status eq "A") { # created
1293                        my $mode_chng = "";
1294                        if (S_ISREG(oct $to_mode)) {
1295                                $mode_chng = sprintf(" with mode: %04o", (oct $to_mode) & 0777);
1296                        }
1297                        print "<td>" .
1298                              $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$file),
1299                                      -class => "list"}, esc_html($file)) .
1300                              "</td>\n" .
1301                              "<td><span class=\"file_status new\">[new " . file_type($to_mode) . "$mode_chng]</span></td>\n" .
1302                              "<td class=\"link\">" .
1303                              $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$file)}, "blob") .
1304                              "</td>\n";
1305
1306                } elsif ($status eq "D") { # deleted
1307                        print "<td>" .
1308                              $cgi->a({-href => href(action=>"blob", hash=>$from_id, hash_base=>$parent, file_name=>$file),
1309                                       -class => "list"}, esc_html($file)) . "</td>\n" .
1310                              "<td><span class=\"file_status deleted\">[deleted " . file_type($from_mode). "]</span></td>\n" .
1311                              "<td class=\"link\">" .
1312                              $cgi->a({-href => href(action=>"blob", hash=>$from_id, hash_base=>$parent, file_name=>$file)}, "blob") . " | " .
1313                              $cgi->a({-href => href(action=>"history", hash_base=>$parent, file_name=>$file)}, "history") .
1314                              "</td>\n"
1315
1316                } elsif ($status eq "M" || $status eq "T") { # modified, or type changed
1317                        my $mode_chnge = "";
1318                        if ($from_mode != $to_mode) {
1319                                $mode_chnge = " <span class=\"file_status mode_chnge\">[changed";
1320                                if (((oct $from_mode) & S_IFMT) != ((oct $to_mode) & S_IFMT)) {
1321                                        $mode_chnge .= " from " . file_type($from_mode) . " to " . file_type($to_mode);
1322                                }
1323                                if (((oct $from_mode) & 0777) != ((oct $to_mode) & 0777)) {
1324                                        if (S_ISREG($from_mode) && S_ISREG($to_mode)) {
1325                                                $mode_chnge .= sprintf(" mode: %04o->%04o", (oct $from_mode) & 0777, (oct $to_mode) & 0777);
1326                                        } elsif (S_ISREG($to_mode)) {
1327                                                $mode_chnge .= sprintf(" mode: %04o", (oct $to_mode) & 0777);
1328                                        }
1329                                }
1330                                $mode_chnge .= "]</span>\n";
1331                        }
1332                        print "<td>";
1333                        if ($to_id ne $from_id) { # modified
1334                                print $cgi->a({-href => href(action=>"blobdiff", hash=>$to_id, hash_parent=>$from_id, hash_base=>$hash, file_name=>$file),
1335                                              -class => "list"}, esc_html($file));
1336                        } else { # mode changed
1337                                print $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$file),
1338                                              -class => "list"}, esc_html($file));
1339                        }
1340                        print "</td>\n" .
1341                              "<td>$mode_chnge</td>\n" .
1342                              "<td class=\"link\">" .
1343                                $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$file)}, "blob");
1344                        if ($to_id ne $from_id) { # modified
1345                                print " | " . $cgi->a({-href => href(action=>"blobdiff", hash=>$to_id, hash_parent=>$from_id, hash_base=>$hash, file_name=>$file)}, "diff");
1346                        }
1347                        print " | " . $cgi->a({-href => href(action=>"history", hash_base=>$hash, file_name=>$file)}, "history") . "\n";
1348                        print "</td>\n";
1349
1350                } elsif ($status eq "R") { # renamed
1351                        my ($from_file, $to_file) = split "\t", $file;
1352                        my $mode_chng = "";
1353                        if ($from_mode != $to_mode) {
1354                                $mode_chng = sprintf(", mode: %04o", (oct $to_mode) & 0777);
1355                        }
1356                        print "<td>" .
1357                              $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$to_file),
1358                                      -class => "list"}, esc_html($to_file)) . "</td>\n" .
1359                              "<td><span class=\"file_status moved\">[moved from " .
1360                              $cgi->a({-href => href(action=>"blob", hash=>$from_id, hash_base=>$parent, file_name=>$from_file),
1361                                      -class => "list"}, esc_html($from_file)) .
1362                              " with " . (int $similarity) . "% similarity$mode_chng]</span></td>\n" .
1363                              "<td class=\"link\">" .
1364                              $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$to_file)}, "blob");
1365                        if ($to_id ne $from_id) {
1366                                print " | " .
1367                                      $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");
1368                        }
1369                        print "</td>\n";
1370
1371                } elsif ($status eq "C") { # copied
1372                        my ($from_file, $to_file) = split "\t", $file;
1373                        my $mode_chng = "";
1374                        if ($from_mode != $to_mode) {
1375                                $mode_chng = sprintf(", mode: %04o", (oct $to_mode) & 0777);
1376                        }
1377                        print "<td>" .
1378                              $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$to_file),
1379                                      -class => "list"}, esc_html($to_file)) . "</td>\n" .
1380                              "<td><span class=\"file_status copied\">[copied from " .
1381                              $cgi->a({-href => href(action=>"blob", hash=>$from_id, hash_base=>$parent, file_name=>$from_file),
1382                                      -class => "list"}, esc_html($from_file)) .
1383                              " with " . (int $similarity) . "% similarity$mode_chng]</span></td>\n" .
1384                              "<td class=\"link\">" .
1385                              $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$to_file)}, "blob");
1386                        if ($to_id ne $from_id) {
1387                                print " | " .
1388                                      $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");
1389                        }
1390                        print "</td>\n";
1391                } # we should not encounter Unmerged (U) or Unknown (X) status
1392                print "</tr>\n";
1393        }
1394        print "</table>\n";
1395}
1396
1397sub git_shortlog_body {
1398        # uses global variable $project
1399        my ($revlist, $from, $to, $refs, $extra) = @_;
1400        my $have_snapshot = git_get_project_config_bool('snapshot');
1401        $from = 0 unless defined $from;
1402        $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
1403
1404        print "<table class=\"shortlog\" cellspacing=\"0\">\n";
1405        my $alternate = 0;
1406        for (my $i = $from; $i <= $to; $i++) {
1407                my $commit = $revlist->[$i];
1408                #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
1409                my $ref = format_ref_marker($refs, $commit);
1410                my %co = parse_commit($commit);
1411                if ($alternate) {
1412                        print "<tr class=\"dark\">\n";
1413                } else {
1414                        print "<tr class=\"light\">\n";
1415                }
1416                $alternate ^= 1;
1417                # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
1418                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1419                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
1420                      "<td>";
1421                print format_subject_html($co{'title'}, $co{'title_short'}, href(action=>"commit", hash=>$commit), $ref);
1422                print "</td>\n" .
1423                      "<td class=\"link\">" .
1424                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1425                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
1426                if ($have_snapshot) {
1427                        print " | " .  $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
1428                }
1429                print "</td>\n" .
1430                      "</tr>\n";
1431        }
1432        if (defined $extra) {
1433                print "<tr>\n" .
1434                      "<td colspan=\"4\">$extra</td>\n" .
1435                      "</tr>\n";
1436        }
1437        print "</table>\n";
1438}
1439
1440sub git_history_body {
1441        # Warning: assumes constant type (blob or tree) during history
1442        my ($fd, $refs, $hash_base, $ftype, $extra) = @_;
1443
1444        print "<table class=\"history\" cellspacing=\"0\">\n";
1445        my $alternate = 0;
1446        while (my $line = <$fd>) {
1447                if ($line !~ m/^([0-9a-fA-F]{40})/) {
1448                        next;
1449                }
1450
1451                my $commit = $1;
1452                my %co = parse_commit($commit);
1453                if (!%co) {
1454                        next;
1455                }
1456
1457                my $ref = format_ref_marker($refs, $commit);
1458
1459                if ($alternate) {
1460                        print "<tr class=\"dark\">\n";
1461                } else {
1462                        print "<tr class=\"light\">\n";
1463                }
1464                $alternate ^= 1;
1465                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1466                      # shortlog uses      chop_str($co{'author_name'}, 10)
1467                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
1468                      "<td>";
1469                # originally git_history used chop_str($co{'title'}, 50)
1470                print format_subject_html($co{'title'}, $co{'title_short'}, href(action=>"commit", hash=>$commit), $ref);
1471                print "</td>\n" .
1472                      "<td class=\"link\">" .
1473                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1474                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
1475                      $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype);
1476
1477                if ($ftype eq 'blob') {
1478                        my $blob_current = git_get_hash_by_path($hash_base, $file_name);
1479                        my $blob_parent  = git_get_hash_by_path($commit, $file_name);
1480                        if (defined $blob_current && defined $blob_parent &&
1481                                        $blob_current ne $blob_parent) {
1482                                print " | " .
1483                                        $cgi->a({-href => href(action=>"blobdiff", hash=>$blob_current, hash_parent=>$blob_parent, hash_base=>$commit, file_name=>$file_name)},
1484                                                "diff to current");
1485                        }
1486                }
1487                print "</td>\n" .
1488                      "</tr>\n";
1489        }
1490        if (defined $extra) {
1491                print "<tr>\n" .
1492                      "<td colspan=\"4\">$extra</td>\n" .
1493                      "</tr>\n";
1494        }
1495        print "</table>\n";
1496}
1497
1498sub git_tags_body {
1499        # uses global variable $project
1500        my ($taglist, $from, $to, $extra) = @_;
1501        $from = 0 unless defined $from;
1502        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
1503
1504        print "<table class=\"tags\" cellspacing=\"0\">\n";
1505        my $alternate = 0;
1506        for (my $i = $from; $i <= $to; $i++) {
1507                my $entry = $taglist->[$i];
1508                my %tag = %$entry;
1509                my $comment_lines = $tag{'comment'};
1510                my $comment = shift @$comment_lines;
1511                my $comment_short;
1512                if (defined $comment) {
1513                        $comment_short = chop_str($comment, 30, 5);
1514                }
1515                if ($alternate) {
1516                        print "<tr class=\"dark\">\n";
1517                } else {
1518                        print "<tr class=\"light\">\n";
1519                }
1520                $alternate ^= 1;
1521                print "<td><i>$tag{'age'}</i></td>\n" .
1522                      "<td>" .
1523                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
1524                               -class => "list"}, "<b>" . esc_html($tag{'name'}) . "</b>") .
1525                      "</td>\n" .
1526                      "<td>";
1527                if (defined $comment) {
1528                        print format_subject_html($comment, $comment_short, href(action=>"tag", hash=>$tag{'id'}));
1529                }
1530                print "</td>\n" .
1531                      "<td class=\"selflink\">";
1532                if ($tag{'type'} eq "tag") {
1533                        print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
1534                } else {
1535                        print "&nbsp;";
1536                }
1537                print "</td>\n" .
1538                      "<td class=\"link\">" . " | " .
1539                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
1540                if ($tag{'reftype'} eq "commit") {
1541                        print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
1542                              " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'refid'})}, "log");
1543                } elsif ($tag{'reftype'} eq "blob") {
1544                        print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
1545                }
1546                print "</td>\n" .
1547                      "</tr>";
1548        }
1549        if (defined $extra) {
1550                print "<tr>\n" .
1551                      "<td colspan=\"5\">$extra</td>\n" .
1552                      "</tr>\n";
1553        }
1554        print "</table>\n";
1555}
1556
1557sub git_heads_body {
1558        # uses global variable $project
1559        my ($taglist, $head, $from, $to, $extra) = @_;
1560        $from = 0 unless defined $from;
1561        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
1562
1563        print "<table class=\"heads\" cellspacing=\"0\">\n";
1564        my $alternate = 0;
1565        for (my $i = $from; $i <= $to; $i++) {
1566                my $entry = $taglist->[$i];
1567                my %tag = %$entry;
1568                my $curr = $tag{'id'} eq $head;
1569                if ($alternate) {
1570                        print "<tr class=\"dark\">\n";
1571                } else {
1572                        print "<tr class=\"light\">\n";
1573                }
1574                $alternate ^= 1;
1575                print "<td><i>$tag{'age'}</i></td>\n" .
1576                      ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
1577                      $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'}),
1578                               -class => "list"}, "<b>" . esc_html($tag{'name'}) . "</b>") .
1579                      "</td>\n" .
1580                      "<td class=\"link\">" .
1581                      $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") . " | " .
1582                      $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log") .
1583                      "</td>\n" .
1584                      "</tr>";
1585        }
1586        if (defined $extra) {
1587                print "<tr>\n" .
1588                      "<td colspan=\"3\">$extra</td>\n" .
1589                      "</tr>\n";
1590        }
1591        print "</table>\n";
1592}
1593
1594## ----------------------------------------------------------------------
1595## functions printing large fragments, format as one of arguments
1596
1597sub git_diff_print {
1598        my $from = shift;
1599        my $from_name = shift;
1600        my $to = shift;
1601        my $to_name = shift;
1602        my $format = shift || "html";
1603
1604        my $from_tmp = "/dev/null";
1605        my $to_tmp = "/dev/null";
1606        my $pid = $$;
1607
1608        # create tmp from-file
1609        if (defined $from) {
1610                $from_tmp = "$git_temp/gitweb_" . $$ . "_from";
1611                open my $fd2, "> $from_tmp";
1612                open my $fd, "-|", $GIT, "cat-file", "blob", $from;
1613                my @file = <$fd>;
1614                print $fd2 @file;
1615                close $fd2;
1616                close $fd;
1617        }
1618
1619        # create tmp to-file
1620        if (defined $to) {
1621                $to_tmp = "$git_temp/gitweb_" . $$ . "_to";
1622                open my $fd2, "> $to_tmp";
1623                open my $fd, "-|", $GIT, "cat-file", "blob", $to;
1624                my @file = <$fd>;
1625                print $fd2 @file;
1626                close $fd2;
1627                close $fd;
1628        }
1629
1630        open my $fd, "-|", "/usr/bin/diff -u -p -L \'$from_name\' -L \'$to_name\' $from_tmp $to_tmp";
1631        if ($format eq "plain") {
1632                undef $/;
1633                print <$fd>;
1634                $/ = "\n";
1635        } else {
1636                while (my $line = <$fd>) {
1637                        chomp $line;
1638                        my $char = substr($line, 0, 1);
1639                        my $diff_class = "";
1640                        if ($char eq '+') {
1641                                $diff_class = " add";
1642                        } elsif ($char eq "-") {
1643                                $diff_class = " rem";
1644                        } elsif ($char eq "@") {
1645                                $diff_class = " chunk_header";
1646                        } elsif ($char eq "\\") {
1647                                # skip errors
1648                                next;
1649                        }
1650                        $line = untabify($line);
1651                        print "<div class=\"diff$diff_class\">" . esc_html($line) . "</div>\n";
1652                }
1653        }
1654        close $fd;
1655
1656        if (defined $from) {
1657                unlink($from_tmp);
1658        }
1659        if (defined $to) {
1660                unlink($to_tmp);
1661        }
1662}
1663
1664
1665## ======================================================================
1666## ======================================================================
1667## actions
1668
1669sub git_project_list {
1670        my $order = $cgi->param('o');
1671        if (defined $order && $order !~ m/project|descr|owner|age/) {
1672                die_error(undef, "Unknown order parameter");
1673        }
1674
1675        my @list = git_get_projects_list();
1676        my @projects;
1677        if (!@list) {
1678                die_error(undef, "No projects found");
1679        }
1680        foreach my $pr (@list) {
1681                my $head = git_get_head_hash($pr->{'path'});
1682                if (!defined $head) {
1683                        next;
1684                }
1685                $ENV{'GIT_DIR'} = "$projectroot/$pr->{'path'}";
1686                my %co = parse_commit($head);
1687                if (!%co) {
1688                        next;
1689                }
1690                $pr->{'commit'} = \%co;
1691                if (!defined $pr->{'descr'}) {
1692                        my $descr = git_get_project_description($pr->{'path'}) || "";
1693                        $pr->{'descr'} = chop_str($descr, 25, 5);
1694                }
1695                if (!defined $pr->{'owner'}) {
1696                        $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
1697                }
1698                push @projects, $pr;
1699        }
1700
1701        git_header_html();
1702        if (-f $home_text) {
1703                print "<div class=\"index_include\">\n";
1704                open (my $fd, $home_text);
1705                print <$fd>;
1706                close $fd;
1707                print "</div>\n";
1708        }
1709        print "<table class=\"project_list\">\n" .
1710              "<tr>\n";
1711        $order ||= "project";
1712        if ($order eq "project") {
1713                @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
1714                print "<th>Project</th>\n";
1715        } else {
1716                print "<th>" .
1717                      $cgi->a({-href => "$my_uri?" . esc_param("o=project"),
1718                               -class => "header"}, "Project") .
1719                      "</th>\n";
1720        }
1721        if ($order eq "descr") {
1722                @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
1723                print "<th>Description</th>\n";
1724        } else {
1725                print "<th>" .
1726                      $cgi->a({-href => "$my_uri?" . esc_param("o=descr"),
1727                               -class => "header"}, "Description") .
1728                      "</th>\n";
1729        }
1730        if ($order eq "owner") {
1731                @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
1732                print "<th>Owner</th>\n";
1733        } else {
1734                print "<th>" .
1735                      $cgi->a({-href => "$my_uri?" . esc_param("o=owner"),
1736                               -class => "header"}, "Owner") .
1737                      "</th>\n";
1738        }
1739        if ($order eq "age") {
1740                @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
1741                print "<th>Last Change</th>\n";
1742        } else {
1743                print "<th>" .
1744                      $cgi->a({-href => "$my_uri?" . esc_param("o=age"),
1745                               -class => "header"}, "Last Change") .
1746                      "</th>\n";
1747        }
1748        print "<th></th>\n" .
1749              "</tr>\n";
1750        my $alternate = 0;
1751        foreach my $pr (@projects) {
1752                if ($alternate) {
1753                        print "<tr class=\"dark\">\n";
1754                } else {
1755                        print "<tr class=\"light\">\n";
1756                }
1757                $alternate ^= 1;
1758                print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
1759                                        -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
1760                      "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
1761                      "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
1762                print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" .
1763                      $pr->{'commit'}{'age_string'} . "</td>\n" .
1764                      "<td class=\"link\">" .
1765                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
1766                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
1767                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") .
1768                      "</td>\n" .
1769                      "</tr>\n";
1770        }
1771        print "</table>\n";
1772        git_footer_html();
1773}
1774
1775sub git_summary {
1776        my $descr = git_get_project_description($project) || "none";
1777        my $head = git_get_head_hash($project);
1778        my %co = parse_commit($head);
1779        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
1780
1781        my $owner = git_get_project_owner($project);
1782
1783        my $refs = git_get_references();
1784        git_header_html();
1785        git_print_page_nav('summary','', $head);
1786
1787        print "<div class=\"title\">&nbsp;</div>\n";
1788        print "<table cellspacing=\"0\">\n" .
1789              "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
1790              "<tr><td>owner</td><td>$owner</td></tr>\n" .
1791              "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
1792        # use per project git URL list in $projectroot/$project/cloneurl
1793        # or make project git URL from git base URL and project name
1794        my $url_tag = "URL";
1795        my @url_list = git_get_project_url_list($project);
1796        @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
1797        foreach my $git_url (@url_list) {
1798                next unless $git_url;
1799                print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
1800                $url_tag = "";
1801        }
1802        print "</table>\n";
1803
1804        open my $fd, "-|", $GIT, "rev-list", "--max-count=17", git_get_head_hash($project)
1805                or die_error(undef, "Open git-rev-list failed");
1806        my @revlist = map { chomp; $_ } <$fd>;
1807        close $fd;
1808        git_print_header_div('shortlog');
1809        git_shortlog_body(\@revlist, 0, 15, $refs,
1810                          $cgi->a({-href => href(action=>"shortlog")}, "..."));
1811
1812        my $taglist = git_get_refs_list("refs/tags");
1813        if (defined @$taglist) {
1814                git_print_header_div('tags');
1815                git_tags_body($taglist, 0, 15,
1816                              $cgi->a({-href => href(action=>"tags")}, "..."));
1817        }
1818
1819        my $headlist = git_get_refs_list("refs/heads");
1820        if (defined @$headlist) {
1821                git_print_header_div('heads');
1822                git_heads_body($headlist, $head, 0, 15,
1823                               $cgi->a({-href => href(action=>"heads")}, "..."));
1824        }
1825
1826        git_footer_html();
1827}
1828
1829sub git_tag {
1830        my $head = git_get_head_hash($project);
1831        git_header_html();
1832        git_print_page_nav('','', $head,undef,$head);
1833        my %tag = parse_tag($hash);
1834        git_print_header_div('commit', esc_html($tag{'name'}), $hash);
1835        print "<div class=\"title_text\">\n" .
1836              "<table cellspacing=\"0\">\n" .
1837              "<tr>\n" .
1838              "<td>object</td>\n" .
1839              "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})}, $tag{'object'}) . "</td>\n" .
1840              "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})}, $tag{'type'}) . "</td>\n" .
1841              "</tr>\n";
1842        if (defined($tag{'author'})) {
1843                my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
1844                print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
1845                print "<tr><td></td><td>" . $ad{'rfc2822'} . sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) . "</td></tr>\n";
1846        }
1847        print "</table>\n\n" .
1848              "</div>\n";
1849        print "<div class=\"page_body\">";
1850        my $comment = $tag{'comment'};
1851        foreach my $line (@$comment) {
1852                print esc_html($line) . "<br/>\n";
1853        }
1854        print "</div>\n";
1855        git_footer_html();
1856}
1857
1858sub git_blame2 {
1859        my $fd;
1860        my $ftype;
1861        die_error(undef, "Permission denied") if (!git_get_project_config_bool ('blame'));
1862        die_error('404 Not Found', "File name not defined") if (!$file_name);
1863        $hash_base ||= git_get_head_hash($project);
1864        die_error(undef, "Couldn't find base commit") unless ($hash_base);
1865        my %co = parse_commit($hash_base)
1866                or die_error(undef, "Reading commit failed");
1867        if (!defined $hash) {
1868                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
1869                        or die_error(undef, "Error looking up file");
1870        }
1871        $ftype = git_get_type($hash);
1872        if ($ftype !~ "blob") {
1873                die_error("400 Bad Request", "Object is not a blob");
1874        }
1875        open ($fd, "-|", $GIT, "blame", '-l', $file_name, $hash_base)
1876                or die_error(undef, "Open git-blame failed");
1877        git_header_html();
1878        my $formats_nav =
1879                $cgi->a({-href => href(action=>"blobl", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)}, "blob") .
1880                " | " . $cgi->a({-href => href(action=>"blame", file_name=>$file_name)}, "head");
1881        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
1882        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
1883        git_print_page_path($file_name, $ftype, $hash_base);
1884        my @rev_color = (qw(light2 dark2));
1885        my $num_colors = scalar(@rev_color);
1886        my $current_color = 0;
1887        my $last_rev;
1888        print "<div class=\"page_body\">\n";
1889        print "<table class=\"blame\">\n";
1890        print "<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n";
1891        while (<$fd>) {
1892                /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
1893                my $full_rev = $1;
1894                my $rev = substr($full_rev, 0, 8);
1895                my $lineno = $2;
1896                my $data = $3;
1897
1898                if (!defined $last_rev) {
1899                        $last_rev = $full_rev;
1900                } elsif ($last_rev ne $full_rev) {
1901                        $last_rev = $full_rev;
1902                        $current_color = ++$current_color % $num_colors;
1903                }
1904                print "<tr class=\"$rev_color[$current_color]\">\n";
1905                print "<td class=\"sha1\">" .
1906                        $cgi->a({-href => href(action=>"commit", hash=>$full_rev, file_name=>$file_name)}, esc_html($rev)) . "</td>\n";
1907                print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" . esc_html($lineno) . "</a></td>\n";
1908                print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
1909                print "</tr>\n";
1910        }
1911        print "</table>\n";
1912        print "</div>";
1913        close $fd or print "Reading blob failed\n";
1914        git_footer_html();
1915}
1916
1917sub git_blame {
1918        my $fd;
1919        die_error('403 Permission denied', "Permission denied") if (!git_get_project_config_bool ('blame'));
1920        die_error('404 Not Found', "File name not defined") if (!$file_name);
1921        $hash_base ||= git_get_head_hash($project);
1922        die_error(undef, "Couldn't find base commit") unless ($hash_base);
1923        my %co = parse_commit($hash_base)
1924                or die_error(undef, "Reading commit failed");
1925        if (!defined $hash) {
1926                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
1927                        or die_error(undef, "Error lookup file");
1928        }
1929        open ($fd, "-|", $GIT, "annotate", '-l', '-t', '-r', $file_name, $hash_base)
1930                or die_error(undef, "Open git-annotate failed");
1931        git_header_html();
1932        my $formats_nav =
1933                $cgi->a({-href => href(action=>"blobl", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)}, "blob") .
1934                " | " . $cgi->a({-href => href(action=>"blame", file_name=>$file_name)}, "head");
1935        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
1936        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
1937        git_print_page_path($file_name, 'blob', $hash_base);
1938        print "<div class=\"page_body\">\n";
1939        print <<HTML;
1940<table class="blame">
1941  <tr>
1942    <th>Commit</th>
1943    <th>Age</th>
1944    <th>Author</th>
1945    <th>Line</th>
1946    <th>Data</th>
1947  </tr>
1948HTML
1949        my @line_class = (qw(light dark));
1950        my $line_class_len = scalar (@line_class);
1951        my $line_class_num = $#line_class;
1952        while (my $line = <$fd>) {
1953                my $long_rev;
1954                my $short_rev;
1955                my $author;
1956                my $time;
1957                my $lineno;
1958                my $data;
1959                my $age;
1960                my $age_str;
1961                my $age_class;
1962
1963                chomp $line;
1964                $line_class_num = ($line_class_num + 1) % $line_class_len;
1965
1966                if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) \+\d\d\d\d\t(\d+)\)(.*)$/) {
1967                        $long_rev = $1;
1968                        $author   = $2;
1969                        $time     = $3;
1970                        $lineno   = $4;
1971                        $data     = $5;
1972                } else {
1973                        print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
1974                        next;
1975                }
1976                $short_rev  = substr ($long_rev, 0, 8);
1977                $age        = time () - $time;
1978                $age_str    = age_string ($age);
1979                $age_str    =~ s/ /&nbsp;/g;
1980                $age_class  = age_class($age);
1981                $author     = esc_html ($author);
1982                $author     =~ s/ /&nbsp;/g;
1983
1984                $data = untabify($data);
1985                $data = esc_html ($data);
1986
1987                print <<HTML;
1988  <tr class="$line_class[$line_class_num]">
1989    <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
1990    <td class="$age_class">$age_str</td>
1991    <td>$author</td>
1992    <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
1993    <td class="pre">$data</td>
1994  </tr>
1995HTML
1996        } # while (my $line = <$fd>)
1997        print "</table>\n\n";
1998        close $fd or print "Reading blob failed.\n";
1999        print "</div>";
2000        git_footer_html();
2001}
2002
2003sub git_tags {
2004        my $head = git_get_head_hash($project);
2005        git_header_html();
2006        git_print_page_nav('','', $head,undef,$head);
2007        git_print_header_div('summary', $project);
2008
2009        my $taglist = git_get_refs_list("refs/tags");
2010        if (defined @$taglist) {
2011                git_tags_body($taglist);
2012        }
2013        git_footer_html();
2014}
2015
2016sub git_heads {
2017        my $head = git_get_head_hash($project);
2018        git_header_html();
2019        git_print_page_nav('','', $head,undef,$head);
2020        git_print_header_div('summary', $project);
2021
2022        my $taglist = git_get_refs_list("refs/heads");
2023        if (defined @$taglist) {
2024                git_heads_body($taglist, $head);
2025        }
2026        git_footer_html();
2027}
2028
2029sub git_blob_plain {
2030        if (!defined $hash) {
2031                if (defined $file_name) {
2032                        my $base = $hash_base || git_get_head_hash($project);
2033                        $hash = git_get_hash_by_path($base, $file_name, "blob")
2034                                or die_error(undef, "Error lookup file");
2035                } else {
2036                        die_error(undef, "No file name defined");
2037                }
2038        }
2039        my $type = shift;
2040        open my $fd, "-|", $GIT, "cat-file", "blob", $hash
2041                or die_error(undef, "Couldn't cat $file_name, $hash");
2042
2043        $type ||= blob_mimetype($fd, $file_name);
2044
2045        # save as filename, even when no $file_name is given
2046        my $save_as = "$hash";
2047        if (defined $file_name) {
2048                $save_as = $file_name;
2049        } elsif ($type =~ m/^text\//) {
2050                $save_as .= '.txt';
2051        }
2052
2053        print $cgi->header(-type => "$type", '-content-disposition' => "inline; filename=\"$save_as\"");
2054        undef $/;
2055        binmode STDOUT, ':raw';
2056        print <$fd>;
2057        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2058        $/ = "\n";
2059        close $fd;
2060}
2061
2062sub git_blob {
2063        if (!defined $hash) {
2064                if (defined $file_name) {
2065                        my $base = $hash_base || git_get_head_hash($project);
2066                        $hash = git_get_hash_by_path($base, $file_name, "blob")
2067                                or die_error(undef, "Error lookup file");
2068                } else {
2069                        die_error(undef, "No file name defined");
2070                }
2071        }
2072        my $have_blame = git_get_project_config_bool ('blame');
2073        open my $fd, "-|", $GIT, "cat-file", "blob", $hash
2074                or die_error(undef, "Couldn't cat $file_name, $hash");
2075        my $mimetype = blob_mimetype($fd, $file_name);
2076        if ($mimetype !~ m/^text\//) {
2077                close $fd;
2078                return git_blob_plain($mimetype);
2079        }
2080        git_header_html();
2081        my $formats_nav = '';
2082        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2083                if (defined $file_name) {
2084                        if ($have_blame) {
2085                                $formats_nav .= $cgi->a({-href => href(action=>"blame", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)}, "blame") . " | ";
2086                        }
2087                        $formats_nav .=
2088                                $cgi->a({-href => href(action=>"blob_plain", hash=>$hash, file_name=>$file_name)}, "plain") .
2089                                " | " . $cgi->a({-href => href(action=>"blob", hash_base=>"HEAD", file_name=>$file_name)}, "head");
2090                } else {
2091                        $formats_nav .= $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "plain");
2092                }
2093                git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2094                git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2095        } else {
2096                print "<div class=\"page_nav\">\n" .
2097                      "<br/><br/></div>\n" .
2098                      "<div class=\"title\">$hash</div>\n";
2099        }
2100        git_print_page_path($file_name, "blob", $hash_base);
2101        print "<div class=\"page_body\">\n";
2102        my $nr;
2103        while (my $line = <$fd>) {
2104                chomp $line;
2105                $nr++;
2106                $line = untabify($line);
2107                printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n", $nr, $nr, $nr, esc_html($line);
2108        }
2109        close $fd or print "Reading blob failed.\n";
2110        print "</div>";
2111        git_footer_html();
2112}
2113
2114sub git_tree {
2115        if (!defined $hash) {
2116                $hash = git_get_head_hash($project);
2117                if (defined $file_name) {
2118                        my $base = $hash_base || $hash;
2119                        $hash = git_get_hash_by_path($base, $file_name, "tree");
2120                }
2121                if (!defined $hash_base) {
2122                        $hash_base = $hash;
2123                }
2124        }
2125        $/ = "\0";
2126        open my $fd, "-|", $GIT, "ls-tree", '-z', $hash
2127                or die_error(undef, "Open git-ls-tree failed");
2128        my @entries = map { chomp; $_ } <$fd>;
2129        close $fd or die_error(undef, "Reading tree failed");
2130        $/ = "\n";
2131
2132        my $refs = git_get_references();
2133        my $ref = format_ref_marker($refs, $hash_base);
2134        git_header_html();
2135        my %base_key = ();
2136        my $base = "";
2137        my $have_blame = git_get_project_config_bool ('blame');
2138        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2139                $base_key{hash_base} = $hash_base;
2140                git_print_page_nav('tree','', $hash_base);
2141                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
2142        } else {
2143                print "<div class=\"page_nav\">\n";
2144                print "<br/><br/></div>\n";
2145                print "<div class=\"title\">$hash</div>\n";
2146        }
2147        if (defined $file_name) {
2148                $base = esc_html("$file_name/");
2149        }
2150        git_print_page_path($file_name, 'tree', $hash_base);
2151        print "<div class=\"page_body\">\n";
2152        print "<table cellspacing=\"0\">\n";
2153        my $alternate = 0;
2154        foreach my $line (@entries) {
2155                #'100644        blob    0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa        panic.c'
2156                $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
2157                my $t_mode = $1;
2158                my $t_type = $2;
2159                my $t_hash = $3;
2160                my $t_name = validate_input($4);
2161                if ($alternate) {
2162                        print "<tr class=\"dark\">\n";
2163                } else {
2164                        print "<tr class=\"light\">\n";
2165                }
2166                $alternate ^= 1;
2167                print "<td class=\"mode\">" . mode_str($t_mode) . "</td>\n";
2168                if ($t_type eq "blob") {
2169                        print "<td class=\"list\">" .
2170                              $cgi->a({-href => href(action=>"blob", hash=>$t_hash, file_name=>"$base$t_name", %base_key), -class => "list"}, esc_html($t_name)) .
2171                              "</td>\n" .
2172                              "<td class=\"link\">" .
2173                              $cgi->a({-href => href(action=>"blob", hash=>$t_hash, file_name=>"$base$t_name", %base_key)}, "blob");
2174                        if ($have_blame) {
2175                                print " | " . $cgi->a({-href => href(action=>"blame", hash=>$t_hash, file_name=>"$base$t_name", %base_key)}, "blame");
2176                        }
2177                        print " | " . $cgi->a({-href => href(action=>"history", hash=>$t_hash, hash_base=>$hash_base, file_name=>"$base$t_name")}, "history") .
2178                              " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$t_hash, file_name=>"$base$t_name")}, "raw") .
2179                              "</td>\n";
2180                } elsif ($t_type eq "tree") {
2181                        print "<td class=\"list\">" .
2182                              $cgi->a({-href => href(action=>"tree", hash=>$t_hash, file_name=>"$base$t_name", %base_key)}, esc_html($t_name)) .
2183                              "</td>\n" .
2184                              "<td class=\"link\">" .
2185                              $cgi->a({-href => href(action=>"tree", hash=>$t_hash, file_name=>"$base$t_name", %base_key)}, "tree") .
2186                              " | " . $cgi->a({-href => href(action=>"history", hash_base=>$hash_base, file_name=>"$base$t_name")}, "history") .
2187                              "</td>\n";
2188                }
2189                print "</tr>\n";
2190        }
2191        print "</table>\n" .
2192              "</div>";
2193        git_footer_html();
2194}
2195
2196sub git_snapshot {
2197
2198        if (!defined $hash) {
2199                $hash = git_get_head_hash($project);
2200        }
2201
2202        my $filename = basename($project) . "-$hash.tar.gz";
2203
2204        print $cgi->header(-type => 'application/x-tar',
2205                        -content-encoding => 'x-gzip',
2206                        '-content-disposition' => "inline; filename=\"$filename\"",
2207                        -status => '200 OK');
2208
2209        open my $fd, "-|", "$GIT tar-tree $hash \'$project\' | gzip" or
2210                                die_error(undef, "Execute git-tar-tree failed.");
2211        binmode STDOUT, ':raw';
2212        print <$fd>;
2213        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2214        close $fd;
2215
2216
2217}
2218
2219sub git_log {
2220        my $head = git_get_head_hash($project);
2221        if (!defined $hash) {
2222                $hash = $head;
2223        }
2224        if (!defined $page) {
2225                $page = 0;
2226        }
2227        my $refs = git_get_references();
2228
2229        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2230        open my $fd, "-|", $GIT, "rev-list", $limit, $hash
2231                or die_error(undef, "Open git-rev-list failed");
2232        my @revlist = map { chomp; $_ } <$fd>;
2233        close $fd;
2234
2235        my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
2236
2237        git_header_html();
2238        git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
2239
2240        if (!@revlist) {
2241                my %co = parse_commit($hash);
2242
2243                git_print_header_div('summary', $project);
2244                print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
2245        }
2246        for (my $i = ($page * 100); $i <= $#revlist; $i++) {
2247                my $commit = $revlist[$i];
2248                my $ref = format_ref_marker($refs, $commit);
2249                my %co = parse_commit($commit);
2250                next if !%co;
2251                my %ad = parse_date($co{'author_epoch'});
2252                git_print_header_div('commit',
2253                               "<span class=\"age\">$co{'age_string'}</span>" .
2254                               esc_html($co{'title'}) . $ref,
2255                               $commit);
2256                print "<div class=\"title_text\">\n" .
2257                      "<div class=\"log_link\">\n" .
2258                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
2259                      " | " . $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
2260                      "<br/>\n" .
2261                      "</div>\n" .
2262                      "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
2263                      "</div>\n";
2264
2265                print "<div class=\"log_body\">\n";
2266                git_print_simplified_log($co{'comment'});
2267                print "</div>\n";
2268        }
2269        git_footer_html();
2270}
2271
2272sub git_commit {
2273        my %co = parse_commit($hash);
2274        if (!%co) {
2275                die_error(undef, "Unknown commit object");
2276        }
2277        my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2278        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2279
2280        my $parent = $co{'parent'};
2281        if (!defined $parent) {
2282                $parent = "--root";
2283        }
2284        open my $fd, "-|", $GIT, "diff-tree", '-r', '-M', $parent, $hash
2285                or die_error(undef, "Open git-diff-tree failed");
2286        my @difftree = map { chomp; $_ } <$fd>;
2287        close $fd or die_error(undef, "Reading git-diff-tree failed");
2288
2289        # non-textual hash id's can be cached
2290        my $expires;
2291        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2292                $expires = "+1d";
2293        }
2294        my $refs = git_get_references();
2295        my $ref = format_ref_marker($refs, $co{'id'});
2296        my $have_snapshot = git_get_project_config_bool('snapshot');
2297        my $formats_nav = '';
2298        if (defined $file_name && defined $co{'parent'}) {
2299                my $parent = $co{'parent'};
2300                $formats_nav .= $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)}, "blame");
2301        }
2302        git_header_html(undef, $expires);
2303        git_print_page_nav('commit', defined $co{'parent'} ? '' : 'commitdiff',
2304                     $hash, $co{'tree'}, $hash,
2305                     $formats_nav);
2306
2307        if (defined $co{'parent'}) {
2308                git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
2309        } else {
2310                git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
2311        }
2312        print "<div class=\"title_text\">\n" .
2313              "<table cellspacing=\"0\">\n";
2314        print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
2315              "<tr>" .
2316              "<td></td><td> $ad{'rfc2822'}";
2317        if ($ad{'hour_local'} < 6) {
2318                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2319        } else {
2320                printf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2321        }
2322        print "</td>" .
2323              "</tr>\n";
2324        print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
2325        print "<tr><td></td><td> $cd{'rfc2822'}" . sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) . "</td></tr>\n";
2326        print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
2327        print "<tr>" .
2328              "<td>tree</td>" .
2329              "<td class=\"sha1\">" .
2330              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash), class => "list"}, $co{'tree'}) .
2331              "</td>" .
2332              "<td class=\"link\">" . $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)}, "tree");
2333        if ($have_snapshot) {
2334                print " | " .  $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
2335        }
2336        print "</td>" .
2337              "</tr>\n";
2338        my $parents = $co{'parents'};
2339        foreach my $par (@$parents) {
2340                print "<tr>" .
2341                      "<td>parent</td>" .
2342                      "<td class=\"sha1\">" . $cgi->a({-href => href(action=>"commit", hash=>$par), class => "list"}, $par) . "</td>" .
2343                      "<td class=\"link\">" .
2344                      $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
2345                      " | " . $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "commitdiff") .
2346                      "</td>" .
2347                      "</tr>\n";
2348        }
2349        print "</table>".
2350              "</div>\n";
2351
2352        print "<div class=\"page_body\">\n";
2353        git_print_log($co{'comment'});
2354        print "</div>\n";
2355
2356        git_difftree_body(\@difftree, $parent);
2357
2358        git_footer_html();
2359}
2360
2361sub git_blobdiff {
2362        mkdir($git_temp, 0700);
2363        git_header_html();
2364        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2365                my $formats_nav =
2366                        $cgi->a({-href => href(action=>"blobdiff_plain", hash=>$hash, hash_parent=>$hash_parent)}, "plain");
2367                git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2368                git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2369        } else {
2370                print "<div class=\"page_nav\">\n" .
2371                      "<br/><br/></div>\n" .
2372                      "<div class=\"title\">$hash vs $hash_parent</div>\n";
2373        }
2374        git_print_page_path($file_name, "blob", $hash_base);
2375        print "<div class=\"page_body\">\n" .
2376              "<div class=\"diff_info\">blob:" .
2377              $cgi->a({-href => href(action=>"blob", hash=>$hash_parent, hash_base=>$hash_base, file_name=>($file_parent || $file_name))}, $hash_parent) .
2378              " -> blob:" .
2379              $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)}, $hash) .
2380              "</div>\n";
2381        git_diff_print($hash_parent, $file_name || $hash_parent, $hash, $file_name || $hash);
2382        print "</div>";
2383        git_footer_html();
2384}
2385
2386sub git_blobdiff_plain {
2387        mkdir($git_temp, 0700);
2388        print $cgi->header(-type => "text/plain", -charset => 'utf-8');
2389        git_diff_print($hash_parent, $file_name || $hash_parent, $hash, $file_name || $hash, "plain");
2390}
2391
2392sub git_commitdiff {
2393        mkdir($git_temp, 0700);
2394        my %co = parse_commit($hash);
2395        if (!%co) {
2396                die_error(undef, "Unknown commit object");
2397        }
2398        if (!defined $hash_parent) {
2399                $hash_parent = $co{'parent'} || '--root';
2400        }
2401        open my $fd, "-|", $GIT, "diff-tree", '-r', $hash_parent, $hash
2402                or die_error(undef, "Open git-diff-tree failed");
2403        my @difftree = map { chomp; $_ } <$fd>;
2404        close $fd or die_error(undef, "Reading git-diff-tree failed");
2405
2406        # non-textual hash id's can be cached
2407        my $expires;
2408        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2409                $expires = "+1d";
2410        }
2411        my $refs = git_get_references();
2412        my $ref = format_ref_marker($refs, $co{'id'});
2413        my $formats_nav =
2414                $cgi->a({-href => href(action=>"commitdiff_plain", hash=>$hash, hash_parent=>$hash_parent)}, "plain");
2415        git_header_html(undef, $expires);
2416        git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
2417        git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
2418        print "<div class=\"page_body\">\n";
2419        git_print_simplified_log($co{'comment'}, 1); # skip title
2420        print "<br/>\n";
2421        foreach my $line (@difftree) {
2422                # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M      ls-files.c'
2423                # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M      rev-tree.c'
2424                if ($line !~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
2425                        next;
2426                }
2427                my $from_mode = $1;
2428                my $to_mode = $2;
2429                my $from_id = $3;
2430                my $to_id = $4;
2431                my $status = $5;
2432                my $file = validate_input(unquote($6));
2433                if ($status eq "A") {
2434                        print "<div class=\"diff_info\">" . file_type($to_mode) . ":" .
2435                              $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$file)}, $to_id) . "(new)" .
2436                              "</div>\n";
2437                        git_diff_print(undef, "/dev/null", $to_id, "b/$file");
2438                } elsif ($status eq "D") {
2439                        print "<div class=\"diff_info\">" . file_type($from_mode) . ":" .
2440                              $cgi->a({-href => href(action=>"blob", hash=>$from_id, hash_base=>$hash_parent, file_name=>$file)}, $from_id) . "(deleted)" .
2441                              "</div>\n";
2442                        git_diff_print($from_id, "a/$file", undef, "/dev/null");
2443                } elsif ($status eq "M") {
2444                        if ($from_id ne $to_id) {
2445                                print "<div class=\"diff_info\">" .
2446                                      file_type($from_mode) . ":" .
2447                                      $cgi->a({-href => href(action=>"blob", hash=>$from_id, hash_base=>$hash_parent, file_name=>$file)}, $from_id) .
2448                                      " -> " .
2449                                      file_type($to_mode) . ":" .
2450                                      $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$file)}, $to_id);
2451                                print "</div>\n";
2452                                git_diff_print($from_id, "a/$file",  $to_id, "b/$file");
2453                        }
2454                }
2455        }
2456        print "<br/>\n" .
2457              "</div>";
2458        git_footer_html();
2459}
2460
2461sub git_commitdiff_plain {
2462        mkdir($git_temp, 0700);
2463        my %co = parse_commit($hash);
2464        if (!%co) {
2465                die_error(undef, "Unknown commit object");
2466        }
2467        if (!defined $hash_parent) {
2468                $hash_parent = $co{'parent'} || '--root';
2469        }
2470        open my $fd, "-|", $GIT, "diff-tree", '-r', $hash_parent, $hash
2471                or die_error(undef, "Open git-diff-tree failed");
2472        my @difftree = map { chomp; $_ } <$fd>;
2473        close $fd or die_error(undef, "Reading diff-tree failed");
2474
2475        # try to figure out the next tag after this commit
2476        my $tagname;
2477        my $refs = git_get_references("tags");
2478        open $fd, "-|", $GIT, "rev-list", "HEAD";
2479        my @commits = map { chomp; $_ } <$fd>;
2480        close $fd;
2481        foreach my $commit (@commits) {
2482                if (defined $refs->{$commit}) {
2483                        $tagname = $refs->{$commit}
2484                }
2485                if ($commit eq $hash) {
2486                        last;
2487                }
2488        }
2489
2490        print $cgi->header(-type => "text/plain", -charset => 'utf-8', '-content-disposition' => "inline; filename=\"git-$hash.patch\"");
2491        my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2492        my $comment = $co{'comment'};
2493        print "From: $co{'author'}\n" .
2494              "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n".
2495              "Subject: $co{'title'}\n";
2496        if (defined $tagname) {
2497                print "X-Git-Tag: $tagname\n";
2498        }
2499        print "X-Git-Url: $my_url?p=$project;a=commitdiff;h=$hash\n" .
2500              "\n";
2501
2502        foreach my $line (@$comment) {;
2503                print "$line\n";
2504        }
2505        print "---\n\n";
2506
2507        foreach my $line (@difftree) {
2508                if ($line !~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
2509                        next;
2510                }
2511                my $from_id = $3;
2512                my $to_id = $4;
2513                my $status = $5;
2514                my $file = $6;
2515                if ($status eq "A") {
2516                        git_diff_print(undef, "/dev/null", $to_id, "b/$file", "plain");
2517                } elsif ($status eq "D") {
2518                        git_diff_print($from_id, "a/$file", undef, "/dev/null", "plain");
2519                } elsif ($status eq "M") {
2520                        git_diff_print($from_id, "a/$file",  $to_id, "b/$file", "plain");
2521                }
2522        }
2523}
2524
2525sub git_history {
2526        if (!defined $hash_base) {
2527                $hash_base = git_get_head_hash($project);
2528        }
2529        my $ftype;
2530        my %co = parse_commit($hash_base);
2531        if (!%co) {
2532                die_error(undef, "Unknown commit object");
2533        }
2534        my $refs = git_get_references();
2535        git_header_html();
2536        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base);
2537        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2538        if (!defined $hash && defined $file_name) {
2539                $hash = git_get_hash_by_path($hash_base, $file_name);
2540        }
2541        if (defined $hash) {
2542                $ftype = git_get_type($hash);
2543        }
2544        git_print_page_path($file_name, $ftype, $hash_base);
2545
2546        open my $fd, "-|",
2547                $GIT, "rev-list", "--full-history", $hash_base, "--", $file_name;
2548        git_history_body($fd, $refs, $hash_base, $ftype);
2549
2550        close $fd;
2551        git_footer_html();
2552}
2553
2554sub git_search {
2555        if (!defined $searchtext) {
2556                die_error(undef, "Text field empty");
2557        }
2558        if (!defined $hash) {
2559                $hash = git_get_head_hash($project);
2560        }
2561        my %co = parse_commit($hash);
2562        if (!%co) {
2563                die_error(undef, "Unknown commit object");
2564        }
2565        # pickaxe may take all resources of your box and run for several minutes
2566        # with every query - so decide by yourself how public you make this feature :)
2567        my $commit_search = 1;
2568        my $author_search = 0;
2569        my $committer_search = 0;
2570        my $pickaxe_search = 0;
2571        if ($searchtext =~ s/^author\\://i) {
2572                $author_search = 1;
2573        } elsif ($searchtext =~ s/^committer\\://i) {
2574                $committer_search = 1;
2575        } elsif ($searchtext =~ s/^pickaxe\\://i) {
2576                $commit_search = 0;
2577                $pickaxe_search = 1;
2578        }
2579        git_header_html();
2580        git_print_page_nav('','', $hash,$co{'tree'},$hash);
2581        git_print_header_div('commit', esc_html($co{'title'}), $hash);
2582
2583        print "<table cellspacing=\"0\">\n";
2584        my $alternate = 0;
2585        if ($commit_search) {
2586                $/ = "\0";
2587                open my $fd, "-|", $GIT, "rev-list", "--header", "--parents", $hash or next;
2588                while (my $commit_text = <$fd>) {
2589                        if (!grep m/$searchtext/i, $commit_text) {
2590                                next;
2591                        }
2592                        if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
2593                                next;
2594                        }
2595                        if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
2596                                next;
2597                        }
2598                        my @commit_lines = split "\n", $commit_text;
2599                        my %co = parse_commit(undef, \@commit_lines);
2600                        if (!%co) {
2601                                next;
2602                        }
2603                        if ($alternate) {
2604                                print "<tr class=\"dark\">\n";
2605                        } else {
2606                                print "<tr class=\"light\">\n";
2607                        }
2608                        $alternate ^= 1;
2609                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2610                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
2611                              "<td>" .
2612                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}) -class => "list"}, "<b>" . esc_html(chop_str($co{'title'}, 50)) . "</b><br/>");
2613                        my $comment = $co{'comment'};
2614                        foreach my $line (@$comment) {
2615                                if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
2616                                        my $lead = esc_html($1) || "";
2617                                        $lead = chop_str($lead, 30, 10);
2618                                        my $match = esc_html($2) || "";
2619                                        my $trail = esc_html($3) || "";
2620                                        $trail = chop_str($trail, 30, 10);
2621                                        my $text = "$lead<span class=\"match\">$match</span>$trail";
2622                                        print chop_str($text, 80, 5) . "<br/>\n";
2623                                }
2624                        }
2625                        print "</td>\n" .
2626                              "<td class=\"link\">" .
2627                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
2628                              " | " . $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
2629                        print "</td>\n" .
2630                              "</tr>\n";
2631                }
2632                close $fd;
2633        }
2634
2635        if ($pickaxe_search) {
2636                $/ = "\n";
2637                open my $fd, "-|", "$GIT rev-list $hash | $GIT diff-tree -r --stdin -S\'$searchtext\'";
2638                undef %co;
2639                my @files;
2640                while (my $line = <$fd>) {
2641                        if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
2642                                my %set;
2643                                $set{'file'} = $6;
2644                                $set{'from_id'} = $3;
2645                                $set{'to_id'} = $4;
2646                                $set{'id'} = $set{'to_id'};
2647                                if ($set{'id'} =~ m/0{40}/) {
2648                                        $set{'id'} = $set{'from_id'};
2649                                }
2650                                if ($set{'id'} =~ m/0{40}/) {
2651                                        next;
2652                                }
2653                                push @files, \%set;
2654                        } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
2655                                if (%co) {
2656                                        if ($alternate) {
2657                                                print "<tr class=\"dark\">\n";
2658                                        } else {
2659                                                print "<tr class=\"light\">\n";
2660                                        }
2661                                        $alternate ^= 1;
2662                                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2663                                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
2664                                              "<td>" .
2665                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list"}, "<b>" .
2666                                              esc_html(chop_str($co{'title'}, 50)) . "</b><br/>");
2667                                        while (my $setref = shift @files) {
2668                                                my %set = %$setref;
2669                                                print $cgi->a({-href => href(action=>"blob", hash=>$set{'id'}, hash_base=>$co{'id'}, file_name=>$set{'file'}), class => "list"},
2670                                                      "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
2671                                                      "<br/>\n";
2672                                        }
2673                                        print "</td>\n" .
2674                                              "<td class=\"link\">" .
2675                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
2676                                              " | " . $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
2677                                        print "</td>\n" .
2678                                              "</tr>\n";
2679                                }
2680                                %co = parse_commit($1);
2681                        }
2682                }
2683                close $fd;
2684        }
2685        print "</table>\n";
2686        git_footer_html();
2687}
2688
2689sub git_shortlog {
2690        my $head = git_get_head_hash($project);
2691        if (!defined $hash) {
2692                $hash = $head;
2693        }
2694        if (!defined $page) {
2695                $page = 0;
2696        }
2697        my $refs = git_get_references();
2698
2699        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2700        open my $fd, "-|", $GIT, "rev-list", $limit, $hash
2701                or die_error(undef, "Open git-rev-list failed");
2702        my @revlist = map { chomp; $_ } <$fd>;
2703        close $fd;
2704
2705        my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
2706        my $next_link = '';
2707        if ($#revlist >= (100 * ($page+1)-1)) {
2708                $next_link =
2709                        $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
2710                                 -title => "Alt-n"}, "next");
2711        }
2712
2713
2714        git_header_html();
2715        git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
2716        git_print_header_div('summary', $project);
2717
2718        git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
2719
2720        git_footer_html();
2721}
2722
2723## ......................................................................
2724## feeds (RSS, OPML)
2725
2726sub git_rss {
2727        # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
2728        open my $fd, "-|", $GIT, "rev-list", "--max-count=150", git_get_head_hash($project)
2729                or die_error(undef, "Open git-rev-list failed");
2730        my @revlist = map { chomp; $_ } <$fd>;
2731        close $fd or die_error(undef, "Reading git-rev-list failed");
2732        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
2733        print "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".
2734              "<rss version=\"2.0\" xmlns:content=\"http://purl.org/rss/1.0/modules/content/\">\n";
2735        print "<channel>\n";
2736        print "<title>$project</title>\n".
2737              "<link>" . esc_html("$my_url?p=$project;a=summary") . "</link>\n".
2738              "<description>$project log</description>\n".
2739              "<language>en</language>\n";
2740
2741        for (my $i = 0; $i <= $#revlist; $i++) {
2742                my $commit = $revlist[$i];
2743                my %co = parse_commit($commit);
2744                # we read 150, we always show 30 and the ones more recent than 48 hours
2745                if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
2746                        last;
2747                }
2748                my %cd = parse_date($co{'committer_epoch'});
2749                open $fd, "-|", $GIT, "diff-tree", '-r', $co{'parent'}, $co{'id'} or next;
2750                my @difftree = map { chomp; $_ } <$fd>;
2751                close $fd or next;
2752                print "<item>\n" .
2753                      "<title>" .
2754                      sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
2755                      "</title>\n" .
2756                      "<author>" . esc_html($co{'author'}) . "</author>\n" .
2757                      "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
2758                      "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
2759                      "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
2760                      "<description>" . esc_html($co{'title'}) . "</description>\n" .
2761                      "<content:encoded>" .
2762                      "<![CDATA[\n";
2763                my $comment = $co{'comment'};
2764                foreach my $line (@$comment) {
2765                        $line = decode("utf8", $line, Encode::FB_DEFAULT);
2766                        print "$line<br/>\n";
2767                }
2768                print "<br/>\n";
2769                foreach my $line (@difftree) {
2770                        if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
2771                                next;
2772                        }
2773                        my $file = validate_input(unquote($7));
2774                        $file = decode("utf8", $file, Encode::FB_DEFAULT);
2775                        print "$file<br/>\n";
2776                }
2777                print "]]>\n" .
2778                      "</content:encoded>\n" .
2779                      "</item>\n";
2780        }
2781        print "</channel></rss>";
2782}
2783
2784sub git_opml {
2785        my @list = git_get_projects_list();
2786
2787        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
2788        print "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".
2789              "<opml version=\"1.0\">\n".
2790              "<head>".
2791              "  <title>$site_name Git OPML Export</title>\n".
2792              "</head>\n".
2793              "<body>\n".
2794              "<outline text=\"git RSS feeds\">\n";
2795
2796        foreach my $pr (@list) {
2797                my %proj = %$pr;
2798                my $head = git_get_head_hash($proj{'path'});
2799                if (!defined $head) {
2800                        next;
2801                }
2802                $ENV{'GIT_DIR'} = "$projectroot/$proj{'path'}";
2803                my %co = parse_commit($head);
2804                if (!%co) {
2805                        next;
2806                }
2807
2808                my $path = esc_html(chop_str($proj{'path'}, 25, 5));
2809                my $rss  = "$my_url?p=$proj{'path'};a=rss";
2810                my $html = "$my_url?p=$proj{'path'};a=summary";
2811                print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
2812        }
2813        print "</outline>\n".
2814              "</body>\n".
2815              "</opml>\n";
2816}