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