1#!/usr/bin/perl 2 3# gitweb - simple web interface to track changes in git repositories 4# 5# (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org> 6# (C) 2005, Christian Gierke 7# 8# This program is licensed under the GPLv2 9 10use strict; 11use warnings; 12use CGI qw(:standard :escapeHTML -nosticky); 13use CGI::Util qw(unescape); 14use CGI::Carp qw(fatalsToBrowser); 15use Encode; 16use Fcntl ':mode'; 17use File::Find qw(); 18use File::Basename qw(basename); 19binmode STDOUT,':utf8'; 20 21our$t0; 22if(eval{require Time::HiRes;1; }) { 23$t0= [Time::HiRes::gettimeofday()]; 24} 25our$number_of_git_cmds=0; 26 27BEGIN{ 28 CGI->compile()if$ENV{'MOD_PERL'}; 29} 30 31our$version="++GIT_VERSION++"; 32 33our($my_url,$my_uri,$base_url,$path_info,$home_link); 34sub evaluate_uri { 35our$cgi; 36 37our$my_url=$cgi->url(); 38our$my_uri=$cgi->url(-absolute =>1); 39 40# Base URL for relative URLs in gitweb ($logo, $favicon, ...), 41# needed and used only for URLs with nonempty PATH_INFO 42our$base_url=$my_url; 43 44# When the script is used as DirectoryIndex, the URL does not contain the name 45# of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we 46# have to do it ourselves. We make $path_info global because it's also used 47# later on. 48# 49# Another issue with the script being the DirectoryIndex is that the resulting 50# $my_url data is not the full script URL: this is good, because we want 51# generated links to keep implying the script name if it wasn't explicitly 52# indicated in the URL we're handling, but it means that $my_url cannot be used 53# as base URL. 54# Therefore, if we needed to strip PATH_INFO, then we know that we have 55# to build the base URL ourselves: 56our$path_info=$ENV{"PATH_INFO"}; 57if($path_info) { 58if($my_url=~ s,\Q$path_info\E$,, && 59$my_uri=~ s,\Q$path_info\E$,, && 60defined$ENV{'SCRIPT_NAME'}) { 61$base_url=$cgi->url(-base =>1) .$ENV{'SCRIPT_NAME'}; 62} 63} 64 65# target of the home link on top of all pages 66our$home_link=$my_uri||"/"; 67} 68 69# core git executable to use 70# this can just be "git" if your webserver has a sensible PATH 71our$GIT="++GIT_BINDIR++/git"; 72 73# absolute fs-path which will be prepended to the project path 74#our $projectroot = "/pub/scm"; 75our$projectroot="++GITWEB_PROJECTROOT++"; 76 77# fs traversing limit for getting project list 78# the number is relative to the projectroot 79our$project_maxdepth="++GITWEB_PROJECT_MAXDEPTH++"; 80 81# string of the home link on top of all pages 82our$home_link_str="++GITWEB_HOME_LINK_STR++"; 83 84# name of your site or organization to appear in page titles 85# replace this with something more descriptive for clearer bookmarks 86our$site_name="++GITWEB_SITENAME++" 87|| ($ENV{'SERVER_NAME'} ||"Untitled") ." Git"; 88 89# filename of html text to include at top of each page 90our$site_header="++GITWEB_SITE_HEADER++"; 91# html text to include at home page 92our$home_text="++GITWEB_HOMETEXT++"; 93# filename of html text to include at bottom of each page 94our$site_footer="++GITWEB_SITE_FOOTER++"; 95 96# URI of stylesheets 97our@stylesheets= ("++GITWEB_CSS++"); 98# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG. 99our$stylesheet=undef; 100# URI of GIT logo (72x27 size) 101our$logo="++GITWEB_LOGO++"; 102# URI of GIT favicon, assumed to be image/png type 103our$favicon="++GITWEB_FAVICON++"; 104# URI of gitweb.js (JavaScript code for gitweb) 105our$javascript="++GITWEB_JS++"; 106 107# URI and label (title) of GIT logo link 108#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/"; 109#our $logo_label = "git documentation"; 110our$logo_url="http://git-scm.com/"; 111our$logo_label="git homepage"; 112 113# source of projects list 114our$projects_list="++GITWEB_LIST++"; 115 116# the width (in characters) of the projects list "Description" column 117our$projects_list_description_width=25; 118 119# default order of projects list 120# valid values are none, project, descr, owner, and age 121our$default_projects_order="project"; 122 123# show repository only if this file exists 124# (only effective if this variable evaluates to true) 125our$export_ok="++GITWEB_EXPORT_OK++"; 126 127# show repository only if this subroutine returns true 128# when given the path to the project, for example: 129# sub { return -e "$_[0]/git-daemon-export-ok"; } 130our$export_auth_hook=undef; 131 132# only allow viewing of repositories also shown on the overview page 133our$strict_export="++GITWEB_STRICT_EXPORT++"; 134 135# list of git base URLs used for URL to where fetch project from, 136# i.e. full URL is "$git_base_url/$project" 137our@git_base_url_list=grep{$_ne''} ("++GITWEB_BASE_URL++"); 138 139# default blob_plain mimetype and default charset for text/plain blob 140our$default_blob_plain_mimetype='text/plain'; 141our$default_text_plain_charset=undef; 142 143# file to use for guessing MIME types before trying /etc/mime.types 144# (relative to the current git repository) 145our$mimetypes_file=undef; 146 147# assume this charset if line contains non-UTF-8 characters; 148# it should be valid encoding (see Encoding::Supported(3pm) for list), 149# for which encoding all byte sequences are valid, for example 150# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it 151# could be even 'utf-8' for the old behavior) 152our$fallback_encoding='latin1'; 153 154# rename detection options for git-diff and git-diff-tree 155# - default is '-M', with the cost proportional to 156# (number of removed files) * (number of new files). 157# - more costly is '-C' (which implies '-M'), with the cost proportional to 158# (number of changed files + number of removed files) * (number of new files) 159# - even more costly is '-C', '--find-copies-harder' with cost 160# (number of files in the original tree) * (number of new files) 161# - one might want to include '-B' option, e.g. '-B', '-M' 162our@diff_opts= ('-M');# taken from git_commit 163 164# Disables features that would allow repository owners to inject script into 165# the gitweb domain. 166our$prevent_xss=0; 167 168# information about snapshot formats that gitweb is capable of serving 169our%known_snapshot_formats= ( 170# name => { 171# 'display' => display name, 172# 'type' => mime type, 173# 'suffix' => filename suffix, 174# 'format' => --format for git-archive, 175# 'compressor' => [compressor command and arguments] 176# (array reference, optional) 177# 'disabled' => boolean (optional)} 178# 179'tgz'=> { 180'display'=>'tar.gz', 181'type'=>'application/x-gzip', 182'suffix'=>'.tar.gz', 183'format'=>'tar', 184'compressor'=> ['gzip']}, 185 186'tbz2'=> { 187'display'=>'tar.bz2', 188'type'=>'application/x-bzip2', 189'suffix'=>'.tar.bz2', 190'format'=>'tar', 191'compressor'=> ['bzip2']}, 192 193'txz'=> { 194'display'=>'tar.xz', 195'type'=>'application/x-xz', 196'suffix'=>'.tar.xz', 197'format'=>'tar', 198'compressor'=> ['xz'], 199'disabled'=>1}, 200 201'zip'=> { 202'display'=>'zip', 203'type'=>'application/x-zip', 204'suffix'=>'.zip', 205'format'=>'zip'}, 206); 207 208# Aliases so we understand old gitweb.snapshot values in repository 209# configuration. 210our%known_snapshot_format_aliases= ( 211'gzip'=>'tgz', 212'bzip2'=>'tbz2', 213'xz'=>'txz', 214 215# backward compatibility: legacy gitweb config support 216'x-gzip'=>undef,'gz'=>undef, 217'x-bzip2'=>undef,'bz2'=>undef, 218'x-zip'=>undef,''=>undef, 219); 220 221# Pixel sizes for icons and avatars. If the default font sizes or lineheights 222# are changed, it may be appropriate to change these values too via 223# $GITWEB_CONFIG. 224our%avatar_size= ( 225'default'=>16, 226'double'=>32 227); 228 229# Used to set the maximum load that we will still respond to gitweb queries. 230# If server load exceed this value then return "503 server busy" error. 231# If gitweb cannot determined server load, it is taken to be 0. 232# Leave it undefined (or set to 'undef') to turn off load checking. 233our$maxload=300; 234 235# You define site-wide feature defaults here; override them with 236# $GITWEB_CONFIG as necessary. 237our%feature= ( 238# feature => { 239# 'sub' => feature-sub (subroutine), 240# 'override' => allow-override (boolean), 241# 'default' => [ default options...] (array reference)} 242# 243# if feature is overridable (it means that allow-override has true value), 244# then feature-sub will be called with default options as parameters; 245# return value of feature-sub indicates if to enable specified feature 246# 247# if there is no 'sub' key (no feature-sub), then feature cannot be 248# overriden 249# 250# use gitweb_get_feature(<feature>) to retrieve the <feature> value 251# (an array) or gitweb_check_feature(<feature>) to check if <feature> 252# is enabled 253 254# Enable the 'blame' blob view, showing the last commit that modified 255# each line in the file. This can be very CPU-intensive. 256 257# To enable system wide have in $GITWEB_CONFIG 258# $feature{'blame'}{'default'} = [1]; 259# To have project specific config enable override in $GITWEB_CONFIG 260# $feature{'blame'}{'override'} = 1; 261# and in project config gitweb.blame = 0|1; 262'blame'=> { 263'sub'=>sub{ feature_bool('blame',@_) }, 264'override'=>0, 265'default'=> [0]}, 266 267# Enable the 'snapshot' link, providing a compressed archive of any 268# tree. This can potentially generate high traffic if you have large 269# project. 270 271# Value is a list of formats defined in %known_snapshot_formats that 272# you wish to offer. 273# To disable system wide have in $GITWEB_CONFIG 274# $feature{'snapshot'}{'default'} = []; 275# To have project specific config enable override in $GITWEB_CONFIG 276# $feature{'snapshot'}{'override'} = 1; 277# and in project config, a comma-separated list of formats or "none" 278# to disable. Example: gitweb.snapshot = tbz2,zip; 279'snapshot'=> { 280'sub'=> \&feature_snapshot, 281'override'=>0, 282'default'=> ['tgz']}, 283 284# Enable text search, which will list the commits which match author, 285# committer or commit text to a given string. Enabled by default. 286# Project specific override is not supported. 287'search'=> { 288'override'=>0, 289'default'=> [1]}, 290 291# Enable grep search, which will list the files in currently selected 292# tree containing the given string. Enabled by default. This can be 293# potentially CPU-intensive, of course. 294 295# To enable system wide have in $GITWEB_CONFIG 296# $feature{'grep'}{'default'} = [1]; 297# To have project specific config enable override in $GITWEB_CONFIG 298# $feature{'grep'}{'override'} = 1; 299# and in project config gitweb.grep = 0|1; 300'grep'=> { 301'sub'=>sub{ feature_bool('grep',@_) }, 302'override'=>0, 303'default'=> [1]}, 304 305# Enable the pickaxe search, which will list the commits that modified 306# a given string in a file. This can be practical and quite faster 307# alternative to 'blame', but still potentially CPU-intensive. 308 309# To enable system wide have in $GITWEB_CONFIG 310# $feature{'pickaxe'}{'default'} = [1]; 311# To have project specific config enable override in $GITWEB_CONFIG 312# $feature{'pickaxe'}{'override'} = 1; 313# and in project config gitweb.pickaxe = 0|1; 314'pickaxe'=> { 315'sub'=>sub{ feature_bool('pickaxe',@_) }, 316'override'=>0, 317'default'=> [1]}, 318 319# Enable showing size of blobs in a 'tree' view, in a separate 320# column, similar to what 'ls -l' does. This cost a bit of IO. 321 322# To disable system wide have in $GITWEB_CONFIG 323# $feature{'show-sizes'}{'default'} = [0]; 324# To have project specific config enable override in $GITWEB_CONFIG 325# $feature{'show-sizes'}{'override'} = 1; 326# and in project config gitweb.showsizes = 0|1; 327'show-sizes'=> { 328'sub'=>sub{ feature_bool('showsizes',@_) }, 329'override'=>0, 330'default'=> [1]}, 331 332# Make gitweb use an alternative format of the URLs which can be 333# more readable and natural-looking: project name is embedded 334# directly in the path and the query string contains other 335# auxiliary information. All gitweb installations recognize 336# URL in either format; this configures in which formats gitweb 337# generates links. 338 339# To enable system wide have in $GITWEB_CONFIG 340# $feature{'pathinfo'}{'default'} = [1]; 341# Project specific override is not supported. 342 343# Note that you will need to change the default location of CSS, 344# favicon, logo and possibly other files to an absolute URL. Also, 345# if gitweb.cgi serves as your indexfile, you will need to force 346# $my_uri to contain the script name in your $GITWEB_CONFIG. 347'pathinfo'=> { 348'override'=>0, 349'default'=> [0]}, 350 351# Make gitweb consider projects in project root subdirectories 352# to be forks of existing projects. Given project $projname.git, 353# projects matching $projname/*.git will not be shown in the main 354# projects list, instead a '+' mark will be added to $projname 355# there and a 'forks' view will be enabled for the project, listing 356# all the forks. If project list is taken from a file, forks have 357# to be listed after the main project. 358 359# To enable system wide have in $GITWEB_CONFIG 360# $feature{'forks'}{'default'} = [1]; 361# Project specific override is not supported. 362'forks'=> { 363'override'=>0, 364'default'=> [0]}, 365 366# Insert custom links to the action bar of all project pages. 367# This enables you mainly to link to third-party scripts integrating 368# into gitweb; e.g. git-browser for graphical history representation 369# or custom web-based repository administration interface. 370 371# The 'default' value consists of a list of triplets in the form 372# (label, link, position) where position is the label after which 373# to insert the link and link is a format string where %n expands 374# to the project name, %f to the project path within the filesystem, 375# %h to the current hash (h gitweb parameter) and %b to the current 376# hash base (hb gitweb parameter); %% expands to %. 377 378# To enable system wide have in $GITWEB_CONFIG e.g. 379# $feature{'actions'}{'default'} = [('graphiclog', 380# '/git-browser/by-commit.html?r=%n', 'summary')]; 381# Project specific override is not supported. 382'actions'=> { 383'override'=>0, 384'default'=> []}, 385 386# Allow gitweb scan project content tags described in ctags/ 387# of project repository, and display the popular Web 2.0-ish 388# "tag cloud" near the project list. Note that this is something 389# COMPLETELY different from the normal Git tags. 390 391# gitweb by itself can show existing tags, but it does not handle 392# tagging itself; you need an external application for that. 393# For an example script, check Girocco's cgi/tagproj.cgi. 394# You may want to install the HTML::TagCloud Perl module to get 395# a pretty tag cloud instead of just a list of tags. 396 397# To enable system wide have in $GITWEB_CONFIG 398# $feature{'ctags'}{'default'} = ['path_to_tag_script']; 399# Project specific override is not supported. 400'ctags'=> { 401'override'=>0, 402'default'=> [0]}, 403 404# The maximum number of patches in a patchset generated in patch 405# view. Set this to 0 or undef to disable patch view, or to a 406# negative number to remove any limit. 407 408# To disable system wide have in $GITWEB_CONFIG 409# $feature{'patches'}{'default'} = [0]; 410# To have project specific config enable override in $GITWEB_CONFIG 411# $feature{'patches'}{'override'} = 1; 412# and in project config gitweb.patches = 0|n; 413# where n is the maximum number of patches allowed in a patchset. 414'patches'=> { 415'sub'=> \&feature_patches, 416'override'=>0, 417'default'=> [16]}, 418 419# Avatar support. When this feature is enabled, views such as 420# shortlog or commit will display an avatar associated with 421# the email of the committer(s) and/or author(s). 422 423# Currently available providers are gravatar and picon. 424# If an unknown provider is specified, the feature is disabled. 425 426# Gravatar depends on Digest::MD5. 427# Picon currently relies on the indiana.edu database. 428 429# To enable system wide have in $GITWEB_CONFIG 430# $feature{'avatar'}{'default'} = ['<provider>']; 431# where <provider> is either gravatar or picon. 432# To have project specific config enable override in $GITWEB_CONFIG 433# $feature{'avatar'}{'override'} = 1; 434# and in project config gitweb.avatar = <provider>; 435'avatar'=> { 436'sub'=> \&feature_avatar, 437'override'=>0, 438'default'=> ['']}, 439 440# Enable displaying how much time and how many git commands 441# it took to generate and display page. Disabled by default. 442# Project specific override is not supported. 443'timed'=> { 444'override'=>0, 445'default'=> [0]}, 446 447# Enable turning some links into links to actions which require 448# JavaScript to run (like 'blame_incremental'). Not enabled by 449# default. Project specific override is currently not supported. 450'javascript-actions'=> { 451'override'=>0, 452'default'=> [0]}, 453); 454 455sub gitweb_get_feature { 456my($name) =@_; 457return unlessexists$feature{$name}; 458my($sub,$override,@defaults) = ( 459$feature{$name}{'sub'}, 460$feature{$name}{'override'}, 461@{$feature{$name}{'default'}}); 462# project specific override is possible only if we have project 463our$git_dir;# global variable, declared later 464if(!$override|| !defined$git_dir) { 465return@defaults; 466} 467if(!defined$sub) { 468warn"feature$nameis not overridable"; 469return@defaults; 470} 471return$sub->(@defaults); 472} 473 474# A wrapper to check if a given feature is enabled. 475# With this, you can say 476# 477# my $bool_feat = gitweb_check_feature('bool_feat'); 478# gitweb_check_feature('bool_feat') or somecode; 479# 480# instead of 481# 482# my ($bool_feat) = gitweb_get_feature('bool_feat'); 483# (gitweb_get_feature('bool_feat'))[0] or somecode; 484# 485sub gitweb_check_feature { 486return(gitweb_get_feature(@_))[0]; 487} 488 489 490sub feature_bool { 491my$key=shift; 492my($val) = git_get_project_config($key,'--bool'); 493 494if(!defined$val) { 495return($_[0]); 496}elsif($valeq'true') { 497return(1); 498}elsif($valeq'false') { 499return(0); 500} 501} 502 503sub feature_snapshot { 504my(@fmts) =@_; 505 506my($val) = git_get_project_config('snapshot'); 507 508if($val) { 509@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 510} 511 512return@fmts; 513} 514 515sub feature_patches { 516my@val= (git_get_project_config('patches','--int')); 517 518if(@val) { 519return@val; 520} 521 522return($_[0]); 523} 524 525sub feature_avatar { 526my@val= (git_get_project_config('avatar')); 527 528return@val?@val:@_; 529} 530 531# checking HEAD file with -e is fragile if the repository was 532# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 533# and then pruned. 534sub check_head_link { 535my($dir) =@_; 536my$headfile="$dir/HEAD"; 537return((-e $headfile) || 538(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 539} 540 541sub check_export_ok { 542my($dir) =@_; 543return(check_head_link($dir) && 544(!$export_ok|| -e "$dir/$export_ok") && 545(!$export_auth_hook||$export_auth_hook->($dir))); 546} 547 548# process alternate names for backward compatibility 549# filter out unsupported (unknown) snapshot formats 550sub filter_snapshot_fmts { 551my@fmts=@_; 552 553@fmts=map{ 554exists$known_snapshot_format_aliases{$_} ? 555$known_snapshot_format_aliases{$_} :$_}@fmts; 556@fmts=grep{ 557exists$known_snapshot_formats{$_} && 558!$known_snapshot_formats{$_}{'disabled'}}@fmts; 559} 560 561our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM); 562sub evaluate_gitweb_config { 563our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 564our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 565# die if there are errors parsing config file 566if(-e $GITWEB_CONFIG) { 567do$GITWEB_CONFIG; 568die$@if$@; 569}elsif(-e $GITWEB_CONFIG_SYSTEM) { 570do$GITWEB_CONFIG_SYSTEM; 571die$@if$@; 572} 573} 574 575# Get loadavg of system, to compare against $maxload. 576# Currently it requires '/proc/loadavg' present to get loadavg; 577# if it is not present it returns 0, which means no load checking. 578sub get_loadavg { 579if( -e '/proc/loadavg'){ 580open my$fd,'<','/proc/loadavg' 581orreturn0; 582my@load=split(/\s+/,scalar<$fd>); 583close$fd; 584 585# The first three columns measure CPU and IO utilization of the last one, 586# five, and 10 minute periods. The fourth column shows the number of 587# currently running processes and the total number of processes in the m/n 588# format. The last column displays the last process ID used. 589return$load[0] ||0; 590} 591# additional checks for load average should go here for things that don't export 592# /proc/loadavg 593 594return0; 595} 596 597# version of the core git binary 598our$git_version; 599sub evaluate_git_version { 600our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 601$number_of_git_cmds++; 602} 603 604sub check_loadavg { 605if(defined$maxload&& get_loadavg() >$maxload) { 606 die_error(503,"The load average on the server is too high"); 607} 608} 609 610# ====================================================================== 611# input validation and dispatch 612 613# input parameters can be collected from a variety of sources (presently, CGI 614# and PATH_INFO), so we define an %input_params hash that collects them all 615# together during validation: this allows subsequent uses (e.g. href()) to be 616# agnostic of the parameter origin 617 618our%input_params= (); 619 620# input parameters are stored with the long parameter name as key. This will 621# also be used in the href subroutine to convert parameters to their CGI 622# equivalent, and since the href() usage is the most frequent one, we store 623# the name -> CGI key mapping here, instead of the reverse. 624# 625# XXX: Warning: If you touch this, check the search form for updating, 626# too. 627 628our@cgi_param_mapping= ( 629 project =>"p", 630 action =>"a", 631 file_name =>"f", 632 file_parent =>"fp", 633 hash =>"h", 634 hash_parent =>"hp", 635 hash_base =>"hb", 636 hash_parent_base =>"hpb", 637 page =>"pg", 638 order =>"o", 639 searchtext =>"s", 640 searchtype =>"st", 641 snapshot_format =>"sf", 642 extra_options =>"opt", 643 search_use_regexp =>"sr", 644# this must be last entry (for manipulation from JavaScript) 645 javascript =>"js" 646); 647our%cgi_param_mapping=@cgi_param_mapping; 648 649# we will also need to know the possible actions, for validation 650our%actions= ( 651"blame"=> \&git_blame, 652"blame_incremental"=> \&git_blame_incremental, 653"blame_data"=> \&git_blame_data, 654"blobdiff"=> \&git_blobdiff, 655"blobdiff_plain"=> \&git_blobdiff_plain, 656"blob"=> \&git_blob, 657"blob_plain"=> \&git_blob_plain, 658"commitdiff"=> \&git_commitdiff, 659"commitdiff_plain"=> \&git_commitdiff_plain, 660"commit"=> \&git_commit, 661"forks"=> \&git_forks, 662"heads"=> \&git_heads, 663"history"=> \&git_history, 664"log"=> \&git_log, 665"patch"=> \&git_patch, 666"patches"=> \&git_patches, 667"rss"=> \&git_rss, 668"atom"=> \&git_atom, 669"search"=> \&git_search, 670"search_help"=> \&git_search_help, 671"shortlog"=> \&git_shortlog, 672"summary"=> \&git_summary, 673"tag"=> \&git_tag, 674"tags"=> \&git_tags, 675"tree"=> \&git_tree, 676"snapshot"=> \&git_snapshot, 677"object"=> \&git_object, 678# those below don't need $project 679"opml"=> \&git_opml, 680"project_list"=> \&git_project_list, 681"project_index"=> \&git_project_index, 682); 683 684# finally, we have the hash of allowed extra_options for the commands that 685# allow them 686our%allowed_options= ( 687"--no-merges"=> [qw(rss atom log shortlog history)], 688); 689 690# fill %input_params with the CGI parameters. All values except for 'opt' 691# should be single values, but opt can be an array. We should probably 692# build an array of parameters that can be multi-valued, but since for the time 693# being it's only this one, we just single it out 694sub evaluate_query_params { 695our$cgi; 696 697while(my($name,$symbol) =each%cgi_param_mapping) { 698if($symboleq'opt') { 699$input_params{$name} = [$cgi->param($symbol) ]; 700}else{ 701$input_params{$name} =$cgi->param($symbol); 702} 703} 704} 705 706# now read PATH_INFO and update the parameter list for missing parameters 707sub evaluate_path_info { 708return ifdefined$input_params{'project'}; 709return if!$path_info; 710$path_info=~ s,^/+,,; 711return if!$path_info; 712 713# find which part of PATH_INFO is project 714my$project=$path_info; 715$project=~ s,/+$,,; 716while($project&& !check_head_link("$projectroot/$project")) { 717$project=~ s,/*[^/]*$,,; 718} 719return unless$project; 720$input_params{'project'} =$project; 721 722# do not change any parameters if an action is given using the query string 723return if$input_params{'action'}; 724$path_info=~ s,^\Q$project\E/*,,; 725 726# next, check if we have an action 727my$action=$path_info; 728$action=~ s,/.*$,,; 729if(exists$actions{$action}) { 730$path_info=~ s,^$action/*,,; 731$input_params{'action'} =$action; 732} 733 734# list of actions that want hash_base instead of hash, but can have no 735# pathname (f) parameter 736my@wants_base= ( 737'tree', 738'history', 739); 740 741# we want to catch 742# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 743my($parentrefname,$parentpathname,$refname,$pathname) = 744($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/); 745 746# first, analyze the 'current' part 747if(defined$pathname) { 748# we got "branch:filename" or "branch:dir/" 749# we could use git_get_type(branch:pathname), but: 750# - it needs $git_dir 751# - it does a git() call 752# - the convention of terminating directories with a slash 753# makes it superfluous 754# - embedding the action in the PATH_INFO would make it even 755# more superfluous 756$pathname=~ s,^/+,,; 757if(!$pathname||substr($pathname, -1)eq"/") { 758$input_params{'action'} ||="tree"; 759$pathname=~ s,/$,,; 760}else{ 761# the default action depends on whether we had parent info 762# or not 763if($parentrefname) { 764$input_params{'action'} ||="blobdiff_plain"; 765}else{ 766$input_params{'action'} ||="blob_plain"; 767} 768} 769$input_params{'hash_base'} ||=$refname; 770$input_params{'file_name'} ||=$pathname; 771}elsif(defined$refname) { 772# we got "branch". In this case we have to choose if we have to 773# set hash or hash_base. 774# 775# Most of the actions without a pathname only want hash to be 776# set, except for the ones specified in @wants_base that want 777# hash_base instead. It should also be noted that hand-crafted 778# links having 'history' as an action and no pathname or hash 779# set will fail, but that happens regardless of PATH_INFO. 780$input_params{'action'} ||="shortlog"; 781if(grep{$_eq$input_params{'action'} }@wants_base) { 782$input_params{'hash_base'} ||=$refname; 783}else{ 784$input_params{'hash'} ||=$refname; 785} 786} 787 788# next, handle the 'parent' part, if present 789if(defined$parentrefname) { 790# a missing pathspec defaults to the 'current' filename, allowing e.g. 791# someproject/blobdiff/oldrev..newrev:/filename 792if($parentpathname) { 793$parentpathname=~ s,^/+,,; 794$parentpathname=~ s,/$,,; 795$input_params{'file_parent'} ||=$parentpathname; 796}else{ 797$input_params{'file_parent'} ||=$input_params{'file_name'}; 798} 799# we assume that hash_parent_base is wanted if a path was specified, 800# or if the action wants hash_base instead of hash 801if(defined$input_params{'file_parent'} || 802grep{$_eq$input_params{'action'} }@wants_base) { 803$input_params{'hash_parent_base'} ||=$parentrefname; 804}else{ 805$input_params{'hash_parent'} ||=$parentrefname; 806} 807} 808 809# for the snapshot action, we allow URLs in the form 810# $project/snapshot/$hash.ext 811# where .ext determines the snapshot and gets removed from the 812# passed $refname to provide the $hash. 813# 814# To be able to tell that $refname includes the format extension, we 815# require the following two conditions to be satisfied: 816# - the hash input parameter MUST have been set from the $refname part 817# of the URL (i.e. they must be equal) 818# - the snapshot format MUST NOT have been defined already (e.g. from 819# CGI parameter sf) 820# It's also useless to try any matching unless $refname has a dot, 821# so we check for that too 822if(defined$input_params{'action'} && 823$input_params{'action'}eq'snapshot'&& 824defined$refname&&index($refname,'.') != -1&& 825$refnameeq$input_params{'hash'} && 826!defined$input_params{'snapshot_format'}) { 827# We loop over the known snapshot formats, checking for 828# extensions. Allowed extensions are both the defined suffix 829# (which includes the initial dot already) and the snapshot 830# format key itself, with a prepended dot 831while(my($fmt,$opt) =each%known_snapshot_formats) { 832my$hash=$refname; 833unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 834next; 835} 836my$sfx=$1; 837# a valid suffix was found, so set the snapshot format 838# and reset the hash parameter 839$input_params{'snapshot_format'} =$fmt; 840$input_params{'hash'} =$hash; 841# we also set the format suffix to the one requested 842# in the URL: this way a request for e.g. .tgz returns 843# a .tgz instead of a .tar.gz 844$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 845last; 846} 847} 848} 849 850our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 851$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 852$searchtext,$search_regexp); 853sub evaluate_and_validate_params { 854our$action=$input_params{'action'}; 855if(defined$action) { 856if(!validate_action($action)) { 857 die_error(400,"Invalid action parameter"); 858} 859} 860 861# parameters which are pathnames 862our$project=$input_params{'project'}; 863if(defined$project) { 864if(!validate_project($project)) { 865undef$project; 866 die_error(404,"No such project"); 867} 868} 869 870our$file_name=$input_params{'file_name'}; 871if(defined$file_name) { 872if(!validate_pathname($file_name)) { 873 die_error(400,"Invalid file parameter"); 874} 875} 876 877our$file_parent=$input_params{'file_parent'}; 878if(defined$file_parent) { 879if(!validate_pathname($file_parent)) { 880 die_error(400,"Invalid file parent parameter"); 881} 882} 883 884# parameters which are refnames 885our$hash=$input_params{'hash'}; 886if(defined$hash) { 887if(!validate_refname($hash)) { 888 die_error(400,"Invalid hash parameter"); 889} 890} 891 892our$hash_parent=$input_params{'hash_parent'}; 893if(defined$hash_parent) { 894if(!validate_refname($hash_parent)) { 895 die_error(400,"Invalid hash parent parameter"); 896} 897} 898 899our$hash_base=$input_params{'hash_base'}; 900if(defined$hash_base) { 901if(!validate_refname($hash_base)) { 902 die_error(400,"Invalid hash base parameter"); 903} 904} 905 906our@extra_options= @{$input_params{'extra_options'}}; 907# @extra_options is always defined, since it can only be (currently) set from 908# CGI, and $cgi->param() returns the empty array in array context if the param 909# is not set 910foreachmy$opt(@extra_options) { 911if(not exists$allowed_options{$opt}) { 912 die_error(400,"Invalid option parameter"); 913} 914if(not grep(/^$action$/, @{$allowed_options{$opt}})) { 915 die_error(400,"Invalid option parameter for this action"); 916} 917} 918 919our$hash_parent_base=$input_params{'hash_parent_base'}; 920if(defined$hash_parent_base) { 921if(!validate_refname($hash_parent_base)) { 922 die_error(400,"Invalid hash parent base parameter"); 923} 924} 925 926# other parameters 927our$page=$input_params{'page'}; 928if(defined$page) { 929if($page=~m/[^0-9]/) { 930 die_error(400,"Invalid page parameter"); 931} 932} 933 934our$searchtype=$input_params{'searchtype'}; 935if(defined$searchtype) { 936if($searchtype=~m/[^a-z]/) { 937 die_error(400,"Invalid searchtype parameter"); 938} 939} 940 941our$search_use_regexp=$input_params{'search_use_regexp'}; 942 943our$searchtext=$input_params{'searchtext'}; 944our$search_regexp; 945if(defined$searchtext) { 946if(length($searchtext) <2) { 947 die_error(403,"At least two characters are required for search parameter"); 948} 949$search_regexp=$search_use_regexp?$searchtext:quotemeta$searchtext; 950} 951} 952 953# path to the current git repository 954our$git_dir; 955sub evaluate_git_dir { 956our$git_dir="$projectroot/$project"if$project; 957} 958 959our(@snapshot_fmts,$git_avatar); 960sub configure_gitweb_features { 961# list of supported snapshot formats 962our@snapshot_fmts= gitweb_get_feature('snapshot'); 963@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts); 964 965# check that the avatar feature is set to a known provider name, 966# and for each provider check if the dependencies are satisfied. 967# if the provider name is invalid or the dependencies are not met, 968# reset $git_avatar to the empty string. 969our($git_avatar) = gitweb_get_feature('avatar'); 970if($git_avatareq'gravatar') { 971$git_avatar=''unless(eval{require Digest::MD5;1; }); 972}elsif($git_avatareq'picon') { 973# no dependencies 974}else{ 975$git_avatar=''; 976} 977} 978 979# dispatch 980sub dispatch { 981if(!defined$action) { 982if(defined$hash) { 983$action= git_get_type($hash); 984}elsif(defined$hash_base&&defined$file_name) { 985$action= git_get_type("$hash_base:$file_name"); 986}elsif(defined$project) { 987$action='summary'; 988}else{ 989$action='project_list'; 990} 991} 992if(!defined($actions{$action})) { 993 die_error(400,"Unknown action"); 994} 995if($action!~m/^(?:opml|project_list|project_index)$/&& 996!$project) { 997 die_error(400,"Project needed"); 998} 999$actions{$action}->();1000}10011002sub run {1003our$t0= [Time::HiRes::gettimeofday()]1004ifdefined$t0;10051006 evaluate_uri();1007 evaluate_gitweb_config();1008 evaluate_git_version();1009 check_loadavg();10101011# $projectroot and $projects_list might be set in gitweb config file1012$projects_list||=$projectroot;10131014 evaluate_query_params();1015 evaluate_path_info();1016 evaluate_and_validate_params();1017 evaluate_git_dir();10181019 configure_gitweb_features();10201021 dispatch();10221023 DONE_GITWEB:10241;1025}1026our$cgi= CGI->new();1027run();10281029## ======================================================================1030## action links10311032# possible values of extra options1033# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1034# -replay => 1 - start from a current view (replay with modifications)1035# -path_info => 0|1 - don't use/use path_info URL (if possible)1036sub href {1037my%params=@_;1038# default is to use -absolute url() i.e. $my_uri1039my$href=$params{-full} ?$my_url:$my_uri;10401041$params{'project'} =$projectunlessexists$params{'project'};10421043if($params{-replay}) {1044while(my($name,$symbol) =each%cgi_param_mapping) {1045if(!exists$params{$name}) {1046$params{$name} =$input_params{$name};1047}1048}1049}10501051my$use_pathinfo= gitweb_check_feature('pathinfo');1052if(defined$params{'project'} &&1053(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1054# try to put as many parameters as possible in PATH_INFO:1055# - project name1056# - action1057# - hash_parent or hash_parent_base:/file_parent1058# - hash or hash_base:/filename1059# - the snapshot_format as an appropriate suffix10601061# When the script is the root DirectoryIndex for the domain,1062# $href here would be something like http://gitweb.example.com/1063# Thus, we strip any trailing / from $href, to spare us double1064# slashes in the final URL1065$href=~ s,/$,,;10661067# Then add the project name, if present1068$href.="/".esc_url($params{'project'});1069delete$params{'project'};10701071# since we destructively absorb parameters, we keep this1072# boolean that remembers if we're handling a snapshot1073my$is_snapshot=$params{'action'}eq'snapshot';10741075# Summary just uses the project path URL, any other action is1076# added to the URL1077if(defined$params{'action'}) {1078$href.="/".esc_url($params{'action'})unless$params{'action'}eq'summary';1079delete$params{'action'};1080}10811082# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1083# stripping nonexistent or useless pieces1084$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1085||$params{'hash_parent'} ||$params{'hash'});1086if(defined$params{'hash_base'}) {1087if(defined$params{'hash_parent_base'}) {1088$href.= esc_url($params{'hash_parent_base'});1089# skip the file_parent if it's the same as the file_name1090if(defined$params{'file_parent'}) {1091if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1092delete$params{'file_parent'};1093}elsif($params{'file_parent'} !~/\.\./) {1094$href.=":/".esc_url($params{'file_parent'});1095delete$params{'file_parent'};1096}1097}1098$href.="..";1099delete$params{'hash_parent'};1100delete$params{'hash_parent_base'};1101}elsif(defined$params{'hash_parent'}) {1102$href.= esc_url($params{'hash_parent'})."..";1103delete$params{'hash_parent'};1104}11051106$href.= esc_url($params{'hash_base'});1107if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1108$href.=":/".esc_url($params{'file_name'});1109delete$params{'file_name'};1110}1111delete$params{'hash'};1112delete$params{'hash_base'};1113}elsif(defined$params{'hash'}) {1114$href.= esc_url($params{'hash'});1115delete$params{'hash'};1116}11171118# If the action was a snapshot, we can absorb the1119# snapshot_format parameter too1120if($is_snapshot) {1121my$fmt=$params{'snapshot_format'};1122# snapshot_format should always be defined when href()1123# is called, but just in case some code forgets, we1124# fall back to the default1125$fmt||=$snapshot_fmts[0];1126$href.=$known_snapshot_formats{$fmt}{'suffix'};1127delete$params{'snapshot_format'};1128}1129}11301131# now encode the parameters explicitly1132my@result= ();1133for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1134my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1135if(defined$params{$name}) {1136if(ref($params{$name})eq"ARRAY") {1137foreachmy$par(@{$params{$name}}) {1138push@result,$symbol."=". esc_param($par);1139}1140}else{1141push@result,$symbol."=". esc_param($params{$name});1142}1143}1144}1145$href.="?".join(';',@result)ifscalar@result;11461147return$href;1148}114911501151## ======================================================================1152## validation, quoting/unquoting and escaping11531154sub validate_action {1155my$input=shift||returnundef;1156returnundefunlessexists$actions{$input};1157return$input;1158}11591160sub validate_project {1161my$input=shift||returnundef;1162if(!validate_pathname($input) ||1163!(-d "$projectroot/$input") ||1164!check_export_ok("$projectroot/$input") ||1165($strict_export&& !project_in_list($input))) {1166returnundef;1167}else{1168return$input;1169}1170}11711172sub validate_pathname {1173my$input=shift||returnundef;11741175# no '.' or '..' as elements of path, i.e. no '.' nor '..'1176# at the beginning, at the end, and between slashes.1177# also this catches doubled slashes1178if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1179returnundef;1180}1181# no null characters1182if($input=~m!\0!) {1183returnundef;1184}1185return$input;1186}11871188sub validate_refname {1189my$input=shift||returnundef;11901191# textual hashes are O.K.1192if($input=~m/^[0-9a-fA-F]{40}$/) {1193return$input;1194}1195# it must be correct pathname1196$input= validate_pathname($input)1197orreturnundef;1198# restrictions on ref name according to git-check-ref-format1199if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1200returnundef;1201}1202return$input;1203}12041205# decode sequences of octets in utf8 into Perl's internal form,1206# which is utf-8 with utf8 flag set if needed. gitweb writes out1207# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1208sub to_utf8 {1209my$str=shift;1210returnundefunlessdefined$str;1211if(utf8::valid($str)) {1212 utf8::decode($str);1213return$str;1214}else{1215return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1216}1217}12181219# quote unsafe chars, but keep the slash, even when it's not1220# correct, but quoted slashes look too horrible in bookmarks1221sub esc_param {1222my$str=shift;1223returnundefunlessdefined$str;1224$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1225$str=~s/ /\+/g;1226return$str;1227}12281229# quote unsafe chars in whole URL, so some charactrs cannot be quoted1230sub esc_url {1231my$str=shift;1232returnundefunlessdefined$str;1233$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X",ord($1))/eg;1234$str=~s/\+/%2B/g;1235$str=~s/ /\+/g;1236return$str;1237}12381239# replace invalid utf8 character with SUBSTITUTION sequence1240sub esc_html {1241my$str=shift;1242my%opts=@_;12431244returnundefunlessdefined$str;12451246$str= to_utf8($str);1247$str=$cgi->escapeHTML($str);1248if($opts{'-nbsp'}) {1249$str=~s/ / /g;1250}1251$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1252return$str;1253}12541255# quote control characters and escape filename to HTML1256sub esc_path {1257my$str=shift;1258my%opts=@_;12591260returnundefunlessdefined$str;12611262$str= to_utf8($str);1263$str=$cgi->escapeHTML($str);1264if($opts{'-nbsp'}) {1265$str=~s/ / /g;1266}1267$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1268return$str;1269}12701271# Make control characters "printable", using character escape codes (CEC)1272sub quot_cec {1273my$cntrl=shift;1274my%opts=@_;1275my%es= (# character escape codes, aka escape sequences1276"\t"=>'\t',# tab (HT)1277"\n"=>'\n',# line feed (LF)1278"\r"=>'\r',# carrige return (CR)1279"\f"=>'\f',# form feed (FF)1280"\b"=>'\b',# backspace (BS)1281"\a"=>'\a',# alarm (bell) (BEL)1282"\e"=>'\e',# escape (ESC)1283"\013"=>'\v',# vertical tab (VT)1284"\000"=>'\0',# nul character (NUL)1285);1286my$chr= ( (exists$es{$cntrl})1287?$es{$cntrl}1288:sprintf('\%2x',ord($cntrl)) );1289if($opts{-nohtml}) {1290return$chr;1291}else{1292return"<span class=\"cntrl\">$chr</span>";1293}1294}12951296# Alternatively use unicode control pictures codepoints,1297# Unicode "printable representation" (PR)1298sub quot_upr {1299my$cntrl=shift;1300my%opts=@_;13011302my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1303if($opts{-nohtml}) {1304return$chr;1305}else{1306return"<span class=\"cntrl\">$chr</span>";1307}1308}13091310# git may return quoted and escaped filenames1311sub unquote {1312my$str=shift;13131314sub unq {1315my$seq=shift;1316my%es= (# character escape codes, aka escape sequences1317't'=>"\t",# tab (HT, TAB)1318'n'=>"\n",# newline (NL)1319'r'=>"\r",# return (CR)1320'f'=>"\f",# form feed (FF)1321'b'=>"\b",# backspace (BS)1322'a'=>"\a",# alarm (bell) (BEL)1323'e'=>"\e",# escape (ESC)1324'v'=>"\013",# vertical tab (VT)1325);13261327if($seq=~m/^[0-7]{1,3}$/) {1328# octal char sequence1329returnchr(oct($seq));1330}elsif(exists$es{$seq}) {1331# C escape sequence, aka character escape code1332return$es{$seq};1333}1334# quoted ordinary character1335return$seq;1336}13371338if($str=~m/^"(.*)"$/) {1339# needs unquoting1340$str=$1;1341$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1342}1343return$str;1344}13451346# escape tabs (convert tabs to spaces)1347sub untabify {1348my$line=shift;13491350while((my$pos=index($line,"\t")) != -1) {1351if(my$count= (8- ($pos%8))) {1352my$spaces=' ' x $count;1353$line=~s/\t/$spaces/;1354}1355}13561357return$line;1358}13591360sub project_in_list {1361my$project=shift;1362my@list= git_get_projects_list();1363return@list&&scalar(grep{$_->{'path'}eq$project}@list);1364}13651366## ----------------------------------------------------------------------1367## HTML aware string manipulation13681369# Try to chop given string on a word boundary between position1370# $len and $len+$add_len. If there is no word boundary there,1371# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1372# (marking chopped part) would be longer than given string.1373sub chop_str {1374my$str=shift;1375my$len=shift;1376my$add_len=shift||10;1377my$where=shift||'right';# 'left' | 'center' | 'right'13781379# Make sure perl knows it is utf8 encoded so we don't1380# cut in the middle of a utf8 multibyte char.1381$str= to_utf8($str);13821383# allow only $len chars, but don't cut a word if it would fit in $add_len1384# if it doesn't fit, cut it if it's still longer than the dots we would add1385# remove chopped character entities entirely13861387# when chopping in the middle, distribute $len into left and right part1388# return early if chopping wouldn't make string shorter1389if($whereeq'center') {1390return$strif($len+5>=length($str));# filler is length 51391$len=int($len/2);1392}else{1393return$strif($len+4>=length($str));# filler is length 41394}13951396# regexps: ending and beginning with word part up to $add_len1397my$endre=qr/.{$len}\w{0,$add_len}/;1398my$begre=qr/\w{0,$add_len}.{$len}/;13991400if($whereeq'left') {1401$str=~m/^(.*?)($begre)$/;1402my($lead,$body) = ($1,$2);1403if(length($lead) >4) {1404$lead=" ...";1405}1406return"$lead$body";14071408}elsif($whereeq'center') {1409$str=~m/^($endre)(.*)$/;1410my($left,$str) = ($1,$2);1411$str=~m/^(.*?)($begre)$/;1412my($mid,$right) = ($1,$2);1413if(length($mid) >5) {1414$mid=" ... ";1415}1416return"$left$mid$right";14171418}else{1419$str=~m/^($endre)(.*)$/;1420my$body=$1;1421my$tail=$2;1422if(length($tail) >4) {1423$tail="... ";1424}1425return"$body$tail";1426}1427}14281429# takes the same arguments as chop_str, but also wraps a <span> around the1430# result with a title attribute if it does get chopped. Additionally, the1431# string is HTML-escaped.1432sub chop_and_escape_str {1433my($str) =@_;14341435my$chopped= chop_str(@_);1436if($choppedeq$str) {1437return esc_html($chopped);1438}else{1439$str=~s/[[:cntrl:]]/?/g;1440return$cgi->span({-title=>$str}, esc_html($chopped));1441}1442}14431444## ----------------------------------------------------------------------1445## functions returning short strings14461447# CSS class for given age value (in seconds)1448sub age_class {1449my$age=shift;14501451if(!defined$age) {1452return"noage";1453}elsif($age<60*60*2) {1454return"age0";1455}elsif($age<60*60*24*2) {1456return"age1";1457}else{1458return"age2";1459}1460}14611462# convert age in seconds to "nn units ago" string1463sub age_string {1464my$age=shift;1465my$age_str;14661467if($age>60*60*24*365*2) {1468$age_str= (int$age/60/60/24/365);1469$age_str.=" years ago";1470}elsif($age>60*60*24*(365/12)*2) {1471$age_str=int$age/60/60/24/(365/12);1472$age_str.=" months ago";1473}elsif($age>60*60*24*7*2) {1474$age_str=int$age/60/60/24/7;1475$age_str.=" weeks ago";1476}elsif($age>60*60*24*2) {1477$age_str=int$age/60/60/24;1478$age_str.=" days ago";1479}elsif($age>60*60*2) {1480$age_str=int$age/60/60;1481$age_str.=" hours ago";1482}elsif($age>60*2) {1483$age_str=int$age/60;1484$age_str.=" min ago";1485}elsif($age>2) {1486$age_str=int$age;1487$age_str.=" sec ago";1488}else{1489$age_str.=" right now";1490}1491return$age_str;1492}14931494useconstant{1495 S_IFINVALID =>0030000,1496 S_IFGITLINK =>0160000,1497};14981499# submodule/subproject, a commit object reference1500sub S_ISGITLINK {1501my$mode=shift;15021503return(($mode& S_IFMT) == S_IFGITLINK)1504}15051506# convert file mode in octal to symbolic file mode string1507sub mode_str {1508my$mode=oct shift;15091510if(S_ISGITLINK($mode)) {1511return'm---------';1512}elsif(S_ISDIR($mode& S_IFMT)) {1513return'drwxr-xr-x';1514}elsif(S_ISLNK($mode)) {1515return'lrwxrwxrwx';1516}elsif(S_ISREG($mode)) {1517# git cares only about the executable bit1518if($mode& S_IXUSR) {1519return'-rwxr-xr-x';1520}else{1521return'-rw-r--r--';1522};1523}else{1524return'----------';1525}1526}15271528# convert file mode in octal to file type string1529sub file_type {1530my$mode=shift;15311532if($mode!~m/^[0-7]+$/) {1533return$mode;1534}else{1535$mode=oct$mode;1536}15371538if(S_ISGITLINK($mode)) {1539return"submodule";1540}elsif(S_ISDIR($mode& S_IFMT)) {1541return"directory";1542}elsif(S_ISLNK($mode)) {1543return"symlink";1544}elsif(S_ISREG($mode)) {1545return"file";1546}else{1547return"unknown";1548}1549}15501551# convert file mode in octal to file type description string1552sub file_type_long {1553my$mode=shift;15541555if($mode!~m/^[0-7]+$/) {1556return$mode;1557}else{1558$mode=oct$mode;1559}15601561if(S_ISGITLINK($mode)) {1562return"submodule";1563}elsif(S_ISDIR($mode& S_IFMT)) {1564return"directory";1565}elsif(S_ISLNK($mode)) {1566return"symlink";1567}elsif(S_ISREG($mode)) {1568if($mode& S_IXUSR) {1569return"executable";1570}else{1571return"file";1572};1573}else{1574return"unknown";1575}1576}157715781579## ----------------------------------------------------------------------1580## functions returning short HTML fragments, or transforming HTML fragments1581## which don't belong to other sections15821583# format line of commit message.1584sub format_log_line_html {1585my$line=shift;15861587$line= esc_html($line, -nbsp=>1);1588$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1589$cgi->a({-href => href(action=>"object", hash=>$1),1590-class=>"text"},$1);1591}eg;15921593return$line;1594}15951596# format marker of refs pointing to given object15971598# the destination action is chosen based on object type and current context:1599# - for annotated tags, we choose the tag view unless it's the current view1600# already, in which case we go to shortlog view1601# - for other refs, we keep the current view if we're in history, shortlog or1602# log view, and select shortlog otherwise1603sub format_ref_marker {1604my($refs,$id) =@_;1605my$markers='';16061607if(defined$refs->{$id}) {1608foreachmy$ref(@{$refs->{$id}}) {1609# this code exploits the fact that non-lightweight tags are the1610# only indirect objects, and that they are the only objects for which1611# we want to use tag instead of shortlog as action1612my($type,$name) =qw();1613my$indirect= ($ref=~s/\^\{\}$//);1614# e.g. tags/v2.6.11 or heads/next1615if($ref=~m!^(.*?)s?/(.*)$!) {1616$type=$1;1617$name=$2;1618}else{1619$type="ref";1620$name=$ref;1621}16221623my$class=$type;1624$class.=" indirect"if$indirect;16251626my$dest_action="shortlog";16271628if($indirect) {1629$dest_action="tag"unless$actioneq"tag";1630}elsif($action=~/^(history|(short)?log)$/) {1631$dest_action=$action;1632}16331634my$dest="";1635$dest.="refs/"unless$ref=~ m!^refs/!;1636$dest.=$ref;16371638my$link=$cgi->a({1639-href => href(1640 action=>$dest_action,1641 hash=>$dest1642)},$name);16431644$markers.=" <span class=\"$class\"title=\"$ref\">".1645$link."</span>";1646}1647}16481649if($markers) {1650return' <span class="refs">'.$markers.'</span>';1651}else{1652return"";1653}1654}16551656# format, perhaps shortened and with markers, title line1657sub format_subject_html {1658my($long,$short,$href,$extra) =@_;1659$extra=''unlessdefined($extra);16601661if(length($short) <length($long)) {1662$long=~s/[[:cntrl:]]/?/g;1663return$cgi->a({-href =>$href, -class=>"list subject",1664-title => to_utf8($long)},1665 esc_html($short)) .$extra;1666}else{1667return$cgi->a({-href =>$href, -class=>"list subject"},1668 esc_html($long)) .$extra;1669}1670}16711672# Rather than recomputing the url for an email multiple times, we cache it1673# after the first hit. This gives a visible benefit in views where the avatar1674# for the same email is used repeatedly (e.g. shortlog).1675# The cache is shared by all avatar engines (currently gravatar only), which1676# are free to use it as preferred. Since only one avatar engine is used for any1677# given page, there's no risk for cache conflicts.1678our%avatar_cache= ();16791680# Compute the picon url for a given email, by using the picon search service over at1681# http://www.cs.indiana.edu/picons/search.html1682sub picon_url {1683my$email=lc shift;1684if(!$avatar_cache{$email}) {1685my($user,$domain) =split('@',$email);1686$avatar_cache{$email} =1687"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1688"$domain/$user/".1689"users+domains+unknown/up/single";1690}1691return$avatar_cache{$email};1692}16931694# Compute the gravatar url for a given email, if it's not in the cache already.1695# Gravatar stores only the part of the URL before the size, since that's the1696# one computationally more expensive. This also allows reuse of the cache for1697# different sizes (for this particular engine).1698sub gravatar_url {1699my$email=lc shift;1700my$size=shift;1701$avatar_cache{$email} ||=1702"http://www.gravatar.com/avatar/".1703 Digest::MD5::md5_hex($email) ."?s=";1704return$avatar_cache{$email} .$size;1705}17061707# Insert an avatar for the given $email at the given $size if the feature1708# is enabled.1709sub git_get_avatar {1710my($email,%opts) =@_;1711my$pre_white= ($opts{-pad_before} ?" ":"");1712my$post_white= ($opts{-pad_after} ?" ":"");1713$opts{-size} ||='default';1714my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1715my$url="";1716if($git_avatareq'gravatar') {1717$url= gravatar_url($email,$size);1718}elsif($git_avatareq'picon') {1719$url= picon_url($email);1720}1721# Other providers can be added by extending the if chain, defining $url1722# as needed. If no variant puts something in $url, we assume avatars1723# are completely disabled/unavailable.1724if($url) {1725return$pre_white.1726"<img width=\"$size\"".1727"class=\"avatar\"".1728"src=\"$url\"".1729"alt=\"\"".1730"/>".$post_white;1731}else{1732return"";1733}1734}17351736sub format_search_author {1737my($author,$searchtype,$displaytext) =@_;1738my$have_search= gitweb_check_feature('search');17391740if($have_search) {1741my$performed="";1742if($searchtypeeq'author') {1743$performed="authored";1744}elsif($searchtypeeq'committer') {1745$performed="committed";1746}17471748return$cgi->a({-href => href(action=>"search", hash=>$hash,1749 searchtext=>$author,1750 searchtype=>$searchtype),class=>"list",1751 title=>"Search for commits$performedby$author"},1752$displaytext);17531754}else{1755return$displaytext;1756}1757}17581759# format the author name of the given commit with the given tag1760# the author name is chopped and escaped according to the other1761# optional parameters (see chop_str).1762sub format_author_html {1763my$tag=shift;1764my$co=shift;1765my$author= chop_and_escape_str($co->{'author_name'},@_);1766return"<$tagclass=\"author\">".1767 format_search_author($co->{'author_name'},"author",1768 git_get_avatar($co->{'author_email'}, -pad_after =>1) .1769$author) .1770"</$tag>";1771}17721773# format git diff header line, i.e. "diff --(git|combined|cc) ..."1774sub format_git_diff_header_line {1775my$line=shift;1776my$diffinfo=shift;1777my($from,$to) =@_;17781779if($diffinfo->{'nparents'}) {1780# combined diff1781$line=~s!^(diff (.*?) )"?.*$!$1!;1782if($to->{'href'}) {1783$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1784 esc_path($to->{'file'}));1785}else{# file was deleted (no href)1786$line.= esc_path($to->{'file'});1787}1788}else{1789# "ordinary" diff1790$line=~s!^(diff (.*?) )"?a/.*$!$1!;1791if($from->{'href'}) {1792$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},1793'a/'. esc_path($from->{'file'}));1794}else{# file was added (no href)1795$line.='a/'. esc_path($from->{'file'});1796}1797$line.=' ';1798if($to->{'href'}) {1799$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1800'b/'. esc_path($to->{'file'}));1801}else{# file was deleted1802$line.='b/'. esc_path($to->{'file'});1803}1804}18051806return"<div class=\"diff header\">$line</div>\n";1807}18081809# format extended diff header line, before patch itself1810sub format_extended_diff_header_line {1811my$line=shift;1812my$diffinfo=shift;1813my($from,$to) =@_;18141815# match <path>1816if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {1817$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},1818 esc_path($from->{'file'}));1819}1820if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {1821$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},1822 esc_path($to->{'file'}));1823}1824# match single <mode>1825if($line=~m/\s(\d{6})$/) {1826$line.='<span class="info"> ('.1827 file_type_long($1) .1828')</span>';1829}1830# match <hash>1831if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {1832# can match only for combined diff1833$line='index ';1834for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {1835if($from->{'href'}[$i]) {1836$line.=$cgi->a({-href=>$from->{'href'}[$i],1837-class=>"hash"},1838substr($diffinfo->{'from_id'}[$i],0,7));1839}else{1840$line.='0' x 7;1841}1842# separator1843$line.=','if($i<$diffinfo->{'nparents'} -1);1844}1845$line.='..';1846if($to->{'href'}) {1847$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},1848substr($diffinfo->{'to_id'},0,7));1849}else{1850$line.='0' x 7;1851}18521853}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {1854# can match only for ordinary diff1855my($from_link,$to_link);1856if($from->{'href'}) {1857$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},1858substr($diffinfo->{'from_id'},0,7));1859}else{1860$from_link='0' x 7;1861}1862if($to->{'href'}) {1863$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},1864substr($diffinfo->{'to_id'},0,7));1865}else{1866$to_link='0' x 7;1867}1868my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});1869$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;1870}18711872return$line."<br/>\n";1873}18741875# format from-file/to-file diff header1876sub format_diff_from_to_header {1877my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;1878my$line;1879my$result='';18801881$line=$from_line;1882#assert($line =~ m/^---/) if DEBUG;1883# no extra formatting for "^--- /dev/null"1884if(!$diffinfo->{'nparents'}) {1885# ordinary (single parent) diff1886if($line=~m!^--- "?a/!) {1887if($from->{'href'}) {1888$line='--- a/'.1889$cgi->a({-href=>$from->{'href'}, -class=>"path"},1890 esc_path($from->{'file'}));1891}else{1892$line='--- a/'.1893 esc_path($from->{'file'});1894}1895}1896$result.= qq!<div class="diff from_file">$line</div>\n!;18971898}else{1899# combined diff (merge commit)1900for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {1901if($from->{'href'}[$i]) {1902$line='--- '.1903$cgi->a({-href=>href(action=>"blobdiff",1904 hash_parent=>$diffinfo->{'from_id'}[$i],1905 hash_parent_base=>$parents[$i],1906 file_parent=>$from->{'file'}[$i],1907 hash=>$diffinfo->{'to_id'},1908 hash_base=>$hash,1909 file_name=>$to->{'file'}),1910-class=>"path",1911-title=>"diff". ($i+1)},1912$i+1) .1913'/'.1914$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},1915 esc_path($from->{'file'}[$i]));1916}else{1917$line='--- /dev/null';1918}1919$result.= qq!<div class="diff from_file">$line</div>\n!;1920}1921}19221923$line=$to_line;1924#assert($line =~ m/^\+\+\+/) if DEBUG;1925# no extra formatting for "^+++ /dev/null"1926if($line=~m!^\+\+\+ "?b/!) {1927if($to->{'href'}) {1928$line='+++ b/'.1929$cgi->a({-href=>$to->{'href'}, -class=>"path"},1930 esc_path($to->{'file'}));1931}else{1932$line='+++ b/'.1933 esc_path($to->{'file'});1934}1935}1936$result.= qq!<div class="diff to_file">$line</div>\n!;19371938return$result;1939}19401941# create note for patch simplified by combined diff1942sub format_diff_cc_simplified {1943my($diffinfo,@parents) =@_;1944my$result='';19451946$result.="<div class=\"diff header\">".1947"diff --cc ";1948if(!is_deleted($diffinfo)) {1949$result.=$cgi->a({-href => href(action=>"blob",1950 hash_base=>$hash,1951 hash=>$diffinfo->{'to_id'},1952 file_name=>$diffinfo->{'to_file'}),1953-class=>"path"},1954 esc_path($diffinfo->{'to_file'}));1955}else{1956$result.= esc_path($diffinfo->{'to_file'});1957}1958$result.="</div>\n".# class="diff header"1959"<div class=\"diff nodifferences\">".1960"Simple merge".1961"</div>\n";# class="diff nodifferences"19621963return$result;1964}19651966# format patch (diff) line (not to be used for diff headers)1967sub format_diff_line {1968my$line=shift;1969my($from,$to) =@_;1970my$diff_class="";19711972chomp$line;19731974if($from&&$to&&ref($from->{'href'})eq"ARRAY") {1975# combined diff1976my$prefix=substr($line,0,scalar@{$from->{'href'}});1977if($line=~m/^\@{3}/) {1978$diff_class=" chunk_header";1979}elsif($line=~m/^\\/) {1980$diff_class=" incomplete";1981}elsif($prefix=~tr/+/+/) {1982$diff_class=" add";1983}elsif($prefix=~tr/-/-/) {1984$diff_class=" rem";1985}1986}else{1987# assume ordinary diff1988my$char=substr($line,0,1);1989if($chareq'+') {1990$diff_class=" add";1991}elsif($chareq'-') {1992$diff_class=" rem";1993}elsif($chareq'@') {1994$diff_class=" chunk_header";1995}elsif($chareq"\\") {1996$diff_class=" incomplete";1997}1998}1999$line= untabify($line);2000if($from&&$to&&$line=~m/^\@{2} /) {2001my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2002$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;20032004$from_lines=0unlessdefined$from_lines;2005$to_lines=0unlessdefined$to_lines;20062007if($from->{'href'}) {2008$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2009-class=>"list"},$from_text);2010}2011if($to->{'href'}) {2012$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2013-class=>"list"},$to_text);2014}2015$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2016"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2017return"<div class=\"diff$diff_class\">$line</div>\n";2018}elsif($from&&$to&&$line=~m/^\@{3}/) {2019my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2020my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);20212022@from_text=split(' ',$ranges);2023for(my$i=0;$i<@from_text; ++$i) {2024($from_start[$i],$from_nlines[$i]) =2025(split(',',substr($from_text[$i],1)),0);2026}20272028$to_text=pop@from_text;2029$to_start=pop@from_start;2030$to_nlines=pop@from_nlines;20312032$line="<span class=\"chunk_info\">$prefix";2033for(my$i=0;$i<@from_text; ++$i) {2034if($from->{'href'}[$i]) {2035$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2036-class=>"list"},$from_text[$i]);2037}else{2038$line.=$from_text[$i];2039}2040$line.=" ";2041}2042if($to->{'href'}) {2043$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2044-class=>"list"},$to_text);2045}else{2046$line.=$to_text;2047}2048$line.="$prefix</span>".2049"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2050return"<div class=\"diff$diff_class\">$line</div>\n";2051}2052return"<div class=\"diff$diff_class\">". esc_html($line, -nbsp=>1) ."</div>\n";2053}20542055# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2056# linked. Pass the hash of the tree/commit to snapshot.2057sub format_snapshot_links {2058my($hash) =@_;2059my$num_fmts=@snapshot_fmts;2060if($num_fmts>1) {2061# A parenthesized list of links bearing format names.2062# e.g. "snapshot (_tar.gz_ _zip_)"2063return"snapshot (".join(' ',map2064$cgi->a({2065-href => href(2066 action=>"snapshot",2067 hash=>$hash,2068 snapshot_format=>$_2069)2070},$known_snapshot_formats{$_}{'display'})2071,@snapshot_fmts) .")";2072}elsif($num_fmts==1) {2073# A single "snapshot" link whose tooltip bears the format name.2074# i.e. "_snapshot_"2075my($fmt) =@snapshot_fmts;2076return2077$cgi->a({2078-href => href(2079 action=>"snapshot",2080 hash=>$hash,2081 snapshot_format=>$fmt2082),2083-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2084},"snapshot");2085}else{# $num_fmts == 02086returnundef;2087}2088}20892090## ......................................................................2091## functions returning values to be passed, perhaps after some2092## transformation, to other functions; e.g. returning arguments to href()20932094# returns hash to be passed to href to generate gitweb URL2095# in -title key it returns description of link2096sub get_feed_info {2097my$format=shift||'Atom';2098my%res= (action =>lc($format));20992100# feed links are possible only for project views2101return unless(defined$project);2102# some views should link to OPML, or to generic project feed,2103# or don't have specific feed yet (so they should use generic)2104return if($action=~/^(?:tags|heads|forks|tag|search)$/x);21052106my$branch;2107# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2108# from tag links; this also makes possible to detect branch links2109if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2110(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2111$branch=$1;2112}2113# find log type for feed description (title)2114my$type='log';2115if(defined$file_name) {2116$type="history of$file_name";2117$type.="/"if($actioneq'tree');2118$type.=" on '$branch'"if(defined$branch);2119}else{2120$type="log of$branch"if(defined$branch);2121}21222123$res{-title} =$type;2124$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2125$res{'file_name'} =$file_name;21262127return%res;2128}21292130## ----------------------------------------------------------------------2131## git utility subroutines, invoking git commands21322133# returns path to the core git executable and the --git-dir parameter as list2134sub git_cmd {2135$number_of_git_cmds++;2136return$GIT,'--git-dir='.$git_dir;2137}21382139# quote the given arguments for passing them to the shell2140# quote_command("command", "arg 1", "arg with ' and ! characters")2141# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2142# Try to avoid using this function wherever possible.2143sub quote_command {2144returnjoin(' ',2145map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2146}21472148# get HEAD ref of given project as hash2149sub git_get_head_hash {2150return git_get_full_hash(shift,'HEAD');2151}21522153sub git_get_full_hash {2154return git_get_hash(@_);2155}21562157sub git_get_short_hash {2158return git_get_hash(@_,'--short=7');2159}21602161sub git_get_hash {2162my($project,$hash,@options) =@_;2163my$o_git_dir=$git_dir;2164my$retval=undef;2165$git_dir="$projectroot/$project";2166if(open my$fd,'-|', git_cmd(),'rev-parse',2167'--verify','-q',@options,$hash) {2168$retval= <$fd>;2169chomp$retvalifdefined$retval;2170close$fd;2171}2172if(defined$o_git_dir) {2173$git_dir=$o_git_dir;2174}2175return$retval;2176}21772178# get type of given object2179sub git_get_type {2180my$hash=shift;21812182open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2183my$type= <$fd>;2184close$fdorreturn;2185chomp$type;2186return$type;2187}21882189# repository configuration2190our$config_file='';2191our%config;21922193# store multiple values for single key as anonymous array reference2194# single values stored directly in the hash, not as [ <value> ]2195sub hash_set_multi {2196my($hash,$key,$value) =@_;21972198if(!exists$hash->{$key}) {2199$hash->{$key} =$value;2200}elsif(!ref$hash->{$key}) {2201$hash->{$key} = [$hash->{$key},$value];2202}else{2203push@{$hash->{$key}},$value;2204}2205}22062207# return hash of git project configuration2208# optionally limited to some section, e.g. 'gitweb'2209sub git_parse_project_config {2210my$section_regexp=shift;2211my%config;22122213local$/="\0";22142215open my$fh,"-|", git_cmd(),"config",'-z','-l',2216orreturn;22172218while(my$keyval= <$fh>) {2219chomp$keyval;2220my($key,$value) =split(/\n/,$keyval,2);22212222 hash_set_multi(\%config,$key,$value)2223if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2224}2225close$fh;22262227return%config;2228}22292230# convert config value to boolean: 'true' or 'false'2231# no value, number > 0, 'true' and 'yes' values are true2232# rest of values are treated as false (never as error)2233sub config_to_bool {2234my$val=shift;22352236return1if!defined$val;# section.key22372238# strip leading and trailing whitespace2239$val=~s/^\s+//;2240$val=~s/\s+$//;22412242return(($val=~/^\d+$/&&$val) ||# section.key = 12243($val=~/^(?:true|yes)$/i));# section.key = true2244}22452246# convert config value to simple decimal number2247# an optional value suffix of 'k', 'm', or 'g' will cause the value2248# to be multiplied by 1024, 1048576, or 10737418242249sub config_to_int {2250my$val=shift;22512252# strip leading and trailing whitespace2253$val=~s/^\s+//;2254$val=~s/\s+$//;22552256if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2257$unit=lc($unit);2258# unknown unit is treated as 12259return$num* ($uniteq'g'?1073741824:2260$uniteq'm'?1048576:2261$uniteq'k'?1024:1);2262}2263return$val;2264}22652266# convert config value to array reference, if needed2267sub config_to_multi {2268my$val=shift;22692270returnref($val) ?$val: (defined($val) ? [$val] : []);2271}22722273sub git_get_project_config {2274my($key,$type) =@_;22752276return unlessdefined$git_dir;22772278# key sanity check2279return unless($key);2280$key=~s/^gitweb\.//;2281return if($key=~m/\W/);22822283# type sanity check2284if(defined$type) {2285$type=~s/^--//;2286$type=undef2287unless($typeeq'bool'||$typeeq'int');2288}22892290# get config2291if(!defined$config_file||2292$config_filene"$git_dir/config") {2293%config= git_parse_project_config('gitweb');2294$config_file="$git_dir/config";2295}22962297# check if config variable (key) exists2298return unlessexists$config{"gitweb.$key"};22992300# ensure given type2301if(!defined$type) {2302return$config{"gitweb.$key"};2303}elsif($typeeq'bool') {2304# backward compatibility: 'git config --bool' returns true/false2305return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2306}elsif($typeeq'int') {2307return config_to_int($config{"gitweb.$key"});2308}2309return$config{"gitweb.$key"};2310}23112312# get hash of given path at given ref2313sub git_get_hash_by_path {2314my$base=shift;2315my$path=shift||returnundef;2316my$type=shift;23172318$path=~ s,/+$,,;23192320open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2321or die_error(500,"Open git-ls-tree failed");2322my$line= <$fd>;2323close$fdorreturnundef;23242325if(!defined$line) {2326# there is no tree or hash given by $path at $base2327returnundef;2328}23292330#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2331$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2332if(defined$type&&$typene$2) {2333# type doesn't match2334returnundef;2335}2336return$3;2337}23382339# get path of entry with given hash at given tree-ish (ref)2340# used to get 'from' filename for combined diff (merge commit) for renames2341sub git_get_path_by_hash {2342my$base=shift||return;2343my$hash=shift||return;23442345local$/="\0";23462347open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2348orreturnundef;2349while(my$line= <$fd>) {2350chomp$line;23512352#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2353#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2354if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2355close$fd;2356return$1;2357}2358}2359close$fd;2360returnundef;2361}23622363## ......................................................................2364## git utility functions, directly accessing git repository23652366sub git_get_project_description {2367my$path=shift;23682369$git_dir="$projectroot/$path";2370open my$fd,'<',"$git_dir/description"2371orreturn git_get_project_config('description');2372my$descr= <$fd>;2373close$fd;2374if(defined$descr) {2375chomp$descr;2376}2377return$descr;2378}23792380sub git_get_project_ctags {2381my$path=shift;2382my$ctags= {};23832384$git_dir="$projectroot/$path";2385opendir my$dh,"$git_dir/ctags"2386orreturn$ctags;2387foreach(grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh)) {2388open my$ct,'<',$_ornext;2389my$val= <$ct>;2390chomp$val;2391close$ct;2392my$ctag=$_;$ctag=~ s#.*/##;2393$ctags->{$ctag} =$val;2394}2395closedir$dh;2396$ctags;2397}23982399sub git_populate_project_tagcloud {2400my$ctags=shift;24012402# First, merge different-cased tags; tags vote on casing2403my%ctags_lc;2404foreach(keys%$ctags) {2405$ctags_lc{lc$_}->{count} +=$ctags->{$_};2406if(not$ctags_lc{lc$_}->{topcount}2407or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2408$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2409$ctags_lc{lc$_}->{topname} =$_;2410}2411}24122413my$cloud;2414if(eval{require HTML::TagCloud;1; }) {2415$cloud= HTML::TagCloud->new;2416foreach(sort keys%ctags_lc) {2417# Pad the title with spaces so that the cloud looks2418# less crammed.2419my$title=$ctags_lc{$_}->{topname};2420$title=~s/ / /g;2421$title=~s/^/ /g;2422$title=~s/$/ /g;2423$cloud->add($title,$home_link."?by_tag=".$_,$ctags_lc{$_}->{count});2424}2425}else{2426$cloud= \%ctags_lc;2427}2428$cloud;2429}24302431sub git_show_project_tagcloud {2432my($cloud,$count) =@_;2433print STDERR ref($cloud)."..\n";2434if(ref$cloudeq'HTML::TagCloud') {2435return$cloud->html_and_css($count);2436}else{2437my@tags=sort{$cloud->{$a}->{count} <=>$cloud->{$b}->{count} }keys%$cloud;2438return'<p align="center">'.join(', ',map{2439"<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"2440}splice(@tags,0,$count)) .'</p>';2441}2442}24432444sub git_get_project_url_list {2445my$path=shift;24462447$git_dir="$projectroot/$path";2448open my$fd,'<',"$git_dir/cloneurl"2449orreturnwantarray?2450@{ config_to_multi(git_get_project_config('url')) } :2451 config_to_multi(git_get_project_config('url'));2452my@git_project_url_list=map{chomp;$_} <$fd>;2453close$fd;24542455returnwantarray?@git_project_url_list: \@git_project_url_list;2456}24572458sub git_get_projects_list {2459my($filter) =@_;2460my@list;24612462$filter||='';2463$filter=~s/\.git$//;24642465my$check_forks= gitweb_check_feature('forks');24662467if(-d $projects_list) {2468# search in directory2469my$dir=$projects_list. ($filter?"/$filter":'');2470# remove the trailing "/"2471$dir=~s!/+$!!;2472my$pfxlen=length("$dir");2473my$pfxdepth= ($dir=~tr!/!!);24742475 File::Find::find({2476 follow_fast =>1,# follow symbolic links2477 follow_skip =>2,# ignore duplicates2478 dangling_symlinks =>0,# ignore dangling symlinks, silently2479 wanted =>sub{2480# skip project-list toplevel, if we get it.2481return if(m!^[/.]$!);2482# only directories can be git repositories2483return unless(-d $_);2484# don't traverse too deep (Find is super slow on os x)2485if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2486$File::Find::prune =1;2487return;2488}24892490my$subdir=substr($File::Find::name,$pfxlen+1);2491# we check related file in $projectroot2492my$path= ($filter?"$filter/":'') .$subdir;2493if(check_export_ok("$projectroot/$path")) {2494push@list, { path =>$path};2495$File::Find::prune =1;2496}2497},2498},"$dir");24992500}elsif(-f $projects_list) {2501# read from file(url-encoded):2502# 'git%2Fgit.git Linus+Torvalds'2503# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2504# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2505my%paths;2506open my$fd,'<',$projects_listorreturn;2507 PROJECT:2508while(my$line= <$fd>) {2509chomp$line;2510my($path,$owner) =split' ',$line;2511$path= unescape($path);2512$owner= unescape($owner);2513if(!defined$path) {2514next;2515}2516if($filterne'') {2517# looking for forks;2518my$pfx=substr($path,0,length($filter));2519if($pfxne$filter) {2520next PROJECT;2521}2522my$sfx=substr($path,length($filter));2523if($sfx!~/^\/.*\.git$/) {2524next PROJECT;2525}2526}elsif($check_forks) {2527 PATH:2528foreachmy$filter(keys%paths) {2529# looking for forks;2530my$pfx=substr($path,0,length($filter));2531if($pfxne$filter) {2532next PATH;2533}2534my$sfx=substr($path,length($filter));2535if($sfx!~/^\/.*\.git$/) {2536next PATH;2537}2538# is a fork, don't include it in2539# the list2540next PROJECT;2541}2542}2543if(check_export_ok("$projectroot/$path")) {2544my$pr= {2545 path =>$path,2546 owner => to_utf8($owner),2547};2548push@list,$pr;2549(my$forks_path=$path) =~s/\.git$//;2550$paths{$forks_path}++;2551}2552}2553close$fd;2554}2555return@list;2556}25572558our$gitweb_project_owner=undef;2559sub git_get_project_list_from_file {25602561return if(defined$gitweb_project_owner);25622563$gitweb_project_owner= {};2564# read from file (url-encoded):2565# 'git%2Fgit.git Linus+Torvalds'2566# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2567# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2568if(-f $projects_list) {2569open(my$fd,'<',$projects_list);2570while(my$line= <$fd>) {2571chomp$line;2572my($pr,$ow) =split' ',$line;2573$pr= unescape($pr);2574$ow= unescape($ow);2575$gitweb_project_owner->{$pr} = to_utf8($ow);2576}2577close$fd;2578}2579}25802581sub git_get_project_owner {2582my$project=shift;2583my$owner;25842585returnundefunless$project;2586$git_dir="$projectroot/$project";25872588if(!defined$gitweb_project_owner) {2589 git_get_project_list_from_file();2590}25912592if(exists$gitweb_project_owner->{$project}) {2593$owner=$gitweb_project_owner->{$project};2594}2595if(!defined$owner){2596$owner= git_get_project_config('owner');2597}2598if(!defined$owner) {2599$owner= get_file_owner("$git_dir");2600}26012602return$owner;2603}26042605sub git_get_last_activity {2606my($path) =@_;2607my$fd;26082609$git_dir="$projectroot/$path";2610open($fd,"-|", git_cmd(),'for-each-ref',2611'--format=%(committer)',2612'--sort=-committerdate',2613'--count=1',2614'refs/heads')orreturn;2615my$most_recent= <$fd>;2616close$fdorreturn;2617if(defined$most_recent&&2618$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {2619my$timestamp=$1;2620my$age=time-$timestamp;2621return($age, age_string($age));2622}2623return(undef,undef);2624}26252626sub git_get_references {2627my$type=shift||"";2628my%refs;2629# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.112630# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}2631open my$fd,"-|", git_cmd(),"show-ref","--dereference",2632($type? ("--","refs/$type") : ())# use -- <pattern> if $type2633orreturn;26342635while(my$line= <$fd>) {2636chomp$line;2637if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {2638if(defined$refs{$1}) {2639push@{$refs{$1}},$2;2640}else{2641$refs{$1} = [$2];2642}2643}2644}2645close$fdorreturn;2646return \%refs;2647}26482649sub git_get_rev_name_tags {2650my$hash=shift||returnundef;26512652open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash2653orreturn;2654my$name_rev= <$fd>;2655close$fd;26562657if($name_rev=~ m|^$hash tags/(.*)$|) {2658return$1;2659}else{2660# catches also '$hash undefined' output2661returnundef;2662}2663}26642665## ----------------------------------------------------------------------2666## parse to hash functions26672668sub parse_date {2669my$epoch=shift;2670my$tz=shift||"-0000";26712672my%date;2673my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");2674my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");2675my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);2676$date{'hour'} =$hour;2677$date{'minute'} =$min;2678$date{'mday'} =$mday;2679$date{'day'} =$days[$wday];2680$date{'month'} =$months[$mon];2681$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",2682$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;2683$date{'mday-time'} =sprintf"%d%s%02d:%02d",2684$mday,$months[$mon],$hour,$min;2685$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",26861900+$year,1+$mon,$mday,$hour,$min,$sec;26872688$tz=~m/^([+\-][0-9][0-9])([0-9][0-9])$/;2689my$local=$epoch+ ((int$1+ ($2/60)) *3600);2690($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);2691$date{'hour_local'} =$hour;2692$date{'minute_local'} =$min;2693$date{'tz_local'} =$tz;2694$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",26951900+$year,$mon+1,$mday,2696$hour,$min,$sec,$tz);2697return%date;2698}26992700sub parse_tag {2701my$tag_id=shift;2702my%tag;2703my@comment;27042705open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;2706$tag{'id'} =$tag_id;2707while(my$line= <$fd>) {2708chomp$line;2709if($line=~m/^object ([0-9a-fA-F]{40})$/) {2710$tag{'object'} =$1;2711}elsif($line=~m/^type (.+)$/) {2712$tag{'type'} =$1;2713}elsif($line=~m/^tag (.+)$/) {2714$tag{'name'} =$1;2715}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {2716$tag{'author'} =$1;2717$tag{'author_epoch'} =$2;2718$tag{'author_tz'} =$3;2719if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {2720$tag{'author_name'} =$1;2721$tag{'author_email'} =$2;2722}else{2723$tag{'author_name'} =$tag{'author'};2724}2725}elsif($line=~m/--BEGIN/) {2726push@comment,$line;2727last;2728}elsif($lineeq"") {2729last;2730}2731}2732push@comment, <$fd>;2733$tag{'comment'} = \@comment;2734close$fdorreturn;2735if(!defined$tag{'name'}) {2736return2737};2738return%tag2739}27402741sub parse_commit_text {2742my($commit_text,$withparents) =@_;2743my@commit_lines=split'\n',$commit_text;2744my%co;27452746pop@commit_lines;# Remove '\0'27472748if(!@commit_lines) {2749return;2750}27512752my$header=shift@commit_lines;2753if($header!~m/^[0-9a-fA-F]{40}/) {2754return;2755}2756($co{'id'},my@parents) =split' ',$header;2757while(my$line=shift@commit_lines) {2758last if$lineeq"\n";2759if($line=~m/^tree ([0-9a-fA-F]{40})$/) {2760$co{'tree'} =$1;2761}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {2762push@parents,$1;2763}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {2764$co{'author'} = to_utf8($1);2765$co{'author_epoch'} =$2;2766$co{'author_tz'} =$3;2767if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {2768$co{'author_name'} =$1;2769$co{'author_email'} =$2;2770}else{2771$co{'author_name'} =$co{'author'};2772}2773}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {2774$co{'committer'} = to_utf8($1);2775$co{'committer_epoch'} =$2;2776$co{'committer_tz'} =$3;2777if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {2778$co{'committer_name'} =$1;2779$co{'committer_email'} =$2;2780}else{2781$co{'committer_name'} =$co{'committer'};2782}2783}2784}2785if(!defined$co{'tree'}) {2786return;2787};2788$co{'parents'} = \@parents;2789$co{'parent'} =$parents[0];27902791foreachmy$title(@commit_lines) {2792$title=~s/^ //;2793if($titlene"") {2794$co{'title'} = chop_str($title,80,5);2795# remove leading stuff of merges to make the interesting part visible2796if(length($title) >50) {2797$title=~s/^Automatic //;2798$title=~s/^merge (of|with) /Merge ... /i;2799if(length($title) >50) {2800$title=~s/(http|rsync):\/\///;2801}2802if(length($title) >50) {2803$title=~s/(master|www|rsync)\.//;2804}2805if(length($title) >50) {2806$title=~s/kernel.org:?//;2807}2808if(length($title) >50) {2809$title=~s/\/pub\/scm//;2810}2811}2812$co{'title_short'} = chop_str($title,50,5);2813last;2814}2815}2816if(!defined$co{'title'} ||$co{'title'}eq"") {2817$co{'title'} =$co{'title_short'} ='(no commit message)';2818}2819# remove added spaces2820foreachmy$line(@commit_lines) {2821$line=~s/^ //;2822}2823$co{'comment'} = \@commit_lines;28242825my$age=time-$co{'committer_epoch'};2826$co{'age'} =$age;2827$co{'age_string'} = age_string($age);2828my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});2829if($age>60*60*24*7*2) {2830$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;2831$co{'age_string_age'} =$co{'age_string'};2832}else{2833$co{'age_string_date'} =$co{'age_string'};2834$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;2835}2836return%co;2837}28382839sub parse_commit {2840my($commit_id) =@_;2841my%co;28422843local$/="\0";28442845open my$fd,"-|", git_cmd(),"rev-list",2846"--parents",2847"--header",2848"--max-count=1",2849$commit_id,2850"--",2851or die_error(500,"Open git-rev-list failed");2852%co= parse_commit_text(<$fd>,1);2853close$fd;28542855return%co;2856}28572858sub parse_commits {2859my($commit_id,$maxcount,$skip,$filename,@args) =@_;2860my@cos;28612862$maxcount||=1;2863$skip||=0;28642865local$/="\0";28662867open my$fd,"-|", git_cmd(),"rev-list",2868"--header",2869@args,2870("--max-count=".$maxcount),2871("--skip=".$skip),2872@extra_options,2873$commit_id,2874"--",2875($filename? ($filename) : ())2876or die_error(500,"Open git-rev-list failed");2877while(my$line= <$fd>) {2878my%co= parse_commit_text($line);2879push@cos, \%co;2880}2881close$fd;28822883returnwantarray?@cos: \@cos;2884}28852886# parse line of git-diff-tree "raw" output2887sub parse_difftree_raw_line {2888my$line=shift;2889my%res;28902891# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'2892# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'2893if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {2894$res{'from_mode'} =$1;2895$res{'to_mode'} =$2;2896$res{'from_id'} =$3;2897$res{'to_id'} =$4;2898$res{'status'} =$5;2899$res{'similarity'} =$6;2900if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied2901($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);2902}else{2903$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);2904}2905}2906# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'2907# combined diff (for merge commit)2908elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {2909$res{'nparents'} =length($1);2910$res{'from_mode'} = [split(' ',$2) ];2911$res{'to_mode'} =pop@{$res{'from_mode'}};2912$res{'from_id'} = [split(' ',$3) ];2913$res{'to_id'} =pop@{$res{'from_id'}};2914$res{'status'} = [split('',$4) ];2915$res{'to_file'} = unquote($5);2916}2917# 'c512b523472485aef4fff9e57b229d9d243c967f'2918elsif($line=~m/^([0-9a-fA-F]{40})$/) {2919$res{'commit'} =$1;2920}29212922returnwantarray?%res: \%res;2923}29242925# wrapper: return parsed line of git-diff-tree "raw" output2926# (the argument might be raw line, or parsed info)2927sub parsed_difftree_line {2928my$line_or_ref=shift;29292930if(ref($line_or_ref)eq"HASH") {2931# pre-parsed (or generated by hand)2932return$line_or_ref;2933}else{2934return parse_difftree_raw_line($line_or_ref);2935}2936}29372938# parse line of git-ls-tree output2939sub parse_ls_tree_line {2940my$line=shift;2941my%opts=@_;2942my%res;29432944if($opts{'-l'}) {2945#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'2946$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;29472948$res{'mode'} =$1;2949$res{'type'} =$2;2950$res{'hash'} =$3;2951$res{'size'} =$4;2952if($opts{'-z'}) {2953$res{'name'} =$5;2954}else{2955$res{'name'} = unquote($5);2956}2957}else{2958#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2959$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;29602961$res{'mode'} =$1;2962$res{'type'} =$2;2963$res{'hash'} =$3;2964if($opts{'-z'}) {2965$res{'name'} =$4;2966}else{2967$res{'name'} = unquote($4);2968}2969}29702971returnwantarray?%res: \%res;2972}29732974# generates _two_ hashes, references to which are passed as 2 and 3 argument2975sub parse_from_to_diffinfo {2976my($diffinfo,$from,$to,@parents) =@_;29772978if($diffinfo->{'nparents'}) {2979# combined diff2980$from->{'file'} = [];2981$from->{'href'} = [];2982 fill_from_file_info($diffinfo,@parents)2983unlessexists$diffinfo->{'from_file'};2984for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2985$from->{'file'}[$i] =2986defined$diffinfo->{'from_file'}[$i] ?2987$diffinfo->{'from_file'}[$i] :2988$diffinfo->{'to_file'};2989if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file2990$from->{'href'}[$i] = href(action=>"blob",2991 hash_base=>$parents[$i],2992 hash=>$diffinfo->{'from_id'}[$i],2993 file_name=>$from->{'file'}[$i]);2994}else{2995$from->{'href'}[$i] =undef;2996}2997}2998}else{2999# ordinary (not combined) diff3000$from->{'file'} =$diffinfo->{'from_file'};3001if($diffinfo->{'status'}ne"A") {# not new (added) file3002$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3003 hash=>$diffinfo->{'from_id'},3004 file_name=>$from->{'file'});3005}else{3006delete$from->{'href'};3007}3008}30093010$to->{'file'} =$diffinfo->{'to_file'};3011if(!is_deleted($diffinfo)) {# file exists in result3012$to->{'href'} = href(action=>"blob", hash_base=>$hash,3013 hash=>$diffinfo->{'to_id'},3014 file_name=>$to->{'file'});3015}else{3016delete$to->{'href'};3017}3018}30193020## ......................................................................3021## parse to array of hashes functions30223023sub git_get_heads_list {3024my$limit=shift;3025my@headslist;30263027open my$fd,'-|', git_cmd(),'for-each-ref',3028($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3029'--format=%(objectname) %(refname) %(subject)%00%(committer)',3030'refs/heads'3031orreturn;3032while(my$line= <$fd>) {3033my%ref_item;30343035chomp$line;3036my($refinfo,$committerinfo) =split(/\0/,$line);3037my($hash,$name,$title) =split(' ',$refinfo,3);3038my($committer,$epoch,$tz) =3039($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3040$ref_item{'fullname'} =$name;3041$name=~s!^refs/heads/!!;30423043$ref_item{'name'} =$name;3044$ref_item{'id'} =$hash;3045$ref_item{'title'} =$title||'(no commit message)';3046$ref_item{'epoch'} =$epoch;3047if($epoch) {3048$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3049}else{3050$ref_item{'age'} ="unknown";3051}30523053push@headslist, \%ref_item;3054}3055close$fd;30563057returnwantarray?@headslist: \@headslist;3058}30593060sub git_get_tags_list {3061my$limit=shift;3062my@tagslist;30633064open my$fd,'-|', git_cmd(),'for-each-ref',3065($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3066'--format=%(objectname) %(objecttype) %(refname) '.3067'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3068'refs/tags'3069orreturn;3070while(my$line= <$fd>) {3071my%ref_item;30723073chomp$line;3074my($refinfo,$creatorinfo) =split(/\0/,$line);3075my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3076my($creator,$epoch,$tz) =3077($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3078$ref_item{'fullname'} =$name;3079$name=~s!^refs/tags/!!;30803081$ref_item{'type'} =$type;3082$ref_item{'id'} =$id;3083$ref_item{'name'} =$name;3084if($typeeq"tag") {3085$ref_item{'subject'} =$title;3086$ref_item{'reftype'} =$reftype;3087$ref_item{'refid'} =$refid;3088}else{3089$ref_item{'reftype'} =$type;3090$ref_item{'refid'} =$id;3091}30923093if($typeeq"tag"||$typeeq"commit") {3094$ref_item{'epoch'} =$epoch;3095if($epoch) {3096$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3097}else{3098$ref_item{'age'} ="unknown";3099}3100}31013102push@tagslist, \%ref_item;3103}3104close$fd;31053106returnwantarray?@tagslist: \@tagslist;3107}31083109## ----------------------------------------------------------------------3110## filesystem-related functions31113112sub get_file_owner {3113my$path=shift;31143115my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3116my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3117if(!defined$gcos) {3118returnundef;3119}3120my$owner=$gcos;3121$owner=~s/[,;].*$//;3122return to_utf8($owner);3123}31243125# assume that file exists3126sub insert_file {3127my$filename=shift;31283129open my$fd,'<',$filename;3130print map{ to_utf8($_) } <$fd>;3131close$fd;3132}31333134## ......................................................................3135## mimetype related functions31363137sub mimetype_guess_file {3138my$filename=shift;3139my$mimemap=shift;3140-r $mimemaporreturnundef;31413142my%mimemap;3143open(my$mh,'<',$mimemap)orreturnundef;3144while(<$mh>) {3145next ifm/^#/;# skip comments3146my($mimetype,$exts) =split(/\t+/);3147if(defined$exts) {3148my@exts=split(/\s+/,$exts);3149foreachmy$ext(@exts) {3150$mimemap{$ext} =$mimetype;3151}3152}3153}3154close($mh);31553156$filename=~/\.([^.]*)$/;3157return$mimemap{$1};3158}31593160sub mimetype_guess {3161my$filename=shift;3162my$mime;3163$filename=~/\./orreturnundef;31643165if($mimetypes_file) {3166my$file=$mimetypes_file;3167if($file!~m!^/!) {# if it is relative path3168# it is relative to project3169$file="$projectroot/$project/$file";3170}3171$mime= mimetype_guess_file($filename,$file);3172}3173$mime||= mimetype_guess_file($filename,'/etc/mime.types');3174return$mime;3175}31763177sub blob_mimetype {3178my$fd=shift;3179my$filename=shift;31803181if($filename) {3182my$mime= mimetype_guess($filename);3183$mimeandreturn$mime;3184}31853186# just in case3187return$default_blob_plain_mimetypeunless$fd;31883189if(-T $fd) {3190return'text/plain';3191}elsif(!$filename) {3192return'application/octet-stream';3193}elsif($filename=~m/\.png$/i) {3194return'image/png';3195}elsif($filename=~m/\.gif$/i) {3196return'image/gif';3197}elsif($filename=~m/\.jpe?g$/i) {3198return'image/jpeg';3199}else{3200return'application/octet-stream';3201}3202}32033204sub blob_contenttype {3205my($fd,$file_name,$type) =@_;32063207$type||= blob_mimetype($fd,$file_name);3208if($typeeq'text/plain'&&defined$default_text_plain_charset) {3209$type.="; charset=$default_text_plain_charset";3210}32113212return$type;3213}32143215## ======================================================================3216## functions printing HTML: header, footer, error page32173218sub git_header_html {3219my$status=shift||"200 OK";3220my$expires=shift;32213222my$title="$site_name";3223if(defined$project) {3224$title.=" - ". to_utf8($project);3225if(defined$action) {3226$title.="/$action";3227if(defined$file_name) {3228$title.=" - ". esc_path($file_name);3229if($actioneq"tree"&&$file_name!~ m|/$|) {3230$title.="/";3231}3232}3233}3234}3235my$content_type;3236# require explicit support from the UA if we are to send the page as3237# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3238# we have to do this because MSIE sometimes globs '*/*', pretending to3239# support xhtml+xml but choking when it gets what it asked for.3240if(defined$cgi->http('HTTP_ACCEPT') &&3241$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3242$cgi->Accept('application/xhtml+xml') !=0) {3243$content_type='application/xhtml+xml';3244}else{3245$content_type='text/html';3246}3247print$cgi->header(-type=>$content_type, -charset =>'utf-8',3248-status=>$status, -expires =>$expires);3249my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3250print<<EOF;3251<?xml version="1.0" encoding="utf-8"?>3252<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3253<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3254<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3255<!-- git core binaries version$git_version-->3256<head>3257<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3258<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3259<meta name="robots" content="index, nofollow"/>3260<title>$title</title>3261EOF3262# the stylesheet, favicon etc urls won't work correctly with path_info3263# unless we set the appropriate base URL3264if($ENV{'PATH_INFO'}) {3265print"<base href=\"".esc_url($base_url)."\"/>\n";3266}3267# print out each stylesheet that exist, providing backwards capability3268# for those people who defined $stylesheet in a config file3269if(defined$stylesheet) {3270print'<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";3271}else{3272foreachmy$stylesheet(@stylesheets) {3273next unless$stylesheet;3274print'<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";3275}3276}3277if(defined$project) {3278my%href_params= get_feed_info();3279if(!exists$href_params{'-title'}) {3280$href_params{'-title'} ='log';3281}32823283foreachmy$formatqw(RSS Atom){3284my$type=lc($format);3285my%link_attr= (3286'-rel'=>'alternate',3287'-title'=>"$project-$href_params{'-title'} -$formatfeed",3288'-type'=>"application/$type+xml"3289);32903291$href_params{'action'} =$type;3292$link_attr{'-href'} = href(%href_params);3293print"<link ".3294"rel=\"$link_attr{'-rel'}\"".3295"title=\"$link_attr{'-title'}\"".3296"href=\"$link_attr{'-href'}\"".3297"type=\"$link_attr{'-type'}\"".3298"/>\n";32993300$href_params{'extra_options'} ='--no-merges';3301$link_attr{'-href'} = href(%href_params);3302$link_attr{'-title'} .=' (no merges)';3303print"<link ".3304"rel=\"$link_attr{'-rel'}\"".3305"title=\"$link_attr{'-title'}\"".3306"href=\"$link_attr{'-href'}\"".3307"type=\"$link_attr{'-type'}\"".3308"/>\n";3309}33103311}else{3312printf('<link rel="alternate" title="%sprojects list" '.3313'href="%s" type="text/plain; charset=utf-8" />'."\n",3314$site_name, href(project=>undef, action=>"project_index"));3315printf('<link rel="alternate" title="%sprojects feeds" '.3316'href="%s" type="text/x-opml" />'."\n",3317$site_name, href(project=>undef, action=>"opml"));3318}3319if(defined$favicon) {3320printqq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);3321}33223323print"</head>\n".3324"<body>\n";33253326if(defined$site_header&& -f $site_header) {3327 insert_file($site_header);3328}33293330print"<div class=\"page_header\">\n".3331$cgi->a({-href => esc_url($logo_url),3332-title =>$logo_label},3333qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));3334print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3335if(defined$project) {3336print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3337if(defined$action) {3338print" /$action";3339}3340print"\n";3341}3342print"</div>\n";33433344my$have_search= gitweb_check_feature('search');3345if(defined$project&&$have_search) {3346if(!defined$searchtext) {3347$searchtext="";3348}3349my$search_hash;3350if(defined$hash_base) {3351$search_hash=$hash_base;3352}elsif(defined$hash) {3353$search_hash=$hash;3354}else{3355$search_hash="HEAD";3356}3357my$action=$my_uri;3358my$use_pathinfo= gitweb_check_feature('pathinfo');3359if($use_pathinfo) {3360$action.="/".esc_url($project);3361}3362print$cgi->startform(-method=>"get", -action =>$action) .3363"<div class=\"search\">\n".3364(!$use_pathinfo&&3365$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3366$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3367$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3368$cgi->popup_menu(-name =>'st', -default=>'commit',3369-values=> ['commit','grep','author','committer','pickaxe']) .3370$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3371" search:\n",3372$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3373"<span title=\"Extended regular expression\">".3374$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3375-checked =>$search_use_regexp) .3376"</span>".3377"</div>".3378$cgi->end_form() ."\n";3379}3380}33813382sub git_footer_html {3383my$feed_class='rss_logo';33843385print"<div class=\"page_footer\">\n";3386if(defined$project) {3387my$descr= git_get_project_description($project);3388if(defined$descr) {3389print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3390}33913392my%href_params= get_feed_info();3393if(!%href_params) {3394$feed_class.=' generic';3395}3396$href_params{'-title'} ||='log';33973398foreachmy$formatqw(RSS Atom){3399$href_params{'action'} =lc($format);3400print$cgi->a({-href => href(%href_params),3401-title =>"$href_params{'-title'}$formatfeed",3402-class=>$feed_class},$format)."\n";3403}34043405}else{3406print$cgi->a({-href => href(project=>undef, action=>"opml"),3407-class=>$feed_class},"OPML") ." ";3408print$cgi->a({-href => href(project=>undef, action=>"project_index"),3409-class=>$feed_class},"TXT") ."\n";3410}3411print"</div>\n";# class="page_footer"34123413if(defined$t0&& gitweb_check_feature('timed')) {3414print"<div id=\"generating_info\">\n";3415print'This page took '.3416'<span id="generating_time" class="time_span">'.3417 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).3418' seconds </span>'.3419' and '.3420'<span id="generating_cmd">'.3421$number_of_git_cmds.3422'</span> git commands '.3423" to generate.\n";3424print"</div>\n";# class="page_footer"3425}34263427if(defined$site_footer&& -f $site_footer) {3428 insert_file($site_footer);3429}34303431print qq!<script type="text/javascript" src="$javascript"></script>\n!;3432if(defined$action&&3433$actioneq'blame_incremental') {3434print qq!<script type="text/javascript">\n!.3435 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.3436 qq!"!. href() .qq!");\n!.3437 qq!</script>\n!;3438}elsif(gitweb_check_feature('javascript-actions')) {3439print qq!<script type="text/javascript">\n!.3440 qq!window.onload = fixLinks;\n!.3441 qq!</script>\n!;3442}34433444print"</body>\n".3445"</html>";3446}34473448# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])3449# Example: die_error(404, 'Hash not found')3450# By convention, use the following status codes (as defined in RFC 2616):3451# 400: Invalid or missing CGI parameters, or3452# requested object exists but has wrong type.3453# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3454# this server or project.3455# 404: Requested object/revision/project doesn't exist.3456# 500: The server isn't configured properly, or3457# an internal error occurred (e.g. failed assertions caused by bugs), or3458# an unknown error occurred (e.g. the git binary died unexpectedly).3459# 503: The server is currently unavailable (because it is overloaded,3460# or down for maintenance). Generally, this is a temporary state.3461sub die_error {3462my$status=shift||500;3463my$error= esc_html(shift) ||"Internal Server Error";3464my$extra=shift;34653466my%http_responses= (3467400=>'400 Bad Request',3468403=>'403 Forbidden',3469404=>'404 Not Found',3470500=>'500 Internal Server Error',3471503=>'503 Service Unavailable',3472);3473 git_header_html($http_responses{$status});3474print<<EOF;3475<div class="page_body">3476<br /><br />3477$status-$error3478<br />3479EOF3480if(defined$extra) {3481print"<hr />\n".3482"$extra\n";3483}3484print"</div>\n";34853486 git_footer_html();3487goto DONE_GITWEB;3488}34893490## ----------------------------------------------------------------------3491## functions printing or outputting HTML: navigation34923493sub git_print_page_nav {3494my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;3495$extra=''if!defined$extra;# pager or formats34963497my@navs=qw(summary shortlog log commit commitdiff tree);3498if($suppress) {3499@navs=grep{$_ne$suppress}@navs;3500}35013502my%arg=map{$_=> {action=>$_} }@navs;3503if(defined$head) {3504for(qw(commit commitdiff)) {3505$arg{$_}{'hash'} =$head;3506}3507if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {3508for(qw(shortlog log)) {3509$arg{$_}{'hash'} =$head;3510}3511}3512}35133514$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;3515$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;35163517my@actions= gitweb_get_feature('actions');3518my%repl= (3519'%'=>'%',3520'n'=>$project,# project name3521'f'=>$git_dir,# project path within filesystem3522'h'=>$treehead||'',# current hash ('h' parameter)3523'b'=>$treebase||'',# hash base ('hb' parameter)3524);3525while(@actions) {3526my($label,$link,$pos) =splice(@actions,0,3);3527# insert3528@navs=map{$_eq$pos? ($_,$label) :$_}@navs;3529# munch munch3530$link=~s/%([%nfhb])/$repl{$1}/g;3531$arg{$label}{'_href'} =$link;3532}35333534print"<div class=\"page_nav\">\n".3535(join" | ",3536map{$_eq$current?3537$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")3538}@navs);3539print"<br/>\n$extra<br/>\n".3540"</div>\n";3541}35423543sub format_paging_nav {3544my($action,$page,$has_next_link) =@_;3545my$paging_nav;354635473548if($page>0) {3549$paging_nav.=3550$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .3551" ⋅ ".3552$cgi->a({-href => href(-replay=>1, page=>$page-1),3553-accesskey =>"p", -title =>"Alt-p"},"prev");3554}else{3555$paging_nav.="first ⋅ prev";3556}35573558if($has_next_link) {3559$paging_nav.=" ⋅ ".3560$cgi->a({-href => href(-replay=>1, page=>$page+1),3561-accesskey =>"n", -title =>"Alt-n"},"next");3562}else{3563$paging_nav.=" ⋅ next";3564}35653566return$paging_nav;3567}35683569## ......................................................................3570## functions printing or outputting HTML: div35713572sub git_print_header_div {3573my($action,$title,$hash,$hash_base) =@_;3574my%args= ();35753576$args{'action'} =$action;3577$args{'hash'} =$hashif$hash;3578$args{'hash_base'} =$hash_baseif$hash_base;35793580print"<div class=\"header\">\n".3581$cgi->a({-href => href(%args), -class=>"title"},3582$title?$title:$action) .3583"\n</div>\n";3584}35853586sub print_local_time {3587print format_local_time(@_);3588}35893590sub format_local_time {3591my$localtime='';3592my%date=@_;3593if($date{'hour_local'} <6) {3594$localtime.=sprintf(" (<span class=\"atnight\">%02d:%02d</span>%s)",3595$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});3596}else{3597$localtime.=sprintf(" (%02d:%02d%s)",3598$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});3599}36003601return$localtime;3602}36033604# Outputs the author name and date in long form3605sub git_print_authorship {3606my$co=shift;3607my%opts=@_;3608my$tag=$opts{-tag} ||'div';3609my$author=$co->{'author_name'};36103611my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});3612print"<$tagclass=\"author_date\">".3613 format_search_author($author,"author", esc_html($author)) .3614" [$ad{'rfc2822'}";3615 print_local_time(%ad)if($opts{-localtime});3616print"]". git_get_avatar($co->{'author_email'}, -pad_before =>1)3617."</$tag>\n";3618}36193620# Outputs table rows containing the full author or committer information,3621# in the format expected for 'commit' view (& similia).3622# Parameters are a commit hash reference, followed by the list of people3623# to output information for. If the list is empty it defalts to both3624# author and committer.3625sub git_print_authorship_rows {3626my$co=shift;3627# too bad we can't use @people = @_ || ('author', 'committer')3628my@people=@_;3629@people= ('author','committer')unless@people;3630foreachmy$who(@people) {3631my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});3632print"<tr><td>$who</td><td>".3633 format_search_author($co->{"${who}_name"},$who,3634 esc_html($co->{"${who}_name"})) ." ".3635 format_search_author($co->{"${who}_email"},$who,3636 esc_html("<".$co->{"${who}_email"} .">")) .3637"</td><td rowspan=\"2\">".3638 git_get_avatar($co->{"${who}_email"}, -size =>'double') .3639"</td></tr>\n".3640"<tr>".3641"<td></td><td>$wd{'rfc2822'}";3642 print_local_time(%wd);3643print"</td>".3644"</tr>\n";3645}3646}36473648sub git_print_page_path {3649my$name=shift;3650my$type=shift;3651my$hb=shift;365236533654print"<div class=\"page_path\">";3655print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),3656-title =>'tree root'}, to_utf8("[$project]"));3657print" / ";3658if(defined$name) {3659my@dirname=split'/',$name;3660my$basename=pop@dirname;3661my$fullname='';36623663foreachmy$dir(@dirname) {3664$fullname.= ($fullname?'/':'') .$dir;3665print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,3666 hash_base=>$hb),3667-title =>$fullname}, esc_path($dir));3668print" / ";3669}3670if(defined$type&&$typeeq'blob') {3671print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,3672 hash_base=>$hb),3673-title =>$name}, esc_path($basename));3674}elsif(defined$type&&$typeeq'tree') {3675print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,3676 hash_base=>$hb),3677-title =>$name}, esc_path($basename));3678print" / ";3679}else{3680print esc_path($basename);3681}3682}3683print"<br/></div>\n";3684}36853686sub git_print_log {3687my$log=shift;3688my%opts=@_;36893690if($opts{'-remove_title'}) {3691# remove title, i.e. first line of log3692shift@$log;3693}3694# remove leading empty lines3695while(defined$log->[0] &&$log->[0]eq"") {3696shift@$log;3697}36983699# print log3700my$signoff=0;3701my$empty=0;3702foreachmy$line(@$log) {3703if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {3704$signoff=1;3705$empty=0;3706if(!$opts{'-remove_signoff'}) {3707print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";3708next;3709}else{3710# remove signoff lines3711next;3712}3713}else{3714$signoff=0;3715}37163717# print only one empty line3718# do not print empty line after signoff3719if($lineeq"") {3720next if($empty||$signoff);3721$empty=1;3722}else{3723$empty=0;3724}37253726print format_log_line_html($line) ."<br/>\n";3727}37283729if($opts{'-final_empty_line'}) {3730# end with single empty line3731print"<br/>\n"unless$empty;3732}3733}37343735# return link target (what link points to)3736sub git_get_link_target {3737my$hash=shift;3738my$link_target;37393740# read link3741open my$fd,"-|", git_cmd(),"cat-file","blob",$hash3742orreturn;3743{3744local$/=undef;3745$link_target= <$fd>;3746}3747close$fd3748orreturn;37493750return$link_target;3751}37523753# given link target, and the directory (basedir) the link is in,3754# return target of link relative to top directory (top tree);3755# return undef if it is not possible (including absolute links).3756sub normalize_link_target {3757my($link_target,$basedir) =@_;37583759# absolute symlinks (beginning with '/') cannot be normalized3760return if(substr($link_target,0,1)eq'/');37613762# normalize link target to path from top (root) tree (dir)3763my$path;3764if($basedir) {3765$path=$basedir.'/'.$link_target;3766}else{3767# we are in top (root) tree (dir)3768$path=$link_target;3769}37703771# remove //, /./, and /../3772my@path_parts;3773foreachmy$part(split('/',$path)) {3774# discard '.' and ''3775next if(!$part||$parteq'.');3776# handle '..'3777if($parteq'..') {3778if(@path_parts) {3779pop@path_parts;3780}else{3781# link leads outside repository (outside top dir)3782return;3783}3784}else{3785push@path_parts,$part;3786}3787}3788$path=join('/',@path_parts);37893790return$path;3791}37923793# print tree entry (row of git_tree), but without encompassing <tr> element3794sub git_print_tree_entry {3795my($t,$basedir,$hash_base,$have_blame) =@_;37963797my%base_key= ();3798$base_key{'hash_base'} =$hash_baseifdefined$hash_base;37993800# The format of a table row is: mode list link. Where mode is3801# the mode of the entry, list is the name of the entry, an href,3802# and link is the action links of the entry.38033804print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";3805if(exists$t->{'size'}) {3806print"<td class=\"size\">$t->{'size'}</td>\n";3807}3808if($t->{'type'}eq"blob") {3809print"<td class=\"list\">".3810$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},3811 file_name=>"$basedir$t->{'name'}",%base_key),3812-class=>"list"}, esc_path($t->{'name'}));3813if(S_ISLNK(oct$t->{'mode'})) {3814my$link_target= git_get_link_target($t->{'hash'});3815if($link_target) {3816my$norm_target= normalize_link_target($link_target,$basedir);3817if(defined$norm_target) {3818print" -> ".3819$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,3820 file_name=>$norm_target),3821-title =>$norm_target}, esc_path($link_target));3822}else{3823print" -> ". esc_path($link_target);3824}3825}3826}3827print"</td>\n";3828print"<td class=\"link\">";3829print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},3830 file_name=>"$basedir$t->{'name'}",%base_key)},3831"blob");3832if($have_blame) {3833print" | ".3834$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},3835 file_name=>"$basedir$t->{'name'}",%base_key)},3836"blame");3837}3838if(defined$hash_base) {3839print" | ".3840$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,3841 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},3842"history");3843}3844print" | ".3845$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,3846 file_name=>"$basedir$t->{'name'}")},3847"raw");3848print"</td>\n";38493850}elsif($t->{'type'}eq"tree") {3851print"<td class=\"list\">";3852print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},3853 file_name=>"$basedir$t->{'name'}",3854%base_key)},3855 esc_path($t->{'name'}));3856print"</td>\n";3857print"<td class=\"link\">";3858print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},3859 file_name=>"$basedir$t->{'name'}",3860%base_key)},3861"tree");3862if(defined$hash_base) {3863print" | ".3864$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,3865 file_name=>"$basedir$t->{'name'}")},3866"history");3867}3868print"</td>\n";3869}else{3870# unknown object: we can only present history for it3871# (this includes 'commit' object, i.e. submodule support)3872print"<td class=\"list\">".3873 esc_path($t->{'name'}) .3874"</td>\n";3875print"<td class=\"link\">";3876if(defined$hash_base) {3877print$cgi->a({-href => href(action=>"history",3878 hash_base=>$hash_base,3879 file_name=>"$basedir$t->{'name'}")},3880"history");3881}3882print"</td>\n";3883}3884}38853886## ......................................................................3887## functions printing large fragments of HTML38883889# get pre-image filenames for merge (combined) diff3890sub fill_from_file_info {3891my($diff,@parents) =@_;38923893$diff->{'from_file'} = [ ];3894$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;3895for(my$i=0;$i<$diff->{'nparents'};$i++) {3896if($diff->{'status'}[$i]eq'R'||3897$diff->{'status'}[$i]eq'C') {3898$diff->{'from_file'}[$i] =3899 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);3900}3901}39023903return$diff;3904}39053906# is current raw difftree line of file deletion3907sub is_deleted {3908my$diffinfo=shift;39093910return$diffinfo->{'to_id'}eq('0' x 40);3911}39123913# does patch correspond to [previous] difftree raw line3914# $diffinfo - hashref of parsed raw diff format3915# $patchinfo - hashref of parsed patch diff format3916# (the same keys as in $diffinfo)3917sub is_patch_split {3918my($diffinfo,$patchinfo) =@_;39193920returndefined$diffinfo&&defined$patchinfo3921&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};3922}392339243925sub git_difftree_body {3926my($difftree,$hash,@parents) =@_;3927my($parent) =$parents[0];3928my$have_blame= gitweb_check_feature('blame');3929print"<div class=\"list_head\">\n";3930if($#{$difftree} >10) {3931print(($#{$difftree} +1) ." files changed:\n");3932}3933print"</div>\n";39343935print"<table class=\"".3936(@parents>1?"combined ":"") .3937"diff_tree\">\n";39383939# header only for combined diff in 'commitdiff' view3940my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';3941if($has_header) {3942# table header3943print"<thead><tr>\n".3944"<th></th><th></th>\n";# filename, patchN link3945for(my$i=0;$i<@parents;$i++) {3946my$par=$parents[$i];3947print"<th>".3948$cgi->a({-href => href(action=>"commitdiff",3949 hash=>$hash, hash_parent=>$par),3950-title =>'commitdiff to parent number '.3951($i+1) .': '.substr($par,0,7)},3952$i+1) .3953" </th>\n";3954}3955print"</tr></thead>\n<tbody>\n";3956}39573958my$alternate=1;3959my$patchno=0;3960foreachmy$line(@{$difftree}) {3961my$diff= parsed_difftree_line($line);39623963if($alternate) {3964print"<tr class=\"dark\">\n";3965}else{3966print"<tr class=\"light\">\n";3967}3968$alternate^=1;39693970if(exists$diff->{'nparents'}) {# combined diff39713972 fill_from_file_info($diff,@parents)3973unlessexists$diff->{'from_file'};39743975if(!is_deleted($diff)) {3976# file exists in the result (child) commit3977print"<td>".3978$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},3979 file_name=>$diff->{'to_file'},3980 hash_base=>$hash),3981-class=>"list"}, esc_path($diff->{'to_file'})) .3982"</td>\n";3983}else{3984print"<td>".3985 esc_path($diff->{'to_file'}) .3986"</td>\n";3987}39883989if($actioneq'commitdiff') {3990# link to patch3991$patchno++;3992print"<td class=\"link\">".3993$cgi->a({-href =>"#patch$patchno"},"patch") .3994" | ".3995"</td>\n";3996}39973998my$has_history=0;3999my$not_deleted=0;4000for(my$i=0;$i<$diff->{'nparents'};$i++) {4001my$hash_parent=$parents[$i];4002my$from_hash=$diff->{'from_id'}[$i];4003my$from_path=$diff->{'from_file'}[$i];4004my$status=$diff->{'status'}[$i];40054006$has_history||= ($statusne'A');4007$not_deleted||= ($statusne'D');40084009if($statuseq'A') {4010print"<td class=\"link\"align=\"right\"> | </td>\n";4011}elsif($statuseq'D') {4012print"<td class=\"link\">".4013$cgi->a({-href => href(action=>"blob",4014 hash_base=>$hash,4015 hash=>$from_hash,4016 file_name=>$from_path)},4017"blob". ($i+1)) .4018" | </td>\n";4019}else{4020if($diff->{'to_id'}eq$from_hash) {4021print"<td class=\"link nochange\">";4022}else{4023print"<td class=\"link\">";4024}4025print$cgi->a({-href => href(action=>"blobdiff",4026 hash=>$diff->{'to_id'},4027 hash_parent=>$from_hash,4028 hash_base=>$hash,4029 hash_parent_base=>$hash_parent,4030 file_name=>$diff->{'to_file'},4031 file_parent=>$from_path)},4032"diff". ($i+1)) .4033" | </td>\n";4034}4035}40364037print"<td class=\"link\">";4038if($not_deleted) {4039print$cgi->a({-href => href(action=>"blob",4040 hash=>$diff->{'to_id'},4041 file_name=>$diff->{'to_file'},4042 hash_base=>$hash)},4043"blob");4044print" | "if($has_history);4045}4046if($has_history) {4047print$cgi->a({-href => href(action=>"history",4048 file_name=>$diff->{'to_file'},4049 hash_base=>$hash)},4050"history");4051}4052print"</td>\n";40534054print"</tr>\n";4055next;# instead of 'else' clause, to avoid extra indent4056}4057# else ordinary diff40584059my($to_mode_oct,$to_mode_str,$to_file_type);4060my($from_mode_oct,$from_mode_str,$from_file_type);4061if($diff->{'to_mode'}ne('0' x 6)) {4062$to_mode_oct=oct$diff->{'to_mode'};4063if(S_ISREG($to_mode_oct)) {# only for regular file4064$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4065}4066$to_file_type= file_type($diff->{'to_mode'});4067}4068if($diff->{'from_mode'}ne('0' x 6)) {4069$from_mode_oct=oct$diff->{'from_mode'};4070if(S_ISREG($to_mode_oct)) {# only for regular file4071$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4072}4073$from_file_type= file_type($diff->{'from_mode'});4074}40754076if($diff->{'status'}eq"A") {# created4077my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4078$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4079$mode_chng.="]</span>";4080print"<td>";4081print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4082 hash_base=>$hash, file_name=>$diff->{'file'}),4083-class=>"list"}, esc_path($diff->{'file'}));4084print"</td>\n";4085print"<td>$mode_chng</td>\n";4086print"<td class=\"link\">";4087if($actioneq'commitdiff') {4088# link to patch4089$patchno++;4090print$cgi->a({-href =>"#patch$patchno"},"patch");4091print" | ";4092}4093print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4094 hash_base=>$hash, file_name=>$diff->{'file'})},4095"blob");4096print"</td>\n";40974098}elsif($diff->{'status'}eq"D") {# deleted4099my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4100print"<td>";4101print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4102 hash_base=>$parent, file_name=>$diff->{'file'}),4103-class=>"list"}, esc_path($diff->{'file'}));4104print"</td>\n";4105print"<td>$mode_chng</td>\n";4106print"<td class=\"link\">";4107if($actioneq'commitdiff') {4108# link to patch4109$patchno++;4110print$cgi->a({-href =>"#patch$patchno"},"patch");4111print" | ";4112}4113print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4114 hash_base=>$parent, file_name=>$diff->{'file'})},4115"blob") ." | ";4116if($have_blame) {4117print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4118 file_name=>$diff->{'file'})},4119"blame") ." | ";4120}4121print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4122 file_name=>$diff->{'file'})},4123"history");4124print"</td>\n";41254126}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4127my$mode_chnge="";4128if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4129$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4130if($from_file_typene$to_file_type) {4131$mode_chnge.=" from$from_file_typeto$to_file_type";4132}4133if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4134if($from_mode_str&&$to_mode_str) {4135$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4136}elsif($to_mode_str) {4137$mode_chnge.=" mode:$to_mode_str";4138}4139}4140$mode_chnge.="]</span>\n";4141}4142print"<td>";4143print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4144 hash_base=>$hash, file_name=>$diff->{'file'}),4145-class=>"list"}, esc_path($diff->{'file'}));4146print"</td>\n";4147print"<td>$mode_chnge</td>\n";4148print"<td class=\"link\">";4149if($actioneq'commitdiff') {4150# link to patch4151$patchno++;4152print$cgi->a({-href =>"#patch$patchno"},"patch") .4153" | ";4154}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4155# "commit" view and modified file (not onlu mode changed)4156print$cgi->a({-href => href(action=>"blobdiff",4157 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4158 hash_base=>$hash, hash_parent_base=>$parent,4159 file_name=>$diff->{'file'})},4160"diff") .4161" | ";4162}4163print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4164 hash_base=>$hash, file_name=>$diff->{'file'})},4165"blob") ." | ";4166if($have_blame) {4167print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4168 file_name=>$diff->{'file'})},4169"blame") ." | ";4170}4171print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4172 file_name=>$diff->{'file'})},4173"history");4174print"</td>\n";41754176}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4177my%status_name= ('R'=>'moved','C'=>'copied');4178my$nstatus=$status_name{$diff->{'status'}};4179my$mode_chng="";4180if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4181# mode also for directories, so we cannot use $to_mode_str4182$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4183}4184print"<td>".4185$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4186 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4187-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4188"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4189$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4190 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4191-class=>"list"}, esc_path($diff->{'from_file'})) .4192" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4193"<td class=\"link\">";4194if($actioneq'commitdiff') {4195# link to patch4196$patchno++;4197print$cgi->a({-href =>"#patch$patchno"},"patch") .4198" | ";4199}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4200# "commit" view and modified file (not only pure rename or copy)4201print$cgi->a({-href => href(action=>"blobdiff",4202 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4203 hash_base=>$hash, hash_parent_base=>$parent,4204 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4205"diff") .4206" | ";4207}4208print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4209 hash_base=>$parent, file_name=>$diff->{'to_file'})},4210"blob") ." | ";4211if($have_blame) {4212print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4213 file_name=>$diff->{'to_file'})},4214"blame") ." | ";4215}4216print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4217 file_name=>$diff->{'to_file'})},4218"history");4219print"</td>\n";42204221}# we should not encounter Unmerged (U) or Unknown (X) status4222print"</tr>\n";4223}4224print"</tbody>"if$has_header;4225print"</table>\n";4226}42274228sub git_patchset_body {4229my($fd,$difftree,$hash,@hash_parents) =@_;4230my($hash_parent) =$hash_parents[0];42314232my$is_combined= (@hash_parents>1);4233my$patch_idx=0;4234my$patch_number=0;4235my$patch_line;4236my$diffinfo;4237my$to_name;4238my(%from,%to);42394240print"<div class=\"patchset\">\n";42414242# skip to first patch4243while($patch_line= <$fd>) {4244chomp$patch_line;42454246last if($patch_line=~m/^diff /);4247}42484249 PATCH:4250while($patch_line) {42514252# parse "git diff" header line4253if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4254# $1 is from_name, which we do not use4255$to_name= unquote($2);4256$to_name=~s!^b/!!;4257}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4258# $1 is 'cc' or 'combined', which we do not use4259$to_name= unquote($2);4260}else{4261$to_name=undef;4262}42634264# check if current patch belong to current raw line4265# and parse raw git-diff line if needed4266if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4267# this is continuation of a split patch4268print"<div class=\"patch cont\">\n";4269}else{4270# advance raw git-diff output if needed4271$patch_idx++ifdefined$diffinfo;42724273# read and prepare patch information4274$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);42754276# compact combined diff output can have some patches skipped4277# find which patch (using pathname of result) we are at now;4278if($is_combined) {4279while($to_namene$diffinfo->{'to_file'}) {4280print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4281 format_diff_cc_simplified($diffinfo,@hash_parents) .4282"</div>\n";# class="patch"42834284$patch_idx++;4285$patch_number++;42864287last if$patch_idx>$#$difftree;4288$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4289}4290}42914292# modifies %from, %to hashes4293 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);42944295# this is first patch for raw difftree line with $patch_idx index4296# we index @$difftree array from 0, but number patches from 14297print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4298}42994300# git diff header4301#assert($patch_line =~ m/^diff /) if DEBUG;4302#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4303$patch_number++;4304# print "git diff" header4305print format_git_diff_header_line($patch_line,$diffinfo,4306 \%from, \%to);43074308# print extended diff header4309print"<div class=\"diff extended_header\">\n";4310 EXTENDED_HEADER:4311while($patch_line= <$fd>) {4312chomp$patch_line;43134314last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);43154316print format_extended_diff_header_line($patch_line,$diffinfo,4317 \%from, \%to);4318}4319print"</div>\n";# class="diff extended_header"43204321# from-file/to-file diff header4322if(!$patch_line) {4323print"</div>\n";# class="patch"4324last PATCH;4325}4326next PATCH if($patch_line=~m/^diff /);4327#assert($patch_line =~ m/^---/) if DEBUG;43284329my$last_patch_line=$patch_line;4330$patch_line= <$fd>;4331chomp$patch_line;4332#assert($patch_line =~ m/^\+\+\+/) if DEBUG;43334334print format_diff_from_to_header($last_patch_line,$patch_line,4335$diffinfo, \%from, \%to,4336@hash_parents);43374338# the patch itself4339 LINE:4340while($patch_line= <$fd>) {4341chomp$patch_line;43424343next PATCH if($patch_line=~m/^diff /);43444345print format_diff_line($patch_line, \%from, \%to);4346}43474348}continue{4349print"</div>\n";# class="patch"4350}43514352# for compact combined (--cc) format, with chunk and patch simpliciaction4353# patchset might be empty, but there might be unprocessed raw lines4354for(++$patch_idxif$patch_number>0;4355$patch_idx<@$difftree;4356++$patch_idx) {4357# read and prepare patch information4358$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);43594360# generate anchor for "patch" links in difftree / whatchanged part4361print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4362 format_diff_cc_simplified($diffinfo,@hash_parents) .4363"</div>\n";# class="patch"43644365$patch_number++;4366}43674368if($patch_number==0) {4369if(@hash_parents>1) {4370print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4371}else{4372print"<div class=\"diff nodifferences\">No differences found</div>\n";4373}4374}43754376print"</div>\n";# class="patchset"4377}43784379# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .43804381# fills project list info (age, description, owner, forks) for each4382# project in the list, removing invalid projects from returned list4383# NOTE: modifies $projlist, but does not remove entries from it4384sub fill_project_list_info {4385my($projlist,$check_forks) =@_;4386my@projects;43874388my$show_ctags= gitweb_check_feature('ctags');4389 PROJECT:4390foreachmy$pr(@$projlist) {4391my(@activity) = git_get_last_activity($pr->{'path'});4392unless(@activity) {4393next PROJECT;4394}4395($pr->{'age'},$pr->{'age_string'}) =@activity;4396if(!defined$pr->{'descr'}) {4397my$descr= git_get_project_description($pr->{'path'}) ||"";4398$descr= to_utf8($descr);4399$pr->{'descr_long'} =$descr;4400$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);4401}4402if(!defined$pr->{'owner'}) {4403$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";4404}4405if($check_forks) {4406my$pname=$pr->{'path'};4407if(($pname=~s/\.git$//) &&4408($pname!~/\/$/) &&4409(-d "$projectroot/$pname")) {4410$pr->{'forks'} ="-d$projectroot/$pname";4411}else{4412$pr->{'forks'} =0;4413}4414}4415$show_ctagsand$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});4416push@projects,$pr;4417}44184419return@projects;4420}44214422# print 'sort by' <th> element, generating 'sort by $name' replay link4423# if that order is not selected4424sub print_sort_th {4425print format_sort_th(@_);4426}44274428sub format_sort_th {4429my($name,$order,$header) =@_;4430my$sort_th="";4431$header||=ucfirst($name);44324433if($ordereq$name) {4434$sort_th.="<th>$header</th>\n";4435}else{4436$sort_th.="<th>".4437$cgi->a({-href => href(-replay=>1, order=>$name),4438-class=>"header"},$header) .4439"</th>\n";4440}44414442return$sort_th;4443}44444445sub git_project_list_body {4446# actually uses global variable $project4447my($projlist,$order,$from,$to,$extra,$no_header) =@_;44484449my$check_forks= gitweb_check_feature('forks');4450my@projects= fill_project_list_info($projlist,$check_forks);44514452$order||=$default_projects_order;4453$from=0unlessdefined$from;4454$to=$#projectsif(!defined$to||$#projects<$to);44554456my%order_info= (4457 project => { key =>'path', type =>'str'},4458 descr => { key =>'descr_long', type =>'str'},4459 owner => { key =>'owner', type =>'str'},4460 age => { key =>'age', type =>'num'}4461);4462my$oi=$order_info{$order};4463if($oi->{'type'}eq'str') {4464@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@projects;4465}else{4466@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@projects;4467}44684469my$show_ctags= gitweb_check_feature('ctags');4470if($show_ctags) {4471my%ctags;4472foreachmy$p(@projects) {4473foreachmy$ct(keys%{$p->{'ctags'}}) {4474$ctags{$ct} +=$p->{'ctags'}->{$ct};4475}4476}4477my$cloud= git_populate_project_tagcloud(\%ctags);4478print git_show_project_tagcloud($cloud,64);4479}44804481print"<table class=\"project_list\">\n";4482unless($no_header) {4483print"<tr>\n";4484if($check_forks) {4485print"<th></th>\n";4486}4487 print_sort_th('project',$order,'Project');4488 print_sort_th('descr',$order,'Description');4489 print_sort_th('owner',$order,'Owner');4490 print_sort_th('age',$order,'Last Change');4491print"<th></th>\n".# for links4492"</tr>\n";4493}4494my$alternate=1;4495my$tagfilter=$cgi->param('by_tag');4496for(my$i=$from;$i<=$to;$i++) {4497my$pr=$projects[$i];44984499next if$tagfilterand$show_ctagsand not grep{lc$_eq lc$tagfilter}keys%{$pr->{'ctags'}};4500next if$searchtextand not$pr->{'path'} =~/$searchtext/4501and not$pr->{'descr_long'} =~/$searchtext/;4502# Weed out forks or non-matching entries of search4503if($check_forks) {4504my$forkbase=$project;$forkbase||='';$forkbase=~ s#\.git$#/#;4505$forkbase="^$forkbase"if$forkbase;4506next ifnot$searchtextand not$tagfilterand$show_ctags4507and$pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe4508}45094510if($alternate) {4511print"<tr class=\"dark\">\n";4512}else{4513print"<tr class=\"light\">\n";4514}4515$alternate^=1;4516if($check_forks) {4517print"<td>";4518if($pr->{'forks'}) {4519print"<!--$pr->{'forks'} -->\n";4520print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"+");4521}4522print"</td>\n";4523}4524print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),4525-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".4526"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),4527-class=>"list", -title =>$pr->{'descr_long'}},4528 esc_html($pr->{'descr'})) ."</td>\n".4529"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";4530print"<td class=\"". age_class($pr->{'age'}) ."\">".4531(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".4532"<td class=\"link\">".4533$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".4534$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".4535$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".4536$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .4537($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .4538"</td>\n".4539"</tr>\n";4540}4541if(defined$extra) {4542print"<tr>\n";4543if($check_forks) {4544print"<td></td>\n";4545}4546print"<td colspan=\"5\">$extra</td>\n".4547"</tr>\n";4548}4549print"</table>\n";4550}45514552sub git_log_body {4553# uses global variable $project4554my($commitlist,$from,$to,$refs,$extra) =@_;45554556$from=0unlessdefined$from;4557$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);45584559for(my$i=0;$i<=$to;$i++) {4560my%co= %{$commitlist->[$i]};4561next if!%co;4562my$commit=$co{'id'};4563my$ref= format_ref_marker($refs,$commit);4564my%ad= parse_date($co{'author_epoch'});4565 git_print_header_div('commit',4566"<span class=\"age\">$co{'age_string'}</span>".4567 esc_html($co{'title'}) .$ref,4568$commit);4569print"<div class=\"title_text\">\n".4570"<div class=\"log_link\">\n".4571$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .4572" | ".4573$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .4574" | ".4575$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .4576"<br/>\n".4577"</div>\n";4578 git_print_authorship(\%co, -tag =>'span');4579print"<br/>\n</div>\n";45804581print"<div class=\"log_body\">\n";4582 git_print_log($co{'comment'}, -final_empty_line=>1);4583print"</div>\n";4584}4585if($extra) {4586print"<div class=\"page_nav\">\n";4587print"$extra\n";4588print"</div>\n";4589}4590}45914592sub git_shortlog_body {4593# uses global variable $project4594my($commitlist,$from,$to,$refs,$extra) =@_;45954596$from=0unlessdefined$from;4597$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);45984599print"<table class=\"shortlog\">\n";4600my$alternate=1;4601for(my$i=$from;$i<=$to;$i++) {4602my%co= %{$commitlist->[$i]};4603my$commit=$co{'id'};4604my$ref= format_ref_marker($refs,$commit);4605if($alternate) {4606print"<tr class=\"dark\">\n";4607}else{4608print"<tr class=\"light\">\n";4609}4610$alternate^=1;4611# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .4612print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4613 format_author_html('td', \%co,10) ."<td>";4614print format_subject_html($co{'title'},$co{'title_short'},4615 href(action=>"commit", hash=>$commit),$ref);4616print"</td>\n".4617"<td class=\"link\">".4618$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".4619$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".4620$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");4621my$snapshot_links= format_snapshot_links($commit);4622if(defined$snapshot_links) {4623print" | ".$snapshot_links;4624}4625print"</td>\n".4626"</tr>\n";4627}4628if(defined$extra) {4629print"<tr>\n".4630"<td colspan=\"4\">$extra</td>\n".4631"</tr>\n";4632}4633print"</table>\n";4634}46354636sub git_history_body {4637# Warning: assumes constant type (blob or tree) during history4638my($commitlist,$from,$to,$refs,$extra,4639$file_name,$file_hash,$ftype) =@_;46404641$from=0unlessdefined$from;4642$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});46434644print"<table class=\"history\">\n";4645my$alternate=1;4646for(my$i=$from;$i<=$to;$i++) {4647my%co= %{$commitlist->[$i]};4648if(!%co) {4649next;4650}4651my$commit=$co{'id'};46524653my$ref= format_ref_marker($refs,$commit);46544655if($alternate) {4656print"<tr class=\"dark\">\n";4657}else{4658print"<tr class=\"light\">\n";4659}4660$alternate^=1;4661print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4662# shortlog: format_author_html('td', \%co, 10)4663 format_author_html('td', \%co,15,3) ."<td>";4664# originally git_history used chop_str($co{'title'}, 50)4665print format_subject_html($co{'title'},$co{'title_short'},4666 href(action=>"commit", hash=>$commit),$ref);4667print"</td>\n".4668"<td class=\"link\">".4669$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".4670$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");46714672if($ftypeeq'blob') {4673my$blob_current=$file_hash;4674my$blob_parent= git_get_hash_by_path($commit,$file_name);4675if(defined$blob_current&&defined$blob_parent&&4676$blob_currentne$blob_parent) {4677print" | ".4678$cgi->a({-href => href(action=>"blobdiff",4679 hash=>$blob_current, hash_parent=>$blob_parent,4680 hash_base=>$hash_base, hash_parent_base=>$commit,4681 file_name=>$file_name)},4682"diff to current");4683}4684}4685print"</td>\n".4686"</tr>\n";4687}4688if(defined$extra) {4689print"<tr>\n".4690"<td colspan=\"4\">$extra</td>\n".4691"</tr>\n";4692}4693print"</table>\n";4694}46954696sub git_tags_body {4697# uses global variable $project4698my($taglist,$from,$to,$extra) =@_;4699$from=0unlessdefined$from;4700$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);47014702print"<table class=\"tags\">\n";4703my$alternate=1;4704for(my$i=$from;$i<=$to;$i++) {4705my$entry=$taglist->[$i];4706my%tag=%$entry;4707my$comment=$tag{'subject'};4708my$comment_short;4709if(defined$comment) {4710$comment_short= chop_str($comment,30,5);4711}4712if($alternate) {4713print"<tr class=\"dark\">\n";4714}else{4715print"<tr class=\"light\">\n";4716}4717$alternate^=1;4718if(defined$tag{'age'}) {4719print"<td><i>$tag{'age'}</i></td>\n";4720}else{4721print"<td></td>\n";4722}4723print"<td>".4724$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),4725-class=>"list name"}, esc_html($tag{'name'})) .4726"</td>\n".4727"<td>";4728if(defined$comment) {4729print format_subject_html($comment,$comment_short,4730 href(action=>"tag", hash=>$tag{'id'}));4731}4732print"</td>\n".4733"<td class=\"selflink\">";4734if($tag{'type'}eq"tag") {4735print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");4736}else{4737print" ";4738}4739print"</td>\n".4740"<td class=\"link\">"." | ".4741$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});4742if($tag{'reftype'}eq"commit") {4743print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .4744" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");4745}elsif($tag{'reftype'}eq"blob") {4746print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");4747}4748print"</td>\n".4749"</tr>";4750}4751if(defined$extra) {4752print"<tr>\n".4753"<td colspan=\"5\">$extra</td>\n".4754"</tr>\n";4755}4756print"</table>\n";4757}47584759sub git_heads_body {4760# uses global variable $project4761my($headlist,$head,$from,$to,$extra) =@_;4762$from=0unlessdefined$from;4763$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);47644765print"<table class=\"heads\">\n";4766my$alternate=1;4767for(my$i=$from;$i<=$to;$i++) {4768my$entry=$headlist->[$i];4769my%ref=%$entry;4770my$curr=$ref{'id'}eq$head;4771if($alternate) {4772print"<tr class=\"dark\">\n";4773}else{4774print"<tr class=\"light\">\n";4775}4776$alternate^=1;4777print"<td><i>$ref{'age'}</i></td>\n".4778($curr?"<td class=\"current_head\">":"<td>") .4779$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),4780-class=>"list name"},esc_html($ref{'name'})) .4781"</td>\n".4782"<td class=\"link\">".4783$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".4784$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".4785$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})},"tree") .4786"</td>\n".4787"</tr>";4788}4789if(defined$extra) {4790print"<tr>\n".4791"<td colspan=\"3\">$extra</td>\n".4792"</tr>\n";4793}4794print"</table>\n";4795}47964797sub git_search_grep_body {4798my($commitlist,$from,$to,$extra) =@_;4799$from=0unlessdefined$from;4800$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);48014802print"<table class=\"commit_search\">\n";4803my$alternate=1;4804for(my$i=$from;$i<=$to;$i++) {4805my%co= %{$commitlist->[$i]};4806if(!%co) {4807next;4808}4809my$commit=$co{'id'};4810if($alternate) {4811print"<tr class=\"dark\">\n";4812}else{4813print"<tr class=\"light\">\n";4814}4815$alternate^=1;4816print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4817 format_author_html('td', \%co,15,5) .4818"<td>".4819$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),4820-class=>"list subject"},4821 chop_and_escape_str($co{'title'},50) ."<br/>");4822my$comment=$co{'comment'};4823foreachmy$line(@$comment) {4824if($line=~m/^(.*?)($search_regexp)(.*)$/i) {4825my($lead,$match,$trail) = ($1,$2,$3);4826$match= chop_str($match,70,5,'center');4827my$contextlen=int((80-length($match))/2);4828$contextlen=30if($contextlen>30);4829$lead= chop_str($lead,$contextlen,10,'left');4830$trail= chop_str($trail,$contextlen,10,'right');48314832$lead= esc_html($lead);4833$match= esc_html($match);4834$trail= esc_html($trail);48354836print"$lead<span class=\"match\">$match</span>$trail<br />";4837}4838}4839print"</td>\n".4840"<td class=\"link\">".4841$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .4842" | ".4843$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .4844" | ".4845$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");4846print"</td>\n".4847"</tr>\n";4848}4849if(defined$extra) {4850print"<tr>\n".4851"<td colspan=\"3\">$extra</td>\n".4852"</tr>\n";4853}4854print"</table>\n";4855}48564857## ======================================================================4858## ======================================================================4859## actions48604861sub git_project_list {4862my$order=$input_params{'order'};4863if(defined$order&&$order!~m/none|project|descr|owner|age/) {4864 die_error(400,"Unknown order parameter");4865}48664867my@list= git_get_projects_list();4868if(!@list) {4869 die_error(404,"No projects found");4870}48714872 git_header_html();4873if(defined$home_text&& -f $home_text) {4874print"<div class=\"index_include\">\n";4875 insert_file($home_text);4876print"</div>\n";4877}4878print$cgi->startform(-method=>"get") .4879"<p class=\"projsearch\">Search:\n".4880$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".4881"</p>".4882$cgi->end_form() ."\n";4883 git_project_list_body(\@list,$order);4884 git_footer_html();4885}48864887sub git_forks {4888my$order=$input_params{'order'};4889if(defined$order&&$order!~m/none|project|descr|owner|age/) {4890 die_error(400,"Unknown order parameter");4891}48924893my@list= git_get_projects_list($project);4894if(!@list) {4895 die_error(404,"No forks found");4896}48974898 git_header_html();4899 git_print_page_nav('','');4900 git_print_header_div('summary',"$projectforks");4901 git_project_list_body(\@list,$order);4902 git_footer_html();4903}49044905sub git_project_index {4906my@projects= git_get_projects_list($project);49074908print$cgi->header(4909-type =>'text/plain',4910-charset =>'utf-8',4911-content_disposition =>'inline; filename="index.aux"');49124913foreachmy$pr(@projects) {4914if(!exists$pr->{'owner'}) {4915$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");4916}49174918my($path,$owner) = ($pr->{'path'},$pr->{'owner'});4919# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '4920$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;4921$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;4922$path=~s/ /\+/g;4923$owner=~s/ /\+/g;49244925print"$path$owner\n";4926}4927}49284929sub git_summary {4930my$descr= git_get_project_description($project) ||"none";4931my%co= parse_commit("HEAD");4932my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();4933my$head=$co{'id'};49344935my$owner= git_get_project_owner($project);49364937my$refs= git_get_references();4938# These get_*_list functions return one more to allow us to see if4939# there are more ...4940my@taglist= git_get_tags_list(16);4941my@headlist= git_get_heads_list(16);4942my@forklist;4943my$check_forks= gitweb_check_feature('forks');49444945if($check_forks) {4946@forklist= git_get_projects_list($project);4947}49484949 git_header_html();4950 git_print_page_nav('summary','',$head);49514952print"<div class=\"title\"> </div>\n";4953print"<table class=\"projects_list\">\n".4954"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".4955"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";4956if(defined$cd{'rfc2822'}) {4957print"<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";4958}49594960# use per project git URL list in $projectroot/$project/cloneurl4961# or make project git URL from git base URL and project name4962my$url_tag="URL";4963my@url_list= git_get_project_url_list($project);4964@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;4965foreachmy$git_url(@url_list) {4966next unless$git_url;4967print"<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";4968$url_tag="";4969}49704971# Tag cloud4972my$show_ctags= gitweb_check_feature('ctags');4973if($show_ctags) {4974my$ctags= git_get_project_ctags($project);4975my$cloud= git_populate_project_tagcloud($ctags);4976print"<tr id=\"metadata_ctags\"><td>Content tags:<br />";4977print"</td>\n<td>"unless%$ctags;4978print"<form action=\"$show_ctags\"method=\"post\"><input type=\"hidden\"name=\"p\"value=\"$project\"/>Add: <input type=\"text\"name=\"t\"size=\"8\"/></form>";4979print"</td>\n<td>"if%$ctags;4980print git_show_project_tagcloud($cloud,48);4981print"</td></tr>";4982}49834984print"</table>\n";49854986# If XSS prevention is on, we don't include README.html.4987# TODO: Allow a readme in some safe format.4988if(!$prevent_xss&& -s "$projectroot/$project/README.html") {4989print"<div class=\"title\">readme</div>\n".4990"<div class=\"readme\">\n";4991 insert_file("$projectroot/$project/README.html");4992print"\n</div>\n";# class="readme"4993}49944995# we need to request one more than 16 (0..15) to check if4996# those 16 are all4997my@commitlist=$head? parse_commits($head,17) : ();4998if(@commitlist) {4999 git_print_header_div('shortlog');5000 git_shortlog_body(\@commitlist,0,15,$refs,5001$#commitlist<=15?undef:5002$cgi->a({-href => href(action=>"shortlog")},"..."));5003}50045005if(@taglist) {5006 git_print_header_div('tags');5007 git_tags_body(\@taglist,0,15,5008$#taglist<=15?undef:5009$cgi->a({-href => href(action=>"tags")},"..."));5010}50115012if(@headlist) {5013 git_print_header_div('heads');5014 git_heads_body(\@headlist,$head,0,15,5015$#headlist<=15?undef:5016$cgi->a({-href => href(action=>"heads")},"..."));5017}50185019if(@forklist) {5020 git_print_header_div('forks');5021 git_project_list_body(\@forklist,'age',0,15,5022$#forklist<=15?undef:5023$cgi->a({-href => href(action=>"forks")},"..."),5024'no_header');5025}50265027 git_footer_html();5028}50295030sub git_tag {5031my$head= git_get_head_hash($project);5032 git_header_html();5033 git_print_page_nav('','',$head,undef,$head);5034my%tag= parse_tag($hash);50355036if(!%tag) {5037 die_error(404,"Unknown tag object");5038}50395040 git_print_header_div('commit', esc_html($tag{'name'}),$hash);5041print"<div class=\"title_text\">\n".5042"<table class=\"object_header\">\n".5043"<tr>\n".5044"<td>object</td>\n".5045"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5046$tag{'object'}) ."</td>\n".5047"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5048$tag{'type'}) ."</td>\n".5049"</tr>\n";5050if(defined($tag{'author'})) {5051 git_print_authorship_rows(\%tag,'author');5052}5053print"</table>\n\n".5054"</div>\n";5055print"<div class=\"page_body\">";5056my$comment=$tag{'comment'};5057foreachmy$line(@$comment) {5058chomp$line;5059print esc_html($line, -nbsp=>1) ."<br/>\n";5060}5061print"</div>\n";5062 git_footer_html();5063}50645065sub git_blame_common {5066my$format=shift||'porcelain';5067if($formateq'porcelain'&&$cgi->param('js')) {5068$format='incremental';5069$action='blame_incremental';# for page title etc5070}50715072# permissions5073 gitweb_check_feature('blame')5074or die_error(403,"Blame view not allowed");50755076# error checking5077 die_error(400,"No file name given")unless$file_name;5078$hash_base||= git_get_head_hash($project);5079 die_error(404,"Couldn't find base commit")unless$hash_base;5080my%co= parse_commit($hash_base)5081or die_error(404,"Commit not found");5082my$ftype="blob";5083if(!defined$hash) {5084$hash= git_get_hash_by_path($hash_base,$file_name,"blob")5085or die_error(404,"Error looking up file");5086}else{5087$ftype= git_get_type($hash);5088if($ftype!~"blob") {5089 die_error(400,"Object is not a blob");5090}5091}50925093my$fd;5094if($formateq'incremental') {5095# get file contents (as base)5096open$fd,"-|", git_cmd(),'cat-file','blob',$hash5097or die_error(500,"Open git-cat-file failed");5098}elsif($formateq'data') {5099# run git-blame --incremental5100open$fd,"-|", git_cmd(),"blame","--incremental",5101$hash_base,"--",$file_name5102or die_error(500,"Open git-blame --incremental failed");5103}else{5104# run git-blame --porcelain5105open$fd,"-|", git_cmd(),"blame",'-p',5106$hash_base,'--',$file_name5107or die_error(500,"Open git-blame --porcelain failed");5108}51095110# incremental blame data returns early5111if($formateq'data') {5112print$cgi->header(5113-type=>"text/plain", -charset =>"utf-8",5114-status=>"200 OK");5115local$| =1;# output autoflush5116printwhile<$fd>;5117close$fd5118or print"ERROR$!\n";51195120print'END';5121if(defined$t0&& gitweb_check_feature('timed')) {5122print' '.5123 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).5124' '.$number_of_git_cmds;5125}5126print"\n";51275128return;5129}51305131# page header5132 git_header_html();5133my$formats_nav=5134$cgi->a({-href => href(action=>"blob", -replay=>1)},5135"blob") .5136" | ";5137if($formateq'incremental') {5138$formats_nav.=5139$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},5140"blame") ." (non-incremental)";5141}else{5142$formats_nav.=5143$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},5144"blame") ." (incremental)";5145}5146$formats_nav.=5147" | ".5148$cgi->a({-href => href(action=>"history", -replay=>1)},5149"history") .5150" | ".5151$cgi->a({-href => href(action=>$action, file_name=>$file_name)},5152"HEAD");5153 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5154 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5155 git_print_page_path($file_name,$ftype,$hash_base);51565157# page body5158if($formateq'incremental') {5159print"<noscript>\n<div class=\"error\"><center><b>\n".5160"This page requires JavaScript to run.\nUse ".5161$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},5162'this page').5163" instead.\n".5164"</b></center></div>\n</noscript>\n";51655166print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;5167}51685169print qq!<div class="page_body">\n!;5170print qq!<div id="progress_info">.../ ...</div>\n!5171if($formateq'incremental');5172print qq!<table id="blame_table"class="blame" width="100%">\n!.5173#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.5174 qq!<thead>\n!.5175 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.5176 qq!</thead>\n!.5177 qq!<tbody>\n!;51785179my@rev_color=qw(light dark);5180my$num_colors=scalar(@rev_color);5181my$current_color=0;51825183if($formateq'incremental') {5184my$color_class=$rev_color[$current_color];51855186#contents of a file5187my$linenr=0;5188 LINE:5189while(my$line= <$fd>) {5190chomp$line;5191$linenr++;51925193print qq!<tr id="l$linenr"class="$color_class">!.5194 qq!<td class="sha1"><a href=""> </a></td>!.5195 qq!<td class="linenr">!.5196 qq!<a class="linenr" href="">$linenr</a></td>!;5197print qq!<td class="pre">! . esc_html($line) ."</td>\n";5198print qq!</tr>\n!;5199}52005201}else{# porcelain, i.e. ordinary blame5202my%metainfo= ();# saves information about commits52035204# blame data5205 LINE:5206while(my$line= <$fd>) {5207chomp$line;5208# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]5209# no <lines in group> for subsequent lines in group of lines5210my($full_rev,$orig_lineno,$lineno,$group_size) =5211($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);5212if(!exists$metainfo{$full_rev}) {5213$metainfo{$full_rev} = {'nprevious'=>0};5214}5215my$meta=$metainfo{$full_rev};5216my$data;5217while($data= <$fd>) {5218chomp$data;5219last if($data=~s/^\t//);# contents of line5220if($data=~/^(\S+)(?: (.*))?$/) {5221$meta->{$1} =$2unlessexists$meta->{$1};5222}5223if($data=~/^previous /) {5224$meta->{'nprevious'}++;5225}5226}5227my$short_rev=substr($full_rev,0,8);5228my$author=$meta->{'author'};5229my%date=5230 parse_date($meta->{'author-time'},$meta->{'author-tz'});5231my$date=$date{'iso-tz'};5232if($group_size) {5233$current_color= ($current_color+1) %$num_colors;5234}5235my$tr_class=$rev_color[$current_color];5236$tr_class.=' boundary'if(exists$meta->{'boundary'});5237$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);5238$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);5239print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";5240if($group_size) {5241print"<td class=\"sha1\"";5242print" title=\"". esc_html($author) .",$date\"";5243print" rowspan=\"$group_size\""if($group_size>1);5244print">";5245print$cgi->a({-href => href(action=>"commit",5246 hash=>$full_rev,5247 file_name=>$file_name)},5248 esc_html($short_rev));5249if($group_size>=2) {5250my@author_initials= ($author=~/\b([[:upper:]])\B/g);5251if(@author_initials) {5252print"<br />".5253 esc_html(join('',@author_initials));5254# or join('.', ...)5255}5256}5257print"</td>\n";5258}5259# 'previous' <sha1 of parent commit> <filename at commit>5260if(exists$meta->{'previous'} &&5261$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {5262$meta->{'parent'} =$1;5263$meta->{'file_parent'} = unquote($2);5264}5265my$linenr_commit=5266exists($meta->{'parent'}) ?5267$meta->{'parent'} :$full_rev;5268my$linenr_filename=5269exists($meta->{'file_parent'}) ?5270$meta->{'file_parent'} : unquote($meta->{'filename'});5271my$blamed= href(action =>'blame',5272 file_name =>$linenr_filename,5273 hash_base =>$linenr_commit);5274print"<td class=\"linenr\">";5275print$cgi->a({ -href =>"$blamed#l$orig_lineno",5276-class=>"linenr"},5277 esc_html($lineno));5278print"</td>";5279print"<td class=\"pre\">". esc_html($data) ."</td>\n";5280print"</tr>\n";5281}# end while52825283}52845285# footer5286print"</tbody>\n".5287"</table>\n";# class="blame"5288print"</div>\n";# class="blame_body"5289close$fd5290or print"Reading blob failed\n";52915292 git_footer_html();5293}52945295sub git_blame {5296 git_blame_common();5297}52985299sub git_blame_incremental {5300 git_blame_common('incremental');5301}53025303sub git_blame_data {5304 git_blame_common('data');5305}53065307sub git_tags {5308my$head= git_get_head_hash($project);5309 git_header_html();5310 git_print_page_nav('','',$head,undef,$head);5311 git_print_header_div('summary',$project);53125313my@tagslist= git_get_tags_list();5314if(@tagslist) {5315 git_tags_body(\@tagslist);5316}5317 git_footer_html();5318}53195320sub git_heads {5321my$head= git_get_head_hash($project);5322 git_header_html();5323 git_print_page_nav('','',$head,undef,$head);5324 git_print_header_div('summary',$project);53255326my@headslist= git_get_heads_list();5327if(@headslist) {5328 git_heads_body(\@headslist,$head);5329}5330 git_footer_html();5331}53325333sub git_blob_plain {5334my$type=shift;5335my$expires;53365337if(!defined$hash) {5338if(defined$file_name) {5339my$base=$hash_base|| git_get_head_hash($project);5340$hash= git_get_hash_by_path($base,$file_name,"blob")5341or die_error(404,"Cannot find file");5342}else{5343 die_error(400,"No file name defined");5344}5345}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {5346# blobs defined by non-textual hash id's can be cached5347$expires="+1d";5348}53495350open my$fd,"-|", git_cmd(),"cat-file","blob",$hash5351or die_error(500,"Open git-cat-file blob '$hash' failed");53525353# content-type (can include charset)5354$type= blob_contenttype($fd,$file_name,$type);53555356# "save as" filename, even when no $file_name is given5357my$save_as="$hash";5358if(defined$file_name) {5359$save_as=$file_name;5360}elsif($type=~m/^text\//) {5361$save_as.='.txt';5362}53635364# With XSS prevention on, blobs of all types except a few known safe5365# ones are served with "Content-Disposition: attachment" to make sure5366# they don't run in our security domain. For certain image types,5367# blob view writes an <img> tag referring to blob_plain view, and we5368# want to be sure not to break that by serving the image as an5369# attachment (though Firefox 3 doesn't seem to care).5370my$sandbox=$prevent_xss&&5371$type!~m!^(?:text/plain|image/(?:gif|png|jpeg))$!;53725373print$cgi->header(5374-type =>$type,5375-expires =>$expires,5376-content_disposition =>5377($sandbox?'attachment':'inline')5378.'; filename="'.$save_as.'"');5379local$/=undef;5380binmode STDOUT,':raw';5381print<$fd>;5382binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi5383close$fd;5384}53855386sub git_blob {5387my$expires;53885389if(!defined$hash) {5390if(defined$file_name) {5391my$base=$hash_base|| git_get_head_hash($project);5392$hash= git_get_hash_by_path($base,$file_name,"blob")5393or die_error(404,"Cannot find file");5394}else{5395 die_error(400,"No file name defined");5396}5397}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {5398# blobs defined by non-textual hash id's can be cached5399$expires="+1d";5400}54015402my$have_blame= gitweb_check_feature('blame');5403open my$fd,"-|", git_cmd(),"cat-file","blob",$hash5404or die_error(500,"Couldn't cat$file_name,$hash");5405my$mimetype= blob_mimetype($fd,$file_name);5406if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {5407close$fd;5408return git_blob_plain($mimetype);5409}5410# we can have blame only for text/* mimetype5411$have_blame&&= ($mimetype=~m!^text/!);54125413 git_header_html(undef,$expires);5414my$formats_nav='';5415if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5416if(defined$file_name) {5417if($have_blame) {5418$formats_nav.=5419$cgi->a({-href => href(action=>"blame", -replay=>1)},5420"blame") .5421" | ";5422}5423$formats_nav.=5424$cgi->a({-href => href(action=>"history", -replay=>1)},5425"history") .5426" | ".5427$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},5428"raw") .5429" | ".5430$cgi->a({-href => href(action=>"blob",5431 hash_base=>"HEAD", file_name=>$file_name)},5432"HEAD");5433}else{5434$formats_nav.=5435$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},5436"raw");5437}5438 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5439 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5440}else{5441print"<div class=\"page_nav\">\n".5442"<br/><br/></div>\n".5443"<div class=\"title\">$hash</div>\n";5444}5445 git_print_page_path($file_name,"blob",$hash_base);5446print"<div class=\"page_body\">\n";5447if($mimetype=~m!^image/!) {5448print qq!<img type="$mimetype"!;5449if($file_name) {5450print qq! alt="$file_name" title="$file_name"!;5451}5452print qq! src="! .5453 href(action=>"blob_plain", hash=>$hash,5454 hash_base=>$hash_base, file_name=>$file_name) .5455 qq!"/>\n!;5456}else{5457my$nr;5458while(my$line= <$fd>) {5459chomp$line;5460$nr++;5461$line= untabify($line);5462printf"<div class=\"pre\"><a id=\"l%i\"href=\"". href(-replay =>1)5463."#l%i\"class=\"linenr\">%4i</a>%s</div>\n",5464$nr,$nr,$nr, esc_html($line, -nbsp=>1);5465}5466}5467close$fd5468or print"Reading blob failed.\n";5469print"</div>";5470 git_footer_html();5471}54725473sub git_tree {5474if(!defined$hash_base) {5475$hash_base="HEAD";5476}5477if(!defined$hash) {5478if(defined$file_name) {5479$hash= git_get_hash_by_path($hash_base,$file_name,"tree");5480}else{5481$hash=$hash_base;5482}5483}5484 die_error(404,"No such tree")unlessdefined($hash);54855486my$show_sizes= gitweb_check_feature('show-sizes');5487my$have_blame= gitweb_check_feature('blame');54885489my@entries= ();5490{5491local$/="\0";5492open my$fd,"-|", git_cmd(),"ls-tree",'-z',5493($show_sizes?'-l': ()),@extra_options,$hash5494or die_error(500,"Open git-ls-tree failed");5495@entries=map{chomp;$_} <$fd>;5496close$fd5497or die_error(404,"Reading tree failed");5498}54995500my$refs= git_get_references();5501my$ref= format_ref_marker($refs,$hash_base);5502 git_header_html();5503my$basedir='';5504if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5505my@views_nav= ();5506if(defined$file_name) {5507push@views_nav,5508$cgi->a({-href => href(action=>"history", -replay=>1)},5509"history"),5510$cgi->a({-href => href(action=>"tree",5511 hash_base=>"HEAD", file_name=>$file_name)},5512"HEAD"),5513}5514my$snapshot_links= format_snapshot_links($hash);5515if(defined$snapshot_links) {5516# FIXME: Should be available when we have no hash base as well.5517push@views_nav,$snapshot_links;5518}5519 git_print_page_nav('tree','',$hash_base,undef,undef,5520join(' | ',@views_nav));5521 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);5522}else{5523undef$hash_base;5524print"<div class=\"page_nav\">\n";5525print"<br/><br/></div>\n";5526print"<div class=\"title\">$hash</div>\n";5527}5528if(defined$file_name) {5529$basedir=$file_name;5530if($basedirne''&&substr($basedir, -1)ne'/') {5531$basedir.='/';5532}5533 git_print_page_path($file_name,'tree',$hash_base);5534}5535print"<div class=\"page_body\">\n";5536print"<table class=\"tree\">\n";5537my$alternate=1;5538# '..' (top directory) link if possible5539if(defined$hash_base&&5540defined$file_name&&$file_name=~m![^/]+$!) {5541if($alternate) {5542print"<tr class=\"dark\">\n";5543}else{5544print"<tr class=\"light\">\n";5545}5546$alternate^=1;55475548my$up=$file_name;5549$up=~s!/?[^/]+$!!;5550undef$upunless$up;5551# based on git_print_tree_entry5552print'<td class="mode">'. mode_str('040000') ."</td>\n";5553print'<td class="size"> </td>'."\n"if$show_sizes;5554print'<td class="list">';5555print$cgi->a({-href => href(action=>"tree",5556 hash_base=>$hash_base,5557 file_name=>$up)},5558"..");5559print"</td>\n";5560print"<td class=\"link\"></td>\n";55615562print"</tr>\n";5563}5564foreachmy$line(@entries) {5565my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);55665567if($alternate) {5568print"<tr class=\"dark\">\n";5569}else{5570print"<tr class=\"light\">\n";5571}5572$alternate^=1;55735574 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);55755576print"</tr>\n";5577}5578print"</table>\n".5579"</div>";5580 git_footer_html();5581}55825583sub snapshot_name {5584my($project,$hash) =@_;55855586# path/to/project.git -> project5587# path/to/project/.git -> project5588my$name= to_utf8($project);5589$name=~ s,([^/])/*\.git$,$1,;5590$name= basename($name);5591# sanitize name5592$name=~s/[[:cntrl:]]/?/g;55935594my$ver=$hash;5595if($hash=~/^[0-9a-fA-F]+$/) {5596# shorten SHA-1 hash5597my$full_hash= git_get_full_hash($project,$hash);5598if($full_hash=~/^$hash/&&length($hash) >7) {5599$ver= git_get_short_hash($project,$hash);5600}5601}elsif($hash=~m!^refs/tags/(.*)$!) {5602# tags don't need shortened SHA-1 hash5603$ver=$1;5604}else{5605# branches and other need shortened SHA-1 hash5606if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {5607$ver=$1;5608}5609$ver.='-'. git_get_short_hash($project,$hash);5610}5611# in case of hierarchical branch names5612$ver=~s!/!.!g;56135614# name = project-version_string5615$name="$name-$ver";56165617returnwantarray? ($name,$name) :$name;5618}56195620sub git_snapshot {5621my$format=$input_params{'snapshot_format'};5622if(!@snapshot_fmts) {5623 die_error(403,"Snapshots not allowed");5624}5625# default to first supported snapshot format5626$format||=$snapshot_fmts[0];5627if($format!~m/^[a-z0-9]+$/) {5628 die_error(400,"Invalid snapshot format parameter");5629}elsif(!exists($known_snapshot_formats{$format})) {5630 die_error(400,"Unknown snapshot format");5631}elsif($known_snapshot_formats{$format}{'disabled'}) {5632 die_error(403,"Snapshot format not allowed");5633}elsif(!grep($_eq$format,@snapshot_fmts)) {5634 die_error(403,"Unsupported snapshot format");5635}56365637my$type= git_get_type("$hash^{}");5638if(!$type) {5639 die_error(404,'Object does not exist');5640}elsif($typeeq'blob') {5641 die_error(400,'Object is not a tree-ish');5642}56435644my($name,$prefix) = snapshot_name($project,$hash);5645my$filename="$name$known_snapshot_formats{$format}{'suffix'}";5646my$cmd= quote_command(5647 git_cmd(),'archive',5648"--format=$known_snapshot_formats{$format}{'format'}",5649"--prefix=$prefix/",$hash);5650if(exists$known_snapshot_formats{$format}{'compressor'}) {5651$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});5652}56535654$filename=~s/(["\\])/\\$1/g;5655print$cgi->header(5656-type =>$known_snapshot_formats{$format}{'type'},5657-content_disposition =>'inline; filename="'.$filename.'"',5658-status =>'200 OK');56595660open my$fd,"-|",$cmd5661or die_error(500,"Execute git-archive failed");5662binmode STDOUT,':raw';5663print<$fd>;5664binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi5665close$fd;5666}56675668sub git_log_generic {5669my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;56705671my$head= git_get_head_hash($project);5672if(!defined$base) {5673$base=$head;5674}5675if(!defined$page) {5676$page=0;5677}5678my$refs= git_get_references();56795680my$commit_hash=$base;5681if(defined$parent) {5682$commit_hash="$parent..$base";5683}5684my@commitlist=5685 parse_commits($commit_hash,101, (100*$page),5686defined$file_name? ($file_name,"--full-history") : ());56875688my$ftype;5689if(!defined$file_hash&&defined$file_name) {5690# some commits could have deleted file in question,5691# and not have it in tree, but one of them has to have it5692for(my$i=0;$i<@commitlist;$i++) {5693$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);5694last ifdefined$file_hash;5695}5696}5697if(defined$file_hash) {5698$ftype= git_get_type($file_hash);5699}5700if(defined$file_name&& !defined$ftype) {5701 die_error(500,"Unknown type of object");5702}5703my%co;5704if(defined$file_name) {5705%co= parse_commit($base)5706or die_error(404,"Unknown commit object");5707}570857095710my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);5711my$next_link='';5712if($#commitlist>=100) {5713$next_link=5714$cgi->a({-href => href(-replay=>1, page=>$page+1),5715-accesskey =>"n", -title =>"Alt-n"},"next");5716}5717my$patch_max= gitweb_get_feature('patches');5718if($patch_max&& !defined$file_name) {5719if($patch_max<0||@commitlist<=$patch_max) {5720$paging_nav.=" ⋅ ".5721$cgi->a({-href => href(action=>"patches", -replay=>1)},5722"patches");5723}5724}57255726 git_header_html();5727 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);5728if(defined$file_name) {5729 git_print_header_div('commit', esc_html($co{'title'}),$base);5730}else{5731 git_print_header_div('summary',$project)5732}5733 git_print_page_path($file_name,$ftype,$hash_base)5734if(defined$file_name);57355736$body_subr->(\@commitlist,0,99,$refs,$next_link,5737$file_name,$file_hash,$ftype);57385739 git_footer_html();5740}57415742sub git_log {5743 git_log_generic('log', \&git_log_body,5744$hash,$hash_parent);5745}57465747sub git_commit {5748$hash||=$hash_base||"HEAD";5749my%co= parse_commit($hash)5750or die_error(404,"Unknown commit object");57515752my$parent=$co{'parent'};5753my$parents=$co{'parents'};# listref57545755# we need to prepare $formats_nav before any parameter munging5756my$formats_nav;5757if(!defined$parent) {5758# --root commitdiff5759$formats_nav.='(initial)';5760}elsif(@$parents==1) {5761# single parent commit5762$formats_nav.=5763'(parent: '.5764$cgi->a({-href => href(action=>"commit",5765 hash=>$parent)},5766 esc_html(substr($parent,0,7))) .5767')';5768}else{5769# merge commit5770$formats_nav.=5771'(merge: '.5772join(' ',map{5773$cgi->a({-href => href(action=>"commit",5774 hash=>$_)},5775 esc_html(substr($_,0,7)));5776}@$parents) .5777')';5778}5779if(gitweb_check_feature('patches') &&@$parents<=1) {5780$formats_nav.=" | ".5781$cgi->a({-href => href(action=>"patch", -replay=>1)},5782"patch");5783}57845785if(!defined$parent) {5786$parent="--root";5787}5788my@difftree;5789open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",5790@diff_opts,5791(@$parents<=1?$parent:'-c'),5792$hash,"--"5793or die_error(500,"Open git-diff-tree failed");5794@difftree=map{chomp;$_} <$fd>;5795close$fdor die_error(404,"Reading git-diff-tree failed");57965797# non-textual hash id's can be cached5798my$expires;5799if($hash=~m/^[0-9a-fA-F]{40}$/) {5800$expires="+1d";5801}5802my$refs= git_get_references();5803my$ref= format_ref_marker($refs,$co{'id'});58045805 git_header_html(undef,$expires);5806 git_print_page_nav('commit','',5807$hash,$co{'tree'},$hash,5808$formats_nav);58095810if(defined$co{'parent'}) {5811 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);5812}else{5813 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);5814}5815print"<div class=\"title_text\">\n".5816"<table class=\"object_header\">\n";5817 git_print_authorship_rows(\%co);5818print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";5819print"<tr>".5820"<td>tree</td>".5821"<td class=\"sha1\">".5822$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),5823class=>"list"},$co{'tree'}) .5824"</td>".5825"<td class=\"link\">".5826$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},5827"tree");5828my$snapshot_links= format_snapshot_links($hash);5829if(defined$snapshot_links) {5830print" | ".$snapshot_links;5831}5832print"</td>".5833"</tr>\n";58345835foreachmy$par(@$parents) {5836print"<tr>".5837"<td>parent</td>".5838"<td class=\"sha1\">".5839$cgi->a({-href => href(action=>"commit", hash=>$par),5840class=>"list"},$par) .5841"</td>".5842"<td class=\"link\">".5843$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .5844" | ".5845$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .5846"</td>".5847"</tr>\n";5848}5849print"</table>".5850"</div>\n";58515852print"<div class=\"page_body\">\n";5853 git_print_log($co{'comment'});5854print"</div>\n";58555856 git_difftree_body(\@difftree,$hash,@$parents);58575858 git_footer_html();5859}58605861sub git_object {5862# object is defined by:5863# - hash or hash_base alone5864# - hash_base and file_name5865my$type;58665867# - hash or hash_base alone5868if($hash|| ($hash_base&& !defined$file_name)) {5869my$object_id=$hash||$hash_base;58705871open my$fd,"-|", quote_command(5872 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'5873or die_error(404,"Object does not exist");5874$type= <$fd>;5875chomp$type;5876close$fd5877or die_error(404,"Object does not exist");58785879# - hash_base and file_name5880}elsif($hash_base&&defined$file_name) {5881$file_name=~ s,/+$,,;58825883system(git_cmd(),"cat-file",'-e',$hash_base) ==05884or die_error(404,"Base object does not exist");58855886# here errors should not hapen5887open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name5888or die_error(500,"Open git-ls-tree failed");5889my$line= <$fd>;5890close$fd;58915892#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'5893unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {5894 die_error(404,"File or directory for given base does not exist");5895}5896$type=$2;5897$hash=$3;5898}else{5899 die_error(400,"Not enough information to find object");5900}59015902print$cgi->redirect(-uri => href(action=>$type, -full=>1,5903 hash=>$hash, hash_base=>$hash_base,5904 file_name=>$file_name),5905-status =>'302 Found');5906}59075908sub git_blobdiff {5909my$format=shift||'html';59105911my$fd;5912my@difftree;5913my%diffinfo;5914my$expires;59155916# preparing $fd and %diffinfo for git_patchset_body5917# new style URI5918if(defined$hash_base&&defined$hash_parent_base) {5919if(defined$file_name) {5920# read raw output5921open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,5922$hash_parent_base,$hash_base,5923"--", (defined$file_parent?$file_parent: ()),$file_name5924or die_error(500,"Open git-diff-tree failed");5925@difftree=map{chomp;$_} <$fd>;5926close$fd5927or die_error(404,"Reading git-diff-tree failed");5928@difftree5929or die_error(404,"Blob diff not found");59305931}elsif(defined$hash&&5932$hash=~/[0-9a-fA-F]{40}/) {5933# try to find filename from $hash59345935# read filtered raw output5936open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,5937$hash_parent_base,$hash_base,"--"5938or die_error(500,"Open git-diff-tree failed");5939@difftree=5940# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'5941# $hash == to_id5942grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}5943map{chomp;$_} <$fd>;5944close$fd5945or die_error(404,"Reading git-diff-tree failed");5946@difftree5947or die_error(404,"Blob diff not found");59485949}else{5950 die_error(400,"Missing one of the blob diff parameters");5951}59525953if(@difftree>1) {5954 die_error(400,"Ambiguous blob diff specification");5955}59565957%diffinfo= parse_difftree_raw_line($difftree[0]);5958$file_parent||=$diffinfo{'from_file'} ||$file_name;5959$file_name||=$diffinfo{'to_file'};59605961$hash_parent||=$diffinfo{'from_id'};5962$hash||=$diffinfo{'to_id'};59635964# non-textual hash id's can be cached5965if($hash_base=~m/^[0-9a-fA-F]{40}$/&&5966$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {5967$expires='+1d';5968}59695970# open patch output5971open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,5972'-p', ($formateq'html'?"--full-index": ()),5973$hash_parent_base,$hash_base,5974"--", (defined$file_parent?$file_parent: ()),$file_name5975or die_error(500,"Open git-diff-tree failed");5976}59775978# old/legacy style URI -- not generated anymore since 1.4.3.5979if(!%diffinfo) {5980 die_error('404 Not Found',"Missing one of the blob diff parameters")5981}59825983# header5984if($formateq'html') {5985my$formats_nav=5986$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},5987"raw");5988 git_header_html(undef,$expires);5989if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5990 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5991 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5992}else{5993print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";5994print"<div class=\"title\">$hashvs$hash_parent</div>\n";5995}5996if(defined$file_name) {5997 git_print_page_path($file_name,"blob",$hash_base);5998}else{5999print"<div class=\"page_path\"></div>\n";6000}60016002}elsif($formateq'plain') {6003print$cgi->header(6004-type =>'text/plain',6005-charset =>'utf-8',6006-expires =>$expires,6007-content_disposition =>'inline; filename="'."$file_name".'.patch"');60086009print"X-Git-Url: ".$cgi->self_url() ."\n\n";60106011}else{6012 die_error(400,"Unknown blobdiff format");6013}60146015# patch6016if($formateq'html') {6017print"<div class=\"page_body\">\n";60186019 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);6020close$fd;60216022print"</div>\n";# class="page_body"6023 git_footer_html();60246025}else{6026while(my$line= <$fd>) {6027$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;6028$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;60296030print$line;60316032last if$line=~m!^\+\+\+!;6033}6034local$/=undef;6035print<$fd>;6036close$fd;6037}6038}60396040sub git_blobdiff_plain {6041 git_blobdiff('plain');6042}60436044sub git_commitdiff {6045my%params=@_;6046my$format=$params{-format} ||'html';60476048my($patch_max) = gitweb_get_feature('patches');6049if($formateq'patch') {6050 die_error(403,"Patch view not allowed")unless$patch_max;6051}60526053$hash||=$hash_base||"HEAD";6054my%co= parse_commit($hash)6055or die_error(404,"Unknown commit object");60566057# choose format for commitdiff for merge6058if(!defined$hash_parent&& @{$co{'parents'}} >1) {6059$hash_parent='--cc';6060}6061# we need to prepare $formats_nav before almost any parameter munging6062my$formats_nav;6063if($formateq'html') {6064$formats_nav=6065$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},6066"raw");6067if($patch_max&& @{$co{'parents'}} <=1) {6068$formats_nav.=" | ".6069$cgi->a({-href => href(action=>"patch", -replay=>1)},6070"patch");6071}60726073if(defined$hash_parent&&6074$hash_parentne'-c'&&$hash_parentne'--cc') {6075# commitdiff with two commits given6076my$hash_parent_short=$hash_parent;6077if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {6078$hash_parent_short=substr($hash_parent,0,7);6079}6080$formats_nav.=6081' (from';6082for(my$i=0;$i< @{$co{'parents'}};$i++) {6083if($co{'parents'}[$i]eq$hash_parent) {6084$formats_nav.=' parent '. ($i+1);6085last;6086}6087}6088$formats_nav.=': '.6089$cgi->a({-href => href(action=>"commitdiff",6090 hash=>$hash_parent)},6091 esc_html($hash_parent_short)) .6092')';6093}elsif(!$co{'parent'}) {6094# --root commitdiff6095$formats_nav.=' (initial)';6096}elsif(scalar@{$co{'parents'}} ==1) {6097# single parent commit6098$formats_nav.=6099' (parent: '.6100$cgi->a({-href => href(action=>"commitdiff",6101 hash=>$co{'parent'})},6102 esc_html(substr($co{'parent'},0,7))) .6103')';6104}else{6105# merge commit6106if($hash_parenteq'--cc') {6107$formats_nav.=' | '.6108$cgi->a({-href => href(action=>"commitdiff",6109 hash=>$hash, hash_parent=>'-c')},6110'combined');6111}else{# $hash_parent eq '-c'6112$formats_nav.=' | '.6113$cgi->a({-href => href(action=>"commitdiff",6114 hash=>$hash, hash_parent=>'--cc')},6115'compact');6116}6117$formats_nav.=6118' (merge: '.6119join(' ',map{6120$cgi->a({-href => href(action=>"commitdiff",6121 hash=>$_)},6122 esc_html(substr($_,0,7)));6123} @{$co{'parents'}} ) .6124')';6125}6126}61276128my$hash_parent_param=$hash_parent;6129if(!defined$hash_parent_param) {6130# --cc for multiple parents, --root for parentless6131$hash_parent_param=6132@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';6133}61346135# read commitdiff6136my$fd;6137my@difftree;6138if($formateq'html') {6139open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6140"--no-commit-id","--patch-with-raw","--full-index",6141$hash_parent_param,$hash,"--"6142or die_error(500,"Open git-diff-tree failed");61436144while(my$line= <$fd>) {6145chomp$line;6146# empty line ends raw part of diff-tree output6147last unless$line;6148push@difftree,scalar parse_difftree_raw_line($line);6149}61506151}elsif($formateq'plain') {6152open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6153'-p',$hash_parent_param,$hash,"--"6154or die_error(500,"Open git-diff-tree failed");6155}elsif($formateq'patch') {6156# For commit ranges, we limit the output to the number of6157# patches specified in the 'patches' feature.6158# For single commits, we limit the output to a single patch,6159# diverging from the git-format-patch default.6160my@commit_spec= ();6161if($hash_parent) {6162if($patch_max>0) {6163push@commit_spec,"-$patch_max";6164}6165push@commit_spec,'-n',"$hash_parent..$hash";6166}else{6167if($params{-single}) {6168push@commit_spec,'-1';6169}else{6170if($patch_max>0) {6171push@commit_spec,"-$patch_max";6172}6173push@commit_spec,"-n";6174}6175push@commit_spec,'--root',$hash;6176}6177open$fd,"-|", git_cmd(),"format-patch",'--encoding=utf8',6178'--stdout',@commit_spec6179or die_error(500,"Open git-format-patch failed");6180}else{6181 die_error(400,"Unknown commitdiff format");6182}61836184# non-textual hash id's can be cached6185my$expires;6186if($hash=~m/^[0-9a-fA-F]{40}$/) {6187$expires="+1d";6188}61896190# write commit message6191if($formateq'html') {6192my$refs= git_get_references();6193my$ref= format_ref_marker($refs,$co{'id'});61946195 git_header_html(undef,$expires);6196 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);6197 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);6198print"<div class=\"title_text\">\n".6199"<table class=\"object_header\">\n";6200 git_print_authorship_rows(\%co);6201print"</table>".6202"</div>\n";6203print"<div class=\"page_body\">\n";6204if(@{$co{'comment'}} >1) {6205print"<div class=\"log\">\n";6206 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);6207print"</div>\n";# class="log"6208}62096210}elsif($formateq'plain') {6211my$refs= git_get_references("tags");6212my$tagname= git_get_rev_name_tags($hash);6213my$filename= basename($project) ."-$hash.patch";62146215print$cgi->header(6216-type =>'text/plain',6217-charset =>'utf-8',6218-expires =>$expires,6219-content_disposition =>'inline; filename="'."$filename".'"');6220my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});6221print"From: ". to_utf8($co{'author'}) ."\n";6222print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";6223print"Subject: ". to_utf8($co{'title'}) ."\n";62246225print"X-Git-Tag:$tagname\n"if$tagname;6226print"X-Git-Url: ".$cgi->self_url() ."\n\n";62276228foreachmy$line(@{$co{'comment'}}) {6229print to_utf8($line) ."\n";6230}6231print"---\n\n";6232}elsif($formateq'patch') {6233my$filename= basename($project) ."-$hash.patch";62346235print$cgi->header(6236-type =>'text/plain',6237-charset =>'utf-8',6238-expires =>$expires,6239-content_disposition =>'inline; filename="'."$filename".'"');6240}62416242# write patch6243if($formateq'html') {6244my$use_parents= !defined$hash_parent||6245$hash_parenteq'-c'||$hash_parenteq'--cc';6246 git_difftree_body(\@difftree,$hash,6247$use_parents? @{$co{'parents'}} :$hash_parent);6248print"<br/>\n";62496250 git_patchset_body($fd, \@difftree,$hash,6251$use_parents? @{$co{'parents'}} :$hash_parent);6252close$fd;6253print"</div>\n";# class="page_body"6254 git_footer_html();62556256}elsif($formateq'plain') {6257local$/=undef;6258print<$fd>;6259close$fd6260or print"Reading git-diff-tree failed\n";6261}elsif($formateq'patch') {6262local$/=undef;6263print<$fd>;6264close$fd6265or print"Reading git-format-patch failed\n";6266}6267}62686269sub git_commitdiff_plain {6270 git_commitdiff(-format =>'plain');6271}62726273# format-patch-style patches6274sub git_patch {6275 git_commitdiff(-format =>'patch', -single =>1);6276}62776278sub git_patches {6279 git_commitdiff(-format =>'patch');6280}62816282sub git_history {6283 git_log_generic('history', \&git_history_body,6284$hash_base,$hash_parent_base,6285$file_name,$hash);6286}62876288sub git_search {6289 gitweb_check_feature('search')or die_error(403,"Search is disabled");6290if(!defined$searchtext) {6291 die_error(400,"Text field is empty");6292}6293if(!defined$hash) {6294$hash= git_get_head_hash($project);6295}6296my%co= parse_commit($hash);6297if(!%co) {6298 die_error(404,"Unknown commit object");6299}6300if(!defined$page) {6301$page=0;6302}63036304$searchtype||='commit';6305if($searchtypeeq'pickaxe') {6306# pickaxe may take all resources of your box and run for several minutes6307# with every query - so decide by yourself how public you make this feature6308 gitweb_check_feature('pickaxe')6309or die_error(403,"Pickaxe is disabled");6310}6311if($searchtypeeq'grep') {6312 gitweb_check_feature('grep')6313or die_error(403,"Grep is disabled");6314}63156316 git_header_html();63176318if($searchtypeeq'commit'or$searchtypeeq'author'or$searchtypeeq'committer') {6319my$greptype;6320if($searchtypeeq'commit') {6321$greptype="--grep=";6322}elsif($searchtypeeq'author') {6323$greptype="--author=";6324}elsif($searchtypeeq'committer') {6325$greptype="--committer=";6326}6327$greptype.=$searchtext;6328my@commitlist= parse_commits($hash,101, (100*$page),undef,6329$greptype,'--regexp-ignore-case',6330$search_use_regexp?'--extended-regexp':'--fixed-strings');63316332my$paging_nav='';6333if($page>0) {6334$paging_nav.=6335$cgi->a({-href => href(action=>"search", hash=>$hash,6336 searchtext=>$searchtext,6337 searchtype=>$searchtype)},6338"first");6339$paging_nav.=" ⋅ ".6340$cgi->a({-href => href(-replay=>1, page=>$page-1),6341-accesskey =>"p", -title =>"Alt-p"},"prev");6342}else{6343$paging_nav.="first";6344$paging_nav.=" ⋅ prev";6345}6346my$next_link='';6347if($#commitlist>=100) {6348$next_link=6349$cgi->a({-href => href(-replay=>1, page=>$page+1),6350-accesskey =>"n", -title =>"Alt-n"},"next");6351$paging_nav.=" ⋅$next_link";6352}else{6353$paging_nav.=" ⋅ next";6354}63556356if($#commitlist>=100) {6357}63586359 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);6360 git_print_header_div('commit', esc_html($co{'title'}),$hash);6361 git_search_grep_body(\@commitlist,0,99,$next_link);6362}63636364if($searchtypeeq'pickaxe') {6365 git_print_page_nav('','',$hash,$co{'tree'},$hash);6366 git_print_header_div('commit', esc_html($co{'title'}),$hash);63676368print"<table class=\"pickaxe search\">\n";6369my$alternate=1;6370local$/="\n";6371open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,6372'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",6373($search_use_regexp?'--pickaxe-regex': ());6374undef%co;6375my@files;6376while(my$line= <$fd>) {6377chomp$line;6378next unless$line;63796380my%set= parse_difftree_raw_line($line);6381if(defined$set{'commit'}) {6382# finish previous commit6383if(%co) {6384print"</td>\n".6385"<td class=\"link\">".6386$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6387" | ".6388$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6389print"</td>\n".6390"</tr>\n";6391}63926393if($alternate) {6394print"<tr class=\"dark\">\n";6395}else{6396print"<tr class=\"light\">\n";6397}6398$alternate^=1;6399%co= parse_commit($set{'commit'});6400my$author= chop_and_escape_str($co{'author_name'},15,5);6401print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6402"<td><i>$author</i></td>\n".6403"<td>".6404$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6405-class=>"list subject"},6406 chop_and_escape_str($co{'title'},50) ."<br/>");6407}elsif(defined$set{'to_id'}) {6408next if($set{'to_id'} =~m/^0{40}$/);64096410print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},6411 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),6412-class=>"list"},6413"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .6414"<br/>\n";6415}6416}6417close$fd;64186419# finish last commit (warning: repetition!)6420if(%co) {6421print"</td>\n".6422"<td class=\"link\">".6423$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6424" | ".6425$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6426print"</td>\n".6427"</tr>\n";6428}64296430print"</table>\n";6431}64326433if($searchtypeeq'grep') {6434 git_print_page_nav('','',$hash,$co{'tree'},$hash);6435 git_print_header_div('commit', esc_html($co{'title'}),$hash);64366437print"<table class=\"grep_search\">\n";6438my$alternate=1;6439my$matches=0;6440local$/="\n";6441open my$fd,"-|", git_cmd(),'grep','-n',6442$search_use_regexp? ('-E','-i') :'-F',6443$searchtext,$co{'tree'};6444my$lastfile='';6445while(my$line= <$fd>) {6446chomp$line;6447my($file,$lno,$ltext,$binary);6448last if($matches++>1000);6449if($line=~/^Binary file (.+) matches$/) {6450$file=$1;6451$binary=1;6452}else{6453(undef,$file,$lno,$ltext) =split(/:/,$line,4);6454}6455if($filene$lastfile) {6456$lastfileand print"</td></tr>\n";6457if($alternate++) {6458print"<tr class=\"dark\">\n";6459}else{6460print"<tr class=\"light\">\n";6461}6462print"<td class=\"list\">".6463$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},6464 file_name=>"$file"),6465-class=>"list"}, esc_path($file));6466print"</td><td>\n";6467$lastfile=$file;6468}6469if($binary) {6470print"<div class=\"binary\">Binary file</div>\n";6471}else{6472$ltext= untabify($ltext);6473if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6474$ltext= esc_html($1, -nbsp=>1);6475$ltext.='<span class="match">';6476$ltext.= esc_html($2, -nbsp=>1);6477$ltext.='</span>';6478$ltext.= esc_html($3, -nbsp=>1);6479}else{6480$ltext= esc_html($ltext, -nbsp=>1);6481}6482print"<div class=\"pre\">".6483$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},6484 file_name=>"$file").'#l'.$lno,6485-class=>"linenr"},sprintf('%4i',$lno))6486.' '.$ltext."</div>\n";6487}6488}6489if($lastfile) {6490print"</td></tr>\n";6491if($matches>1000) {6492print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6493}6494}else{6495print"<div class=\"diff nodifferences\">No matches found</div>\n";6496}6497close$fd;64986499print"</table>\n";6500}6501 git_footer_html();6502}65036504sub git_search_help {6505 git_header_html();6506 git_print_page_nav('','',$hash,$hash,$hash);6507print<<EOT;6508<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without6509regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,6510the pattern entered is recognized as the POSIX extended6511<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case6512insensitive).</p>6513<dl>6514<dt><b>commit</b></dt>6515<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>6516EOT6517my$have_grep= gitweb_check_feature('grep');6518if($have_grep) {6519print<<EOT;6520<dt><b>grep</b></dt>6521<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing6522 a different one) are searched for the given pattern. On large trees, this search can take6523a while and put some strain on the server, so please use it with some consideration. Note that6524due to git-grep peculiarity, currently if regexp mode is turned off, the matches are6525case-sensitive.</dd>6526EOT6527}6528print<<EOT;6529<dt><b>author</b></dt>6530<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>6531<dt><b>committer</b></dt>6532<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>6533EOT6534my$have_pickaxe= gitweb_check_feature('pickaxe');6535if($have_pickaxe) {6536print<<EOT;6537<dt><b>pickaxe</b></dt>6538<dd>All commits that caused the string to appear or disappear from any file (changes that6539added, removed or "modified" the string) will be listed. This search can take a while and6540takes a lot of strain on the server, so please use it wisely. Note that since you may be6541interested even in changes just changing the case as well, this search is case sensitive.</dd>6542EOT6543}6544print"</dl>\n";6545 git_footer_html();6546}65476548sub git_shortlog {6549 git_log_generic('shortlog', \&git_shortlog_body,6550$hash,$hash_parent);6551}65526553## ......................................................................6554## feeds (RSS, Atom; OPML)65556556sub git_feed {6557my$format=shift||'atom';6558my$have_blame= gitweb_check_feature('blame');65596560# Atom: http://www.atomenabled.org/developers/syndication/6561# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ6562if($formatne'rss'&&$formatne'atom') {6563 die_error(400,"Unknown web feed format");6564}65656566# log/feed of current (HEAD) branch, log of given branch, history of file/directory6567my$head=$hash||'HEAD';6568my@commitlist= parse_commits($head,150,0,$file_name);65696570my%latest_commit;6571my%latest_date;6572my$content_type="application/$format+xml";6573if(defined$cgi->http('HTTP_ACCEPT') &&6574$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {6575# browser (feed reader) prefers text/xml6576$content_type='text/xml';6577}6578if(defined($commitlist[0])) {6579%latest_commit= %{$commitlist[0]};6580my$latest_epoch=$latest_commit{'committer_epoch'};6581%latest_date= parse_date($latest_epoch);6582my$if_modified=$cgi->http('IF_MODIFIED_SINCE');6583if(defined$if_modified) {6584my$since;6585if(eval{require HTTP::Date;1; }) {6586$since= HTTP::Date::str2time($if_modified);6587}elsif(eval{require Time::ParseDate;1; }) {6588$since= Time::ParseDate::parsedate($if_modified, GMT =>1);6589}6590if(defined$since&&$latest_epoch<=$since) {6591print$cgi->header(6592-type =>$content_type,6593-charset =>'utf-8',6594-last_modified =>$latest_date{'rfc2822'},6595-status =>'304 Not Modified');6596return;6597}6598}6599print$cgi->header(6600-type =>$content_type,6601-charset =>'utf-8',6602-last_modified =>$latest_date{'rfc2822'});6603}else{6604print$cgi->header(6605-type =>$content_type,6606-charset =>'utf-8');6607}66086609# Optimization: skip generating the body if client asks only6610# for Last-Modified date.6611return if($cgi->request_method()eq'HEAD');66126613# header variables6614my$title="$site_name-$project/$action";6615my$feed_type='log';6616if(defined$hash) {6617$title.=" - '$hash'";6618$feed_type='branch log';6619if(defined$file_name) {6620$title.=" ::$file_name";6621$feed_type='history';6622}6623}elsif(defined$file_name) {6624$title.=" -$file_name";6625$feed_type='history';6626}6627$title.="$feed_type";6628my$descr= git_get_project_description($project);6629if(defined$descr) {6630$descr= esc_html($descr);6631}else{6632$descr="$project".6633($formateq'rss'?'RSS':'Atom') .6634" feed";6635}6636my$owner= git_get_project_owner($project);6637$owner= esc_html($owner);66386639#header6640my$alt_url;6641if(defined$file_name) {6642$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);6643}elsif(defined$hash) {6644$alt_url= href(-full=>1, action=>"log", hash=>$hash);6645}else{6646$alt_url= href(-full=>1, action=>"summary");6647}6648print qq!<?xml version="1.0" encoding="utf-8"?>\n!;6649if($formateq'rss') {6650print<<XML;6651<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">6652<channel>6653XML6654print"<title>$title</title>\n".6655"<link>$alt_url</link>\n".6656"<description>$descr</description>\n".6657"<language>en</language>\n".6658# project owner is responsible for 'editorial' content6659"<managingEditor>$owner</managingEditor>\n";6660if(defined$logo||defined$favicon) {6661# prefer the logo to the favicon, since RSS6662# doesn't allow both6663my$img= esc_url($logo||$favicon);6664print"<image>\n".6665"<url>$img</url>\n".6666"<title>$title</title>\n".6667"<link>$alt_url</link>\n".6668"</image>\n";6669}6670if(%latest_date) {6671print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";6672print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";6673}6674print"<generator>gitweb v.$version/$git_version</generator>\n";6675}elsif($formateq'atom') {6676print<<XML;6677<feed xmlns="http://www.w3.org/2005/Atom">6678XML6679print"<title>$title</title>\n".6680"<subtitle>$descr</subtitle>\n".6681'<link rel="alternate" type="text/html" href="'.6682$alt_url.'" />'."\n".6683'<link rel="self" type="'.$content_type.'" href="'.6684$cgi->self_url() .'" />'."\n".6685"<id>". href(-full=>1) ."</id>\n".6686# use project owner for feed author6687"<author><name>$owner</name></author>\n";6688if(defined$favicon) {6689print"<icon>". esc_url($favicon) ."</icon>\n";6690}6691if(defined$logo_url) {6692# not twice as wide as tall: 72 x 27 pixels6693print"<logo>". esc_url($logo) ."</logo>\n";6694}6695if(!%latest_date) {6696# dummy date to keep the feed valid until commits trickle in:6697print"<updated>1970-01-01T00:00:00Z</updated>\n";6698}else{6699print"<updated>$latest_date{'iso-8601'}</updated>\n";6700}6701print"<generator version='$version/$git_version'>gitweb</generator>\n";6702}67036704# contents6705for(my$i=0;$i<=$#commitlist;$i++) {6706my%co= %{$commitlist[$i]};6707my$commit=$co{'id'};6708# we read 150, we always show 30 and the ones more recent than 48 hours6709if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {6710last;6711}6712my%cd= parse_date($co{'author_epoch'});67136714# get list of changed files6715open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6716$co{'parent'} ||"--root",6717$co{'id'},"--", (defined$file_name?$file_name: ())6718ornext;6719my@difftree=map{chomp;$_} <$fd>;6720close$fd6721ornext;67226723# print element (entry, item)6724my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);6725if($formateq'rss') {6726print"<item>\n".6727"<title>". esc_html($co{'title'}) ."</title>\n".6728"<author>". esc_html($co{'author'}) ."</author>\n".6729"<pubDate>$cd{'rfc2822'}</pubDate>\n".6730"<guid isPermaLink=\"true\">$co_url</guid>\n".6731"<link>$co_url</link>\n".6732"<description>". esc_html($co{'title'}) ."</description>\n".6733"<content:encoded>".6734"<![CDATA[\n";6735}elsif($formateq'atom') {6736print"<entry>\n".6737"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".6738"<updated>$cd{'iso-8601'}</updated>\n".6739"<author>\n".6740" <name>". esc_html($co{'author_name'}) ."</name>\n";6741if($co{'author_email'}) {6742print" <email>". esc_html($co{'author_email'}) ."</email>\n";6743}6744print"</author>\n".6745# use committer for contributor6746"<contributor>\n".6747" <name>". esc_html($co{'committer_name'}) ."</name>\n";6748if($co{'committer_email'}) {6749print" <email>". esc_html($co{'committer_email'}) ."</email>\n";6750}6751print"</contributor>\n".6752"<published>$cd{'iso-8601'}</published>\n".6753"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".6754"<id>$co_url</id>\n".6755"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".6756"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";6757}6758my$comment=$co{'comment'};6759print"<pre>\n";6760foreachmy$line(@$comment) {6761$line= esc_html($line);6762print"$line\n";6763}6764print"</pre><ul>\n";6765foreachmy$difftree_line(@difftree) {6766my%difftree= parse_difftree_raw_line($difftree_line);6767next if!$difftree{'from_id'};67686769my$file=$difftree{'file'} ||$difftree{'to_file'};67706771print"<li>".6772"[".6773$cgi->a({-href => href(-full=>1, action=>"blobdiff",6774 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},6775 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},6776 file_name=>$file, file_parent=>$difftree{'from_file'}),6777-title =>"diff"},'D');6778if($have_blame) {6779print$cgi->a({-href => href(-full=>1, action=>"blame",6780 file_name=>$file, hash_base=>$commit),6781-title =>"blame"},'B');6782}6783# if this is not a feed of a file history6784if(!defined$file_name||$file_namene$file) {6785print$cgi->a({-href => href(-full=>1, action=>"history",6786 file_name=>$file, hash=>$commit),6787-title =>"history"},'H');6788}6789$file= esc_path($file);6790print"] ".6791"$file</li>\n";6792}6793if($formateq'rss') {6794print"</ul>]]>\n".6795"</content:encoded>\n".6796"</item>\n";6797}elsif($formateq'atom') {6798print"</ul>\n</div>\n".6799"</content>\n".6800"</entry>\n";6801}6802}68036804# end of feed6805if($formateq'rss') {6806print"</channel>\n</rss>\n";6807}elsif($formateq'atom') {6808print"</feed>\n";6809}6810}68116812sub git_rss {6813 git_feed('rss');6814}68156816sub git_atom {6817 git_feed('atom');6818}68196820sub git_opml {6821my@list= git_get_projects_list();68226823print$cgi->header(6824-type =>'text/xml',6825-charset =>'utf-8',6826-content_disposition =>'inline; filename="opml.xml"');68276828print<<XML;6829<?xml version="1.0" encoding="utf-8"?>6830<opml version="1.0">6831<head>6832 <title>$site_nameOPML Export</title>6833</head>6834<body>6835<outline text="git RSS feeds">6836XML68376838foreachmy$pr(@list) {6839my%proj=%$pr;6840my$head= git_get_head_hash($proj{'path'});6841if(!defined$head) {6842next;6843}6844$git_dir="$projectroot/$proj{'path'}";6845my%co= parse_commit($head);6846if(!%co) {6847next;6848}68496850my$path= esc_html(chop_str($proj{'path'},25,5));6851my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);6852my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);6853print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";6854}6855print<<XML;6856</outline>6857</body>6858</opml>6859XML6860}