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 set_message); 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# Syntax highlighting support. This is based on Daniel Svensson's 455# and Sham Chukoury's work in gitweb-xmms2.git. 456# It requires the 'highlight' program present in $PATH, 457# and therefore is disabled by default. 458 459# To enable system wide have in $GITWEB_CONFIG 460# $feature{'highlight'}{'default'} = [1]; 461 462'highlight'=> { 463'sub'=>sub{ feature_bool('highlight',@_) }, 464'override'=>0, 465'default'=> [0]}, 466); 467 468sub gitweb_get_feature { 469my($name) =@_; 470return unlessexists$feature{$name}; 471my($sub,$override,@defaults) = ( 472$feature{$name}{'sub'}, 473$feature{$name}{'override'}, 474@{$feature{$name}{'default'}}); 475# project specific override is possible only if we have project 476our$git_dir;# global variable, declared later 477if(!$override|| !defined$git_dir) { 478return@defaults; 479} 480if(!defined$sub) { 481warn"feature$nameis not overridable"; 482return@defaults; 483} 484return$sub->(@defaults); 485} 486 487# A wrapper to check if a given feature is enabled. 488# With this, you can say 489# 490# my $bool_feat = gitweb_check_feature('bool_feat'); 491# gitweb_check_feature('bool_feat') or somecode; 492# 493# instead of 494# 495# my ($bool_feat) = gitweb_get_feature('bool_feat'); 496# (gitweb_get_feature('bool_feat'))[0] or somecode; 497# 498sub gitweb_check_feature { 499return(gitweb_get_feature(@_))[0]; 500} 501 502 503sub feature_bool { 504my$key=shift; 505my($val) = git_get_project_config($key,'--bool'); 506 507if(!defined$val) { 508return($_[0]); 509}elsif($valeq'true') { 510return(1); 511}elsif($valeq'false') { 512return(0); 513} 514} 515 516sub feature_snapshot { 517my(@fmts) =@_; 518 519my($val) = git_get_project_config('snapshot'); 520 521if($val) { 522@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 523} 524 525return@fmts; 526} 527 528sub feature_patches { 529my@val= (git_get_project_config('patches','--int')); 530 531if(@val) { 532return@val; 533} 534 535return($_[0]); 536} 537 538sub feature_avatar { 539my@val= (git_get_project_config('avatar')); 540 541return@val?@val:@_; 542} 543 544# checking HEAD file with -e is fragile if the repository was 545# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 546# and then pruned. 547sub check_head_link { 548my($dir) =@_; 549my$headfile="$dir/HEAD"; 550return((-e $headfile) || 551(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 552} 553 554sub check_export_ok { 555my($dir) =@_; 556return(check_head_link($dir) && 557(!$export_ok|| -e "$dir/$export_ok") && 558(!$export_auth_hook||$export_auth_hook->($dir))); 559} 560 561# process alternate names for backward compatibility 562# filter out unsupported (unknown) snapshot formats 563sub filter_snapshot_fmts { 564my@fmts=@_; 565 566@fmts=map{ 567exists$known_snapshot_format_aliases{$_} ? 568$known_snapshot_format_aliases{$_} :$_}@fmts; 569@fmts=grep{ 570exists$known_snapshot_formats{$_} && 571!$known_snapshot_formats{$_}{'disabled'}}@fmts; 572} 573 574our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM); 575sub evaluate_gitweb_config { 576our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 577our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 578# die if there are errors parsing config file 579if(-e $GITWEB_CONFIG) { 580do$GITWEB_CONFIG; 581die$@if$@; 582}elsif(-e $GITWEB_CONFIG_SYSTEM) { 583do$GITWEB_CONFIG_SYSTEM; 584die$@if$@; 585} 586} 587 588# Get loadavg of system, to compare against $maxload. 589# Currently it requires '/proc/loadavg' present to get loadavg; 590# if it is not present it returns 0, which means no load checking. 591sub get_loadavg { 592if( -e '/proc/loadavg'){ 593open my$fd,'<','/proc/loadavg' 594orreturn0; 595my@load=split(/\s+/,scalar<$fd>); 596close$fd; 597 598# The first three columns measure CPU and IO utilization of the last one, 599# five, and 10 minute periods. The fourth column shows the number of 600# currently running processes and the total number of processes in the m/n 601# format. The last column displays the last process ID used. 602return$load[0] ||0; 603} 604# additional checks for load average should go here for things that don't export 605# /proc/loadavg 606 607return0; 608} 609 610# version of the core git binary 611our$git_version; 612sub evaluate_git_version { 613our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 614$number_of_git_cmds++; 615} 616 617sub check_loadavg { 618if(defined$maxload&& get_loadavg() >$maxload) { 619 die_error(503,"The load average on the server is too high"); 620} 621} 622 623# ====================================================================== 624# input validation and dispatch 625 626# input parameters can be collected from a variety of sources (presently, CGI 627# and PATH_INFO), so we define an %input_params hash that collects them all 628# together during validation: this allows subsequent uses (e.g. href()) to be 629# agnostic of the parameter origin 630 631our%input_params= (); 632 633# input parameters are stored with the long parameter name as key. This will 634# also be used in the href subroutine to convert parameters to their CGI 635# equivalent, and since the href() usage is the most frequent one, we store 636# the name -> CGI key mapping here, instead of the reverse. 637# 638# XXX: Warning: If you touch this, check the search form for updating, 639# too. 640 641our@cgi_param_mapping= ( 642 project =>"p", 643 action =>"a", 644 file_name =>"f", 645 file_parent =>"fp", 646 hash =>"h", 647 hash_parent =>"hp", 648 hash_base =>"hb", 649 hash_parent_base =>"hpb", 650 page =>"pg", 651 order =>"o", 652 searchtext =>"s", 653 searchtype =>"st", 654 snapshot_format =>"sf", 655 extra_options =>"opt", 656 search_use_regexp =>"sr", 657# this must be last entry (for manipulation from JavaScript) 658 javascript =>"js" 659); 660our%cgi_param_mapping=@cgi_param_mapping; 661 662# we will also need to know the possible actions, for validation 663our%actions= ( 664"blame"=> \&git_blame, 665"blame_incremental"=> \&git_blame_incremental, 666"blame_data"=> \&git_blame_data, 667"blobdiff"=> \&git_blobdiff, 668"blobdiff_plain"=> \&git_blobdiff_plain, 669"blob"=> \&git_blob, 670"blob_plain"=> \&git_blob_plain, 671"commitdiff"=> \&git_commitdiff, 672"commitdiff_plain"=> \&git_commitdiff_plain, 673"commit"=> \&git_commit, 674"forks"=> \&git_forks, 675"heads"=> \&git_heads, 676"history"=> \&git_history, 677"log"=> \&git_log, 678"patch"=> \&git_patch, 679"patches"=> \&git_patches, 680"rss"=> \&git_rss, 681"atom"=> \&git_atom, 682"search"=> \&git_search, 683"search_help"=> \&git_search_help, 684"shortlog"=> \&git_shortlog, 685"summary"=> \&git_summary, 686"tag"=> \&git_tag, 687"tags"=> \&git_tags, 688"tree"=> \&git_tree, 689"snapshot"=> \&git_snapshot, 690"object"=> \&git_object, 691# those below don't need $project 692"opml"=> \&git_opml, 693"project_list"=> \&git_project_list, 694"project_index"=> \&git_project_index, 695); 696 697# finally, we have the hash of allowed extra_options for the commands that 698# allow them 699our%allowed_options= ( 700"--no-merges"=> [qw(rss atom log shortlog history)], 701); 702 703# fill %input_params with the CGI parameters. All values except for 'opt' 704# should be single values, but opt can be an array. We should probably 705# build an array of parameters that can be multi-valued, but since for the time 706# being it's only this one, we just single it out 707sub evaluate_query_params { 708our$cgi; 709 710while(my($name,$symbol) =each%cgi_param_mapping) { 711if($symboleq'opt') { 712$input_params{$name} = [$cgi->param($symbol) ]; 713}else{ 714$input_params{$name} =$cgi->param($symbol); 715} 716} 717} 718 719# now read PATH_INFO and update the parameter list for missing parameters 720sub evaluate_path_info { 721return ifdefined$input_params{'project'}; 722return if!$path_info; 723$path_info=~ s,^/+,,; 724return if!$path_info; 725 726# find which part of PATH_INFO is project 727my$project=$path_info; 728$project=~ s,/+$,,; 729while($project&& !check_head_link("$projectroot/$project")) { 730$project=~ s,/*[^/]*$,,; 731} 732return unless$project; 733$input_params{'project'} =$project; 734 735# do not change any parameters if an action is given using the query string 736return if$input_params{'action'}; 737$path_info=~ s,^\Q$project\E/*,,; 738 739# next, check if we have an action 740my$action=$path_info; 741$action=~ s,/.*$,,; 742if(exists$actions{$action}) { 743$path_info=~ s,^$action/*,,; 744$input_params{'action'} =$action; 745} 746 747# list of actions that want hash_base instead of hash, but can have no 748# pathname (f) parameter 749my@wants_base= ( 750'tree', 751'history', 752); 753 754# we want to catch 755# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 756my($parentrefname,$parentpathname,$refname,$pathname) = 757($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/); 758 759# first, analyze the 'current' part 760if(defined$pathname) { 761# we got "branch:filename" or "branch:dir/" 762# we could use git_get_type(branch:pathname), but: 763# - it needs $git_dir 764# - it does a git() call 765# - the convention of terminating directories with a slash 766# makes it superfluous 767# - embedding the action in the PATH_INFO would make it even 768# more superfluous 769$pathname=~ s,^/+,,; 770if(!$pathname||substr($pathname, -1)eq"/") { 771$input_params{'action'} ||="tree"; 772$pathname=~ s,/$,,; 773}else{ 774# the default action depends on whether we had parent info 775# or not 776if($parentrefname) { 777$input_params{'action'} ||="blobdiff_plain"; 778}else{ 779$input_params{'action'} ||="blob_plain"; 780} 781} 782$input_params{'hash_base'} ||=$refname; 783$input_params{'file_name'} ||=$pathname; 784}elsif(defined$refname) { 785# we got "branch". In this case we have to choose if we have to 786# set hash or hash_base. 787# 788# Most of the actions without a pathname only want hash to be 789# set, except for the ones specified in @wants_base that want 790# hash_base instead. It should also be noted that hand-crafted 791# links having 'history' as an action and no pathname or hash 792# set will fail, but that happens regardless of PATH_INFO. 793$input_params{'action'} ||="shortlog"; 794if(grep{$_eq$input_params{'action'} }@wants_base) { 795$input_params{'hash_base'} ||=$refname; 796}else{ 797$input_params{'hash'} ||=$refname; 798} 799} 800 801# next, handle the 'parent' part, if present 802if(defined$parentrefname) { 803# a missing pathspec defaults to the 'current' filename, allowing e.g. 804# someproject/blobdiff/oldrev..newrev:/filename 805if($parentpathname) { 806$parentpathname=~ s,^/+,,; 807$parentpathname=~ s,/$,,; 808$input_params{'file_parent'} ||=$parentpathname; 809}else{ 810$input_params{'file_parent'} ||=$input_params{'file_name'}; 811} 812# we assume that hash_parent_base is wanted if a path was specified, 813# or if the action wants hash_base instead of hash 814if(defined$input_params{'file_parent'} || 815grep{$_eq$input_params{'action'} }@wants_base) { 816$input_params{'hash_parent_base'} ||=$parentrefname; 817}else{ 818$input_params{'hash_parent'} ||=$parentrefname; 819} 820} 821 822# for the snapshot action, we allow URLs in the form 823# $project/snapshot/$hash.ext 824# where .ext determines the snapshot and gets removed from the 825# passed $refname to provide the $hash. 826# 827# To be able to tell that $refname includes the format extension, we 828# require the following two conditions to be satisfied: 829# - the hash input parameter MUST have been set from the $refname part 830# of the URL (i.e. they must be equal) 831# - the snapshot format MUST NOT have been defined already (e.g. from 832# CGI parameter sf) 833# It's also useless to try any matching unless $refname has a dot, 834# so we check for that too 835if(defined$input_params{'action'} && 836$input_params{'action'}eq'snapshot'&& 837defined$refname&&index($refname,'.') != -1&& 838$refnameeq$input_params{'hash'} && 839!defined$input_params{'snapshot_format'}) { 840# We loop over the known snapshot formats, checking for 841# extensions. Allowed extensions are both the defined suffix 842# (which includes the initial dot already) and the snapshot 843# format key itself, with a prepended dot 844while(my($fmt,$opt) =each%known_snapshot_formats) { 845my$hash=$refname; 846unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 847next; 848} 849my$sfx=$1; 850# a valid suffix was found, so set the snapshot format 851# and reset the hash parameter 852$input_params{'snapshot_format'} =$fmt; 853$input_params{'hash'} =$hash; 854# we also set the format suffix to the one requested 855# in the URL: this way a request for e.g. .tgz returns 856# a .tgz instead of a .tar.gz 857$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 858last; 859} 860} 861} 862 863our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 864$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 865$searchtext,$search_regexp); 866sub evaluate_and_validate_params { 867our$action=$input_params{'action'}; 868if(defined$action) { 869if(!validate_action($action)) { 870 die_error(400,"Invalid action parameter"); 871} 872} 873 874# parameters which are pathnames 875our$project=$input_params{'project'}; 876if(defined$project) { 877if(!validate_project($project)) { 878undef$project; 879 die_error(404,"No such project"); 880} 881} 882 883our$file_name=$input_params{'file_name'}; 884if(defined$file_name) { 885if(!validate_pathname($file_name)) { 886 die_error(400,"Invalid file parameter"); 887} 888} 889 890our$file_parent=$input_params{'file_parent'}; 891if(defined$file_parent) { 892if(!validate_pathname($file_parent)) { 893 die_error(400,"Invalid file parent parameter"); 894} 895} 896 897# parameters which are refnames 898our$hash=$input_params{'hash'}; 899if(defined$hash) { 900if(!validate_refname($hash)) { 901 die_error(400,"Invalid hash parameter"); 902} 903} 904 905our$hash_parent=$input_params{'hash_parent'}; 906if(defined$hash_parent) { 907if(!validate_refname($hash_parent)) { 908 die_error(400,"Invalid hash parent parameter"); 909} 910} 911 912our$hash_base=$input_params{'hash_base'}; 913if(defined$hash_base) { 914if(!validate_refname($hash_base)) { 915 die_error(400,"Invalid hash base parameter"); 916} 917} 918 919our@extra_options= @{$input_params{'extra_options'}}; 920# @extra_options is always defined, since it can only be (currently) set from 921# CGI, and $cgi->param() returns the empty array in array context if the param 922# is not set 923foreachmy$opt(@extra_options) { 924if(not exists$allowed_options{$opt}) { 925 die_error(400,"Invalid option parameter"); 926} 927if(not grep(/^$action$/, @{$allowed_options{$opt}})) { 928 die_error(400,"Invalid option parameter for this action"); 929} 930} 931 932our$hash_parent_base=$input_params{'hash_parent_base'}; 933if(defined$hash_parent_base) { 934if(!validate_refname($hash_parent_base)) { 935 die_error(400,"Invalid hash parent base parameter"); 936} 937} 938 939# other parameters 940our$page=$input_params{'page'}; 941if(defined$page) { 942if($page=~m/[^0-9]/) { 943 die_error(400,"Invalid page parameter"); 944} 945} 946 947our$searchtype=$input_params{'searchtype'}; 948if(defined$searchtype) { 949if($searchtype=~m/[^a-z]/) { 950 die_error(400,"Invalid searchtype parameter"); 951} 952} 953 954our$search_use_regexp=$input_params{'search_use_regexp'}; 955 956our$searchtext=$input_params{'searchtext'}; 957our$search_regexp; 958if(defined$searchtext) { 959if(length($searchtext) <2) { 960 die_error(403,"At least two characters are required for search parameter"); 961} 962$search_regexp=$search_use_regexp?$searchtext:quotemeta$searchtext; 963} 964} 965 966# path to the current git repository 967our$git_dir; 968sub evaluate_git_dir { 969our$git_dir="$projectroot/$project"if$project; 970} 971 972our(@snapshot_fmts,$git_avatar); 973sub configure_gitweb_features { 974# list of supported snapshot formats 975our@snapshot_fmts= gitweb_get_feature('snapshot'); 976@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts); 977 978# check that the avatar feature is set to a known provider name, 979# and for each provider check if the dependencies are satisfied. 980# if the provider name is invalid or the dependencies are not met, 981# reset $git_avatar to the empty string. 982our($git_avatar) = gitweb_get_feature('avatar'); 983if($git_avatareq'gravatar') { 984$git_avatar=''unless(eval{require Digest::MD5;1; }); 985}elsif($git_avatareq'picon') { 986# no dependencies 987}else{ 988$git_avatar=''; 989} 990} 991 992# custom error handler: 'die <message>' is Internal Server Error 993sub handle_errors_html { 994my$msg=shift;# it is already HTML escaped 995 996# to avoid infinite loop where error occurs in die_error, 997# change handler to default handler, disabling handle_errors_html 998 set_message("Error occured when inside die_error:\n$msg"); 9991000# you cannot jump out of die_error when called as error handler;1001# the subroutine set via CGI::Carp::set_message is called _after_1002# HTTP headers are already written, so it cannot write them itself1003 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1004}1005set_message(\&handle_errors_html);10061007# dispatch1008sub dispatch {1009if(!defined$action) {1010if(defined$hash) {1011$action= git_get_type($hash);1012}elsif(defined$hash_base&&defined$file_name) {1013$action= git_get_type("$hash_base:$file_name");1014}elsif(defined$project) {1015$action='summary';1016}else{1017$action='project_list';1018}1019}1020if(!defined($actions{$action})) {1021 die_error(400,"Unknown action");1022}1023if($action!~m/^(?:opml|project_list|project_index)$/&&1024!$project) {1025 die_error(400,"Project needed");1026}1027$actions{$action}->();1028}10291030sub reset_timer {1031our$t0= [Time::HiRes::gettimeofday()]1032ifdefined$t0;1033our$number_of_git_cmds=0;1034}10351036sub run_request {1037 reset_timer();10381039 evaluate_uri();1040 check_loadavg();10411042 evaluate_query_params();1043 evaluate_path_info();1044 evaluate_and_validate_params();1045 evaluate_git_dir();10461047 configure_gitweb_features();10481049 dispatch();1050}10511052our$is_last_request=sub{1};1053our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1054our$CGI='CGI';1055our$cgi;1056sub configure_as_fcgi {1057require CGI::Fast;1058our$CGI='CGI::Fast';10591060my$request_number=0;1061# let each child service 100 requests1062our$is_last_request=sub{ ++$request_number>100};1063}1064sub evaluate_argv {1065my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1066 configure_as_fcgi()1067if$script_name=~/\.fcgi$/;10681069return unless(@ARGV);10701071require Getopt::Long;1072 Getopt::Long::GetOptions(1073'fastcgi|fcgi|f'=> \&configure_as_fcgi,1074'nproc|n=i'=>sub{1075my($arg,$val) =@_;1076return unlesseval{require FCGI::ProcManager;1; };1077my$proc_manager= FCGI::ProcManager->new({1078 n_processes =>$val,1079});1080our$pre_listen_hook=sub{$proc_manager->pm_manage() };1081our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1082our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1083},1084);1085}10861087sub run {1088 evaluate_argv();1089 evaluate_gitweb_config();1090 evaluate_git_version();10911092# $projectroot and $projects_list might be set in gitweb config file1093$projects_list||=$projectroot;10941095$pre_listen_hook->()1096if$pre_listen_hook;10971098 REQUEST:1099while($cgi=$CGI->new()) {1100$pre_dispatch_hook->()1101if$pre_dispatch_hook;11021103 run_request();11041105$pre_dispatch_hook->()1106if$post_dispatch_hook;11071108last REQUEST if($is_last_request->());1109}11101111 DONE_GITWEB:11121;1113}11141115run();11161117if(defined caller) {1118# wrapped in a subroutine processing requests,1119# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1120return;1121}else{1122# pure CGI script, serving single request1123exit;1124}11251126## ======================================================================1127## action links11281129# possible values of extra options1130# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1131# -replay => 1 - start from a current view (replay with modifications)1132# -path_info => 0|1 - don't use/use path_info URL (if possible)1133sub href {1134my%params=@_;1135# default is to use -absolute url() i.e. $my_uri1136my$href=$params{-full} ?$my_url:$my_uri;11371138$params{'project'} =$projectunlessexists$params{'project'};11391140if($params{-replay}) {1141while(my($name,$symbol) =each%cgi_param_mapping) {1142if(!exists$params{$name}) {1143$params{$name} =$input_params{$name};1144}1145}1146}11471148my$use_pathinfo= gitweb_check_feature('pathinfo');1149if(defined$params{'project'} &&1150(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1151# try to put as many parameters as possible in PATH_INFO:1152# - project name1153# - action1154# - hash_parent or hash_parent_base:/file_parent1155# - hash or hash_base:/filename1156# - the snapshot_format as an appropriate suffix11571158# When the script is the root DirectoryIndex for the domain,1159# $href here would be something like http://gitweb.example.com/1160# Thus, we strip any trailing / from $href, to spare us double1161# slashes in the final URL1162$href=~ s,/$,,;11631164# Then add the project name, if present1165$href.="/".esc_url($params{'project'});1166delete$params{'project'};11671168# since we destructively absorb parameters, we keep this1169# boolean that remembers if we're handling a snapshot1170my$is_snapshot=$params{'action'}eq'snapshot';11711172# Summary just uses the project path URL, any other action is1173# added to the URL1174if(defined$params{'action'}) {1175$href.="/".esc_url($params{'action'})unless$params{'action'}eq'summary';1176delete$params{'action'};1177}11781179# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1180# stripping nonexistent or useless pieces1181$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1182||$params{'hash_parent'} ||$params{'hash'});1183if(defined$params{'hash_base'}) {1184if(defined$params{'hash_parent_base'}) {1185$href.= esc_url($params{'hash_parent_base'});1186# skip the file_parent if it's the same as the file_name1187if(defined$params{'file_parent'}) {1188if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1189delete$params{'file_parent'};1190}elsif($params{'file_parent'} !~/\.\./) {1191$href.=":/".esc_url($params{'file_parent'});1192delete$params{'file_parent'};1193}1194}1195$href.="..";1196delete$params{'hash_parent'};1197delete$params{'hash_parent_base'};1198}elsif(defined$params{'hash_parent'}) {1199$href.= esc_url($params{'hash_parent'})."..";1200delete$params{'hash_parent'};1201}12021203$href.= esc_url($params{'hash_base'});1204if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1205$href.=":/".esc_url($params{'file_name'});1206delete$params{'file_name'};1207}1208delete$params{'hash'};1209delete$params{'hash_base'};1210}elsif(defined$params{'hash'}) {1211$href.= esc_url($params{'hash'});1212delete$params{'hash'};1213}12141215# If the action was a snapshot, we can absorb the1216# snapshot_format parameter too1217if($is_snapshot) {1218my$fmt=$params{'snapshot_format'};1219# snapshot_format should always be defined when href()1220# is called, but just in case some code forgets, we1221# fall back to the default1222$fmt||=$snapshot_fmts[0];1223$href.=$known_snapshot_formats{$fmt}{'suffix'};1224delete$params{'snapshot_format'};1225}1226}12271228# now encode the parameters explicitly1229my@result= ();1230for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1231my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1232if(defined$params{$name}) {1233if(ref($params{$name})eq"ARRAY") {1234foreachmy$par(@{$params{$name}}) {1235push@result,$symbol."=". esc_param($par);1236}1237}else{1238push@result,$symbol."=". esc_param($params{$name});1239}1240}1241}1242$href.="?".join(';',@result)ifscalar@result;12431244return$href;1245}124612471248## ======================================================================1249## validation, quoting/unquoting and escaping12501251sub validate_action {1252my$input=shift||returnundef;1253returnundefunlessexists$actions{$input};1254return$input;1255}12561257sub validate_project {1258my$input=shift||returnundef;1259if(!validate_pathname($input) ||1260!(-d "$projectroot/$input") ||1261!check_export_ok("$projectroot/$input") ||1262($strict_export&& !project_in_list($input))) {1263returnundef;1264}else{1265return$input;1266}1267}12681269sub validate_pathname {1270my$input=shift||returnundef;12711272# no '.' or '..' as elements of path, i.e. no '.' nor '..'1273# at the beginning, at the end, and between slashes.1274# also this catches doubled slashes1275if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1276returnundef;1277}1278# no null characters1279if($input=~m!\0!) {1280returnundef;1281}1282return$input;1283}12841285sub validate_refname {1286my$input=shift||returnundef;12871288# textual hashes are O.K.1289if($input=~m/^[0-9a-fA-F]{40}$/) {1290return$input;1291}1292# it must be correct pathname1293$input= validate_pathname($input)1294orreturnundef;1295# restrictions on ref name according to git-check-ref-format1296if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1297returnundef;1298}1299return$input;1300}13011302# decode sequences of octets in utf8 into Perl's internal form,1303# which is utf-8 with utf8 flag set if needed. gitweb writes out1304# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1305sub to_utf8 {1306my$str=shift;1307returnundefunlessdefined$str;1308if(utf8::valid($str)) {1309 utf8::decode($str);1310return$str;1311}else{1312return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1313}1314}13151316# quote unsafe chars, but keep the slash, even when it's not1317# correct, but quoted slashes look too horrible in bookmarks1318sub esc_param {1319my$str=shift;1320returnundefunlessdefined$str;1321$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1322$str=~s/ /\+/g;1323return$str;1324}13251326# quote unsafe chars in whole URL, so some charactrs cannot be quoted1327sub esc_url {1328my$str=shift;1329returnundefunlessdefined$str;1330$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1331$str=~s/ /\+/g;1332return$str;1333}13341335# replace invalid utf8 character with SUBSTITUTION sequence1336sub esc_html {1337my$str=shift;1338my%opts=@_;13391340returnundefunlessdefined$str;13411342$str= to_utf8($str);1343$str=$cgi->escapeHTML($str);1344if($opts{'-nbsp'}) {1345$str=~s/ / /g;1346}1347$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1348return$str;1349}13501351# quote control characters and escape filename to HTML1352sub esc_path {1353my$str=shift;1354my%opts=@_;13551356returnundefunlessdefined$str;13571358$str= to_utf8($str);1359$str=$cgi->escapeHTML($str);1360if($opts{'-nbsp'}) {1361$str=~s/ / /g;1362}1363$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1364return$str;1365}13661367# Make control characters "printable", using character escape codes (CEC)1368sub quot_cec {1369my$cntrl=shift;1370my%opts=@_;1371my%es= (# character escape codes, aka escape sequences1372"\t"=>'\t',# tab (HT)1373"\n"=>'\n',# line feed (LF)1374"\r"=>'\r',# carrige return (CR)1375"\f"=>'\f',# form feed (FF)1376"\b"=>'\b',# backspace (BS)1377"\a"=>'\a',# alarm (bell) (BEL)1378"\e"=>'\e',# escape (ESC)1379"\013"=>'\v',# vertical tab (VT)1380"\000"=>'\0',# nul character (NUL)1381);1382my$chr= ( (exists$es{$cntrl})1383?$es{$cntrl}1384:sprintf('\%2x',ord($cntrl)) );1385if($opts{-nohtml}) {1386return$chr;1387}else{1388return"<span class=\"cntrl\">$chr</span>";1389}1390}13911392# Alternatively use unicode control pictures codepoints,1393# Unicode "printable representation" (PR)1394sub quot_upr {1395my$cntrl=shift;1396my%opts=@_;13971398my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1399if($opts{-nohtml}) {1400return$chr;1401}else{1402return"<span class=\"cntrl\">$chr</span>";1403}1404}14051406# git may return quoted and escaped filenames1407sub unquote {1408my$str=shift;14091410sub unq {1411my$seq=shift;1412my%es= (# character escape codes, aka escape sequences1413't'=>"\t",# tab (HT, TAB)1414'n'=>"\n",# newline (NL)1415'r'=>"\r",# return (CR)1416'f'=>"\f",# form feed (FF)1417'b'=>"\b",# backspace (BS)1418'a'=>"\a",# alarm (bell) (BEL)1419'e'=>"\e",# escape (ESC)1420'v'=>"\013",# vertical tab (VT)1421);14221423if($seq=~m/^[0-7]{1,3}$/) {1424# octal char sequence1425returnchr(oct($seq));1426}elsif(exists$es{$seq}) {1427# C escape sequence, aka character escape code1428return$es{$seq};1429}1430# quoted ordinary character1431return$seq;1432}14331434if($str=~m/^"(.*)"$/) {1435# needs unquoting1436$str=$1;1437$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1438}1439return$str;1440}14411442# escape tabs (convert tabs to spaces)1443sub untabify {1444my$line=shift;14451446while((my$pos=index($line,"\t")) != -1) {1447if(my$count= (8- ($pos%8))) {1448my$spaces=' ' x $count;1449$line=~s/\t/$spaces/;1450}1451}14521453return$line;1454}14551456sub project_in_list {1457my$project=shift;1458my@list= git_get_projects_list();1459return@list&&scalar(grep{$_->{'path'}eq$project}@list);1460}14611462## ----------------------------------------------------------------------1463## HTML aware string manipulation14641465# Try to chop given string on a word boundary between position1466# $len and $len+$add_len. If there is no word boundary there,1467# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1468# (marking chopped part) would be longer than given string.1469sub chop_str {1470my$str=shift;1471my$len=shift;1472my$add_len=shift||10;1473my$where=shift||'right';# 'left' | 'center' | 'right'14741475# Make sure perl knows it is utf8 encoded so we don't1476# cut in the middle of a utf8 multibyte char.1477$str= to_utf8($str);14781479# allow only $len chars, but don't cut a word if it would fit in $add_len1480# if it doesn't fit, cut it if it's still longer than the dots we would add1481# remove chopped character entities entirely14821483# when chopping in the middle, distribute $len into left and right part1484# return early if chopping wouldn't make string shorter1485if($whereeq'center') {1486return$strif($len+5>=length($str));# filler is length 51487$len=int($len/2);1488}else{1489return$strif($len+4>=length($str));# filler is length 41490}14911492# regexps: ending and beginning with word part up to $add_len1493my$endre=qr/.{$len}\w{0,$add_len}/;1494my$begre=qr/\w{0,$add_len}.{$len}/;14951496if($whereeq'left') {1497$str=~m/^(.*?)($begre)$/;1498my($lead,$body) = ($1,$2);1499if(length($lead) >4) {1500$lead=" ...";1501}1502return"$lead$body";15031504}elsif($whereeq'center') {1505$str=~m/^($endre)(.*)$/;1506my($left,$str) = ($1,$2);1507$str=~m/^(.*?)($begre)$/;1508my($mid,$right) = ($1,$2);1509if(length($mid) >5) {1510$mid=" ... ";1511}1512return"$left$mid$right";15131514}else{1515$str=~m/^($endre)(.*)$/;1516my$body=$1;1517my$tail=$2;1518if(length($tail) >4) {1519$tail="... ";1520}1521return"$body$tail";1522}1523}15241525# takes the same arguments as chop_str, but also wraps a <span> around the1526# result with a title attribute if it does get chopped. Additionally, the1527# string is HTML-escaped.1528sub chop_and_escape_str {1529my($str) =@_;15301531my$chopped= chop_str(@_);1532if($choppedeq$str) {1533return esc_html($chopped);1534}else{1535$str=~s/[[:cntrl:]]/?/g;1536return$cgi->span({-title=>$str}, esc_html($chopped));1537}1538}15391540## ----------------------------------------------------------------------1541## functions returning short strings15421543# CSS class for given age value (in seconds)1544sub age_class {1545my$age=shift;15461547if(!defined$age) {1548return"noage";1549}elsif($age<60*60*2) {1550return"age0";1551}elsif($age<60*60*24*2) {1552return"age1";1553}else{1554return"age2";1555}1556}15571558# convert age in seconds to "nn units ago" string1559sub age_string {1560my$age=shift;1561my$age_str;15621563if($age>60*60*24*365*2) {1564$age_str= (int$age/60/60/24/365);1565$age_str.=" years ago";1566}elsif($age>60*60*24*(365/12)*2) {1567$age_str=int$age/60/60/24/(365/12);1568$age_str.=" months ago";1569}elsif($age>60*60*24*7*2) {1570$age_str=int$age/60/60/24/7;1571$age_str.=" weeks ago";1572}elsif($age>60*60*24*2) {1573$age_str=int$age/60/60/24;1574$age_str.=" days ago";1575}elsif($age>60*60*2) {1576$age_str=int$age/60/60;1577$age_str.=" hours ago";1578}elsif($age>60*2) {1579$age_str=int$age/60;1580$age_str.=" min ago";1581}elsif($age>2) {1582$age_str=int$age;1583$age_str.=" sec ago";1584}else{1585$age_str.=" right now";1586}1587return$age_str;1588}15891590useconstant{1591 S_IFINVALID =>0030000,1592 S_IFGITLINK =>0160000,1593};15941595# submodule/subproject, a commit object reference1596sub S_ISGITLINK {1597my$mode=shift;15981599return(($mode& S_IFMT) == S_IFGITLINK)1600}16011602# convert file mode in octal to symbolic file mode string1603sub mode_str {1604my$mode=oct shift;16051606if(S_ISGITLINK($mode)) {1607return'm---------';1608}elsif(S_ISDIR($mode& S_IFMT)) {1609return'drwxr-xr-x';1610}elsif(S_ISLNK($mode)) {1611return'lrwxrwxrwx';1612}elsif(S_ISREG($mode)) {1613# git cares only about the executable bit1614if($mode& S_IXUSR) {1615return'-rwxr-xr-x';1616}else{1617return'-rw-r--r--';1618};1619}else{1620return'----------';1621}1622}16231624# convert file mode in octal to file type string1625sub file_type {1626my$mode=shift;16271628if($mode!~m/^[0-7]+$/) {1629return$mode;1630}else{1631$mode=oct$mode;1632}16331634if(S_ISGITLINK($mode)) {1635return"submodule";1636}elsif(S_ISDIR($mode& S_IFMT)) {1637return"directory";1638}elsif(S_ISLNK($mode)) {1639return"symlink";1640}elsif(S_ISREG($mode)) {1641return"file";1642}else{1643return"unknown";1644}1645}16461647# convert file mode in octal to file type description string1648sub file_type_long {1649my$mode=shift;16501651if($mode!~m/^[0-7]+$/) {1652return$mode;1653}else{1654$mode=oct$mode;1655}16561657if(S_ISGITLINK($mode)) {1658return"submodule";1659}elsif(S_ISDIR($mode& S_IFMT)) {1660return"directory";1661}elsif(S_ISLNK($mode)) {1662return"symlink";1663}elsif(S_ISREG($mode)) {1664if($mode& S_IXUSR) {1665return"executable";1666}else{1667return"file";1668};1669}else{1670return"unknown";1671}1672}167316741675## ----------------------------------------------------------------------1676## functions returning short HTML fragments, or transforming HTML fragments1677## which don't belong to other sections16781679# format line of commit message.1680sub format_log_line_html {1681my$line=shift;16821683$line= esc_html($line, -nbsp=>1);1684$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1685$cgi->a({-href => href(action=>"object", hash=>$1),1686-class=>"text"},$1);1687}eg;16881689return$line;1690}16911692# format marker of refs pointing to given object16931694# the destination action is chosen based on object type and current context:1695# - for annotated tags, we choose the tag view unless it's the current view1696# already, in which case we go to shortlog view1697# - for other refs, we keep the current view if we're in history, shortlog or1698# log view, and select shortlog otherwise1699sub format_ref_marker {1700my($refs,$id) =@_;1701my$markers='';17021703if(defined$refs->{$id}) {1704foreachmy$ref(@{$refs->{$id}}) {1705# this code exploits the fact that non-lightweight tags are the1706# only indirect objects, and that they are the only objects for which1707# we want to use tag instead of shortlog as action1708my($type,$name) =qw();1709my$indirect= ($ref=~s/\^\{\}$//);1710# e.g. tags/v2.6.11 or heads/next1711if($ref=~m!^(.*?)s?/(.*)$!) {1712$type=$1;1713$name=$2;1714}else{1715$type="ref";1716$name=$ref;1717}17181719my$class=$type;1720$class.=" indirect"if$indirect;17211722my$dest_action="shortlog";17231724if($indirect) {1725$dest_action="tag"unless$actioneq"tag";1726}elsif($action=~/^(history|(short)?log)$/) {1727$dest_action=$action;1728}17291730my$dest="";1731$dest.="refs/"unless$ref=~ m!^refs/!;1732$dest.=$ref;17331734my$link=$cgi->a({1735-href => href(1736 action=>$dest_action,1737 hash=>$dest1738)},$name);17391740$markers.=" <span class=\"$class\"title=\"$ref\">".1741$link."</span>";1742}1743}17441745if($markers) {1746return' <span class="refs">'.$markers.'</span>';1747}else{1748return"";1749}1750}17511752# format, perhaps shortened and with markers, title line1753sub format_subject_html {1754my($long,$short,$href,$extra) =@_;1755$extra=''unlessdefined($extra);17561757if(length($short) <length($long)) {1758$long=~s/[[:cntrl:]]/?/g;1759return$cgi->a({-href =>$href, -class=>"list subject",1760-title => to_utf8($long)},1761 esc_html($short)) .$extra;1762}else{1763return$cgi->a({-href =>$href, -class=>"list subject"},1764 esc_html($long)) .$extra;1765}1766}17671768# Rather than recomputing the url for an email multiple times, we cache it1769# after the first hit. This gives a visible benefit in views where the avatar1770# for the same email is used repeatedly (e.g. shortlog).1771# The cache is shared by all avatar engines (currently gravatar only), which1772# are free to use it as preferred. Since only one avatar engine is used for any1773# given page, there's no risk for cache conflicts.1774our%avatar_cache= ();17751776# Compute the picon url for a given email, by using the picon search service over at1777# http://www.cs.indiana.edu/picons/search.html1778sub picon_url {1779my$email=lc shift;1780if(!$avatar_cache{$email}) {1781my($user,$domain) =split('@',$email);1782$avatar_cache{$email} =1783"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1784"$domain/$user/".1785"users+domains+unknown/up/single";1786}1787return$avatar_cache{$email};1788}17891790# Compute the gravatar url for a given email, if it's not in the cache already.1791# Gravatar stores only the part of the URL before the size, since that's the1792# one computationally more expensive. This also allows reuse of the cache for1793# different sizes (for this particular engine).1794sub gravatar_url {1795my$email=lc shift;1796my$size=shift;1797$avatar_cache{$email} ||=1798"http://www.gravatar.com/avatar/".1799 Digest::MD5::md5_hex($email) ."?s=";1800return$avatar_cache{$email} .$size;1801}18021803# Insert an avatar for the given $email at the given $size if the feature1804# is enabled.1805sub git_get_avatar {1806my($email,%opts) =@_;1807my$pre_white= ($opts{-pad_before} ?" ":"");1808my$post_white= ($opts{-pad_after} ?" ":"");1809$opts{-size} ||='default';1810my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1811my$url="";1812if($git_avatareq'gravatar') {1813$url= gravatar_url($email,$size);1814}elsif($git_avatareq'picon') {1815$url= picon_url($email);1816}1817# Other providers can be added by extending the if chain, defining $url1818# as needed. If no variant puts something in $url, we assume avatars1819# are completely disabled/unavailable.1820if($url) {1821return$pre_white.1822"<img width=\"$size\"".1823"class=\"avatar\"".1824"src=\"$url\"".1825"alt=\"\"".1826"/>".$post_white;1827}else{1828return"";1829}1830}18311832sub format_search_author {1833my($author,$searchtype,$displaytext) =@_;1834my$have_search= gitweb_check_feature('search');18351836if($have_search) {1837my$performed="";1838if($searchtypeeq'author') {1839$performed="authored";1840}elsif($searchtypeeq'committer') {1841$performed="committed";1842}18431844return$cgi->a({-href => href(action=>"search", hash=>$hash,1845 searchtext=>$author,1846 searchtype=>$searchtype),class=>"list",1847 title=>"Search for commits$performedby$author"},1848$displaytext);18491850}else{1851return$displaytext;1852}1853}18541855# format the author name of the given commit with the given tag1856# the author name is chopped and escaped according to the other1857# optional parameters (see chop_str).1858sub format_author_html {1859my$tag=shift;1860my$co=shift;1861my$author= chop_and_escape_str($co->{'author_name'},@_);1862return"<$tagclass=\"author\">".1863 format_search_author($co->{'author_name'},"author",1864 git_get_avatar($co->{'author_email'}, -pad_after =>1) .1865$author) .1866"</$tag>";1867}18681869# format git diff header line, i.e. "diff --(git|combined|cc) ..."1870sub format_git_diff_header_line {1871my$line=shift;1872my$diffinfo=shift;1873my($from,$to) =@_;18741875if($diffinfo->{'nparents'}) {1876# combined diff1877$line=~s!^(diff (.*?) )"?.*$!$1!;1878if($to->{'href'}) {1879$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1880 esc_path($to->{'file'}));1881}else{# file was deleted (no href)1882$line.= esc_path($to->{'file'});1883}1884}else{1885# "ordinary" diff1886$line=~s!^(diff (.*?) )"?a/.*$!$1!;1887if($from->{'href'}) {1888$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},1889'a/'. esc_path($from->{'file'}));1890}else{# file was added (no href)1891$line.='a/'. esc_path($from->{'file'});1892}1893$line.=' ';1894if($to->{'href'}) {1895$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1896'b/'. esc_path($to->{'file'}));1897}else{# file was deleted1898$line.='b/'. esc_path($to->{'file'});1899}1900}19011902return"<div class=\"diff header\">$line</div>\n";1903}19041905# format extended diff header line, before patch itself1906sub format_extended_diff_header_line {1907my$line=shift;1908my$diffinfo=shift;1909my($from,$to) =@_;19101911# match <path>1912if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {1913$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},1914 esc_path($from->{'file'}));1915}1916if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {1917$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},1918 esc_path($to->{'file'}));1919}1920# match single <mode>1921if($line=~m/\s(\d{6})$/) {1922$line.='<span class="info"> ('.1923 file_type_long($1) .1924')</span>';1925}1926# match <hash>1927if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {1928# can match only for combined diff1929$line='index ';1930for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {1931if($from->{'href'}[$i]) {1932$line.=$cgi->a({-href=>$from->{'href'}[$i],1933-class=>"hash"},1934substr($diffinfo->{'from_id'}[$i],0,7));1935}else{1936$line.='0' x 7;1937}1938# separator1939$line.=','if($i<$diffinfo->{'nparents'} -1);1940}1941$line.='..';1942if($to->{'href'}) {1943$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},1944substr($diffinfo->{'to_id'},0,7));1945}else{1946$line.='0' x 7;1947}19481949}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {1950# can match only for ordinary diff1951my($from_link,$to_link);1952if($from->{'href'}) {1953$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},1954substr($diffinfo->{'from_id'},0,7));1955}else{1956$from_link='0' x 7;1957}1958if($to->{'href'}) {1959$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},1960substr($diffinfo->{'to_id'},0,7));1961}else{1962$to_link='0' x 7;1963}1964my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});1965$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;1966}19671968return$line."<br/>\n";1969}19701971# format from-file/to-file diff header1972sub format_diff_from_to_header {1973my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;1974my$line;1975my$result='';19761977$line=$from_line;1978#assert($line =~ m/^---/) if DEBUG;1979# no extra formatting for "^--- /dev/null"1980if(!$diffinfo->{'nparents'}) {1981# ordinary (single parent) diff1982if($line=~m!^--- "?a/!) {1983if($from->{'href'}) {1984$line='--- a/'.1985$cgi->a({-href=>$from->{'href'}, -class=>"path"},1986 esc_path($from->{'file'}));1987}else{1988$line='--- a/'.1989 esc_path($from->{'file'});1990}1991}1992$result.= qq!<div class="diff from_file">$line</div>\n!;19931994}else{1995# combined diff (merge commit)1996for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {1997if($from->{'href'}[$i]) {1998$line='--- '.1999$cgi->a({-href=>href(action=>"blobdiff",2000 hash_parent=>$diffinfo->{'from_id'}[$i],2001 hash_parent_base=>$parents[$i],2002 file_parent=>$from->{'file'}[$i],2003 hash=>$diffinfo->{'to_id'},2004 hash_base=>$hash,2005 file_name=>$to->{'file'}),2006-class=>"path",2007-title=>"diff". ($i+1)},2008$i+1) .2009'/'.2010$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2011 esc_path($from->{'file'}[$i]));2012}else{2013$line='--- /dev/null';2014}2015$result.= qq!<div class="diff from_file">$line</div>\n!;2016}2017}20182019$line=$to_line;2020#assert($line =~ m/^\+\+\+/) if DEBUG;2021# no extra formatting for "^+++ /dev/null"2022if($line=~m!^\+\+\+ "?b/!) {2023if($to->{'href'}) {2024$line='+++ b/'.2025$cgi->a({-href=>$to->{'href'}, -class=>"path"},2026 esc_path($to->{'file'}));2027}else{2028$line='+++ b/'.2029 esc_path($to->{'file'});2030}2031}2032$result.= qq!<div class="diff to_file">$line</div>\n!;20332034return$result;2035}20362037# create note for patch simplified by combined diff2038sub format_diff_cc_simplified {2039my($diffinfo,@parents) =@_;2040my$result='';20412042$result.="<div class=\"diff header\">".2043"diff --cc ";2044if(!is_deleted($diffinfo)) {2045$result.=$cgi->a({-href => href(action=>"blob",2046 hash_base=>$hash,2047 hash=>$diffinfo->{'to_id'},2048 file_name=>$diffinfo->{'to_file'}),2049-class=>"path"},2050 esc_path($diffinfo->{'to_file'}));2051}else{2052$result.= esc_path($diffinfo->{'to_file'});2053}2054$result.="</div>\n".# class="diff header"2055"<div class=\"diff nodifferences\">".2056"Simple merge".2057"</div>\n";# class="diff nodifferences"20582059return$result;2060}20612062# format patch (diff) line (not to be used for diff headers)2063sub format_diff_line {2064my$line=shift;2065my($from,$to) =@_;2066my$diff_class="";20672068chomp$line;20692070if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2071# combined diff2072my$prefix=substr($line,0,scalar@{$from->{'href'}});2073if($line=~m/^\@{3}/) {2074$diff_class=" chunk_header";2075}elsif($line=~m/^\\/) {2076$diff_class=" incomplete";2077}elsif($prefix=~tr/+/+/) {2078$diff_class=" add";2079}elsif($prefix=~tr/-/-/) {2080$diff_class=" rem";2081}2082}else{2083# assume ordinary diff2084my$char=substr($line,0,1);2085if($chareq'+') {2086$diff_class=" add";2087}elsif($chareq'-') {2088$diff_class=" rem";2089}elsif($chareq'@') {2090$diff_class=" chunk_header";2091}elsif($chareq"\\") {2092$diff_class=" incomplete";2093}2094}2095$line= untabify($line);2096if($from&&$to&&$line=~m/^\@{2} /) {2097my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2098$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;20992100$from_lines=0unlessdefined$from_lines;2101$to_lines=0unlessdefined$to_lines;21022103if($from->{'href'}) {2104$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2105-class=>"list"},$from_text);2106}2107if($to->{'href'}) {2108$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2109-class=>"list"},$to_text);2110}2111$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2112"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2113return"<div class=\"diff$diff_class\">$line</div>\n";2114}elsif($from&&$to&&$line=~m/^\@{3}/) {2115my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2116my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);21172118@from_text=split(' ',$ranges);2119for(my$i=0;$i<@from_text; ++$i) {2120($from_start[$i],$from_nlines[$i]) =2121(split(',',substr($from_text[$i],1)),0);2122}21232124$to_text=pop@from_text;2125$to_start=pop@from_start;2126$to_nlines=pop@from_nlines;21272128$line="<span class=\"chunk_info\">$prefix";2129for(my$i=0;$i<@from_text; ++$i) {2130if($from->{'href'}[$i]) {2131$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2132-class=>"list"},$from_text[$i]);2133}else{2134$line.=$from_text[$i];2135}2136$line.=" ";2137}2138if($to->{'href'}) {2139$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2140-class=>"list"},$to_text);2141}else{2142$line.=$to_text;2143}2144$line.="$prefix</span>".2145"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2146return"<div class=\"diff$diff_class\">$line</div>\n";2147}2148return"<div class=\"diff$diff_class\">". esc_html($line, -nbsp=>1) ."</div>\n";2149}21502151# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2152# linked. Pass the hash of the tree/commit to snapshot.2153sub format_snapshot_links {2154my($hash) =@_;2155my$num_fmts=@snapshot_fmts;2156if($num_fmts>1) {2157# A parenthesized list of links bearing format names.2158# e.g. "snapshot (_tar.gz_ _zip_)"2159return"snapshot (".join(' ',map2160$cgi->a({2161-href => href(2162 action=>"snapshot",2163 hash=>$hash,2164 snapshot_format=>$_2165)2166},$known_snapshot_formats{$_}{'display'})2167,@snapshot_fmts) .")";2168}elsif($num_fmts==1) {2169# A single "snapshot" link whose tooltip bears the format name.2170# i.e. "_snapshot_"2171my($fmt) =@snapshot_fmts;2172return2173$cgi->a({2174-href => href(2175 action=>"snapshot",2176 hash=>$hash,2177 snapshot_format=>$fmt2178),2179-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2180},"snapshot");2181}else{# $num_fmts == 02182returnundef;2183}2184}21852186## ......................................................................2187## functions returning values to be passed, perhaps after some2188## transformation, to other functions; e.g. returning arguments to href()21892190# returns hash to be passed to href to generate gitweb URL2191# in -title key it returns description of link2192sub get_feed_info {2193my$format=shift||'Atom';2194my%res= (action =>lc($format));21952196# feed links are possible only for project views2197return unless(defined$project);2198# some views should link to OPML, or to generic project feed,2199# or don't have specific feed yet (so they should use generic)2200return if($action=~/^(?:tags|heads|forks|tag|search)$/x);22012202my$branch;2203# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2204# from tag links; this also makes possible to detect branch links2205if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2206(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2207$branch=$1;2208}2209# find log type for feed description (title)2210my$type='log';2211if(defined$file_name) {2212$type="history of$file_name";2213$type.="/"if($actioneq'tree');2214$type.=" on '$branch'"if(defined$branch);2215}else{2216$type="log of$branch"if(defined$branch);2217}22182219$res{-title} =$type;2220$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2221$res{'file_name'} =$file_name;22222223return%res;2224}22252226## ----------------------------------------------------------------------2227## git utility subroutines, invoking git commands22282229# returns path to the core git executable and the --git-dir parameter as list2230sub git_cmd {2231$number_of_git_cmds++;2232return$GIT,'--git-dir='.$git_dir;2233}22342235# quote the given arguments for passing them to the shell2236# quote_command("command", "arg 1", "arg with ' and ! characters")2237# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2238# Try to avoid using this function wherever possible.2239sub quote_command {2240returnjoin(' ',2241map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2242}22432244# get HEAD ref of given project as hash2245sub git_get_head_hash {2246return git_get_full_hash(shift,'HEAD');2247}22482249sub git_get_full_hash {2250return git_get_hash(@_);2251}22522253sub git_get_short_hash {2254return git_get_hash(@_,'--short=7');2255}22562257sub git_get_hash {2258my($project,$hash,@options) =@_;2259my$o_git_dir=$git_dir;2260my$retval=undef;2261$git_dir="$projectroot/$project";2262if(open my$fd,'-|', git_cmd(),'rev-parse',2263'--verify','-q',@options,$hash) {2264$retval= <$fd>;2265chomp$retvalifdefined$retval;2266close$fd;2267}2268if(defined$o_git_dir) {2269$git_dir=$o_git_dir;2270}2271return$retval;2272}22732274# get type of given object2275sub git_get_type {2276my$hash=shift;22772278open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2279my$type= <$fd>;2280close$fdorreturn;2281chomp$type;2282return$type;2283}22842285# repository configuration2286our$config_file='';2287our%config;22882289# store multiple values for single key as anonymous array reference2290# single values stored directly in the hash, not as [ <value> ]2291sub hash_set_multi {2292my($hash,$key,$value) =@_;22932294if(!exists$hash->{$key}) {2295$hash->{$key} =$value;2296}elsif(!ref$hash->{$key}) {2297$hash->{$key} = [$hash->{$key},$value];2298}else{2299push@{$hash->{$key}},$value;2300}2301}23022303# return hash of git project configuration2304# optionally limited to some section, e.g. 'gitweb'2305sub git_parse_project_config {2306my$section_regexp=shift;2307my%config;23082309local$/="\0";23102311open my$fh,"-|", git_cmd(),"config",'-z','-l',2312orreturn;23132314while(my$keyval= <$fh>) {2315chomp$keyval;2316my($key,$value) =split(/\n/,$keyval,2);23172318 hash_set_multi(\%config,$key,$value)2319if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2320}2321close$fh;23222323return%config;2324}23252326# convert config value to boolean: 'true' or 'false'2327# no value, number > 0, 'true' and 'yes' values are true2328# rest of values are treated as false (never as error)2329sub config_to_bool {2330my$val=shift;23312332return1if!defined$val;# section.key23332334# strip leading and trailing whitespace2335$val=~s/^\s+//;2336$val=~s/\s+$//;23372338return(($val=~/^\d+$/&&$val) ||# section.key = 12339($val=~/^(?:true|yes)$/i));# section.key = true2340}23412342# convert config value to simple decimal number2343# an optional value suffix of 'k', 'm', or 'g' will cause the value2344# to be multiplied by 1024, 1048576, or 10737418242345sub config_to_int {2346my$val=shift;23472348# strip leading and trailing whitespace2349$val=~s/^\s+//;2350$val=~s/\s+$//;23512352if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2353$unit=lc($unit);2354# unknown unit is treated as 12355return$num* ($uniteq'g'?1073741824:2356$uniteq'm'?1048576:2357$uniteq'k'?1024:1);2358}2359return$val;2360}23612362# convert config value to array reference, if needed2363sub config_to_multi {2364my$val=shift;23652366returnref($val) ?$val: (defined($val) ? [$val] : []);2367}23682369sub git_get_project_config {2370my($key,$type) =@_;23712372return unlessdefined$git_dir;23732374# key sanity check2375return unless($key);2376$key=~s/^gitweb\.//;2377return if($key=~m/\W/);23782379# type sanity check2380if(defined$type) {2381$type=~s/^--//;2382$type=undef2383unless($typeeq'bool'||$typeeq'int');2384}23852386# get config2387if(!defined$config_file||2388$config_filene"$git_dir/config") {2389%config= git_parse_project_config('gitweb');2390$config_file="$git_dir/config";2391}23922393# check if config variable (key) exists2394return unlessexists$config{"gitweb.$key"};23952396# ensure given type2397if(!defined$type) {2398return$config{"gitweb.$key"};2399}elsif($typeeq'bool') {2400# backward compatibility: 'git config --bool' returns true/false2401return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2402}elsif($typeeq'int') {2403return config_to_int($config{"gitweb.$key"});2404}2405return$config{"gitweb.$key"};2406}24072408# get hash of given path at given ref2409sub git_get_hash_by_path {2410my$base=shift;2411my$path=shift||returnundef;2412my$type=shift;24132414$path=~ s,/+$,,;24152416open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2417or die_error(500,"Open git-ls-tree failed");2418my$line= <$fd>;2419close$fdorreturnundef;24202421if(!defined$line) {2422# there is no tree or hash given by $path at $base2423returnundef;2424}24252426#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2427$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2428if(defined$type&&$typene$2) {2429# type doesn't match2430returnundef;2431}2432return$3;2433}24342435# get path of entry with given hash at given tree-ish (ref)2436# used to get 'from' filename for combined diff (merge commit) for renames2437sub git_get_path_by_hash {2438my$base=shift||return;2439my$hash=shift||return;24402441local$/="\0";24422443open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2444orreturnundef;2445while(my$line= <$fd>) {2446chomp$line;24472448#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2449#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2450if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2451close$fd;2452return$1;2453}2454}2455close$fd;2456returnundef;2457}24582459## ......................................................................2460## git utility functions, directly accessing git repository24612462sub git_get_project_description {2463my$path=shift;24642465$git_dir="$projectroot/$path";2466open my$fd,'<',"$git_dir/description"2467orreturn git_get_project_config('description');2468my$descr= <$fd>;2469close$fd;2470if(defined$descr) {2471chomp$descr;2472}2473return$descr;2474}24752476sub git_get_project_ctags {2477my$path=shift;2478my$ctags= {};24792480$git_dir="$projectroot/$path";2481opendir my$dh,"$git_dir/ctags"2482orreturn$ctags;2483foreach(grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh)) {2484open my$ct,'<',$_ornext;2485my$val= <$ct>;2486chomp$val;2487close$ct;2488my$ctag=$_;$ctag=~ s#.*/##;2489$ctags->{$ctag} =$val;2490}2491closedir$dh;2492$ctags;2493}24942495sub git_populate_project_tagcloud {2496my$ctags=shift;24972498# First, merge different-cased tags; tags vote on casing2499my%ctags_lc;2500foreach(keys%$ctags) {2501$ctags_lc{lc$_}->{count} +=$ctags->{$_};2502if(not$ctags_lc{lc$_}->{topcount}2503or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2504$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2505$ctags_lc{lc$_}->{topname} =$_;2506}2507}25082509my$cloud;2510if(eval{require HTML::TagCloud;1; }) {2511$cloud= HTML::TagCloud->new;2512foreach(sort keys%ctags_lc) {2513# Pad the title with spaces so that the cloud looks2514# less crammed.2515my$title=$ctags_lc{$_}->{topname};2516$title=~s/ / /g;2517$title=~s/^/ /g;2518$title=~s/$/ /g;2519$cloud->add($title,$home_link."?by_tag=".$_,$ctags_lc{$_}->{count});2520}2521}else{2522$cloud= \%ctags_lc;2523}2524$cloud;2525}25262527sub git_show_project_tagcloud {2528my($cloud,$count) =@_;2529print STDERR ref($cloud)."..\n";2530if(ref$cloudeq'HTML::TagCloud') {2531return$cloud->html_and_css($count);2532}else{2533my@tags=sort{$cloud->{$a}->{count} <=>$cloud->{$b}->{count} }keys%$cloud;2534return'<p align="center">'.join(', ',map{2535"<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"2536}splice(@tags,0,$count)) .'</p>';2537}2538}25392540sub git_get_project_url_list {2541my$path=shift;25422543$git_dir="$projectroot/$path";2544open my$fd,'<',"$git_dir/cloneurl"2545orreturnwantarray?2546@{ config_to_multi(git_get_project_config('url')) } :2547 config_to_multi(git_get_project_config('url'));2548my@git_project_url_list=map{chomp;$_} <$fd>;2549close$fd;25502551returnwantarray?@git_project_url_list: \@git_project_url_list;2552}25532554sub git_get_projects_list {2555my($filter) =@_;2556my@list;25572558$filter||='';2559$filter=~s/\.git$//;25602561my$check_forks= gitweb_check_feature('forks');25622563if(-d $projects_list) {2564# search in directory2565my$dir=$projects_list. ($filter?"/$filter":'');2566# remove the trailing "/"2567$dir=~s!/+$!!;2568my$pfxlen=length("$dir");2569my$pfxdepth= ($dir=~tr!/!!);25702571 File::Find::find({2572 follow_fast =>1,# follow symbolic links2573 follow_skip =>2,# ignore duplicates2574 dangling_symlinks =>0,# ignore dangling symlinks, silently2575 wanted =>sub{2576# global variables2577our$project_maxdepth;2578our$projectroot;2579# skip project-list toplevel, if we get it.2580return if(m!^[/.]$!);2581# only directories can be git repositories2582return unless(-d $_);2583# don't traverse too deep (Find is super slow on os x)2584if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2585$File::Find::prune =1;2586return;2587}25882589my$subdir=substr($File::Find::name,$pfxlen+1);2590# we check related file in $projectroot2591my$path= ($filter?"$filter/":'') .$subdir;2592if(check_export_ok("$projectroot/$path")) {2593push@list, { path =>$path};2594$File::Find::prune =1;2595}2596},2597},"$dir");25982599}elsif(-f $projects_list) {2600# read from file(url-encoded):2601# 'git%2Fgit.git Linus+Torvalds'2602# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2603# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2604my%paths;2605open my$fd,'<',$projects_listorreturn;2606 PROJECT:2607while(my$line= <$fd>) {2608chomp$line;2609my($path,$owner) =split' ',$line;2610$path= unescape($path);2611$owner= unescape($owner);2612if(!defined$path) {2613next;2614}2615if($filterne'') {2616# looking for forks;2617my$pfx=substr($path,0,length($filter));2618if($pfxne$filter) {2619next PROJECT;2620}2621my$sfx=substr($path,length($filter));2622if($sfx!~/^\/.*\.git$/) {2623next PROJECT;2624}2625}elsif($check_forks) {2626 PATH:2627foreachmy$filter(keys%paths) {2628# looking for forks;2629my$pfx=substr($path,0,length($filter));2630if($pfxne$filter) {2631next PATH;2632}2633my$sfx=substr($path,length($filter));2634if($sfx!~/^\/.*\.git$/) {2635next PATH;2636}2637# is a fork, don't include it in2638# the list2639next PROJECT;2640}2641}2642if(check_export_ok("$projectroot/$path")) {2643my$pr= {2644 path =>$path,2645 owner => to_utf8($owner),2646};2647push@list,$pr;2648(my$forks_path=$path) =~s/\.git$//;2649$paths{$forks_path}++;2650}2651}2652close$fd;2653}2654return@list;2655}26562657our$gitweb_project_owner=undef;2658sub git_get_project_list_from_file {26592660return if(defined$gitweb_project_owner);26612662$gitweb_project_owner= {};2663# read from file (url-encoded):2664# 'git%2Fgit.git Linus+Torvalds'2665# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2666# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2667if(-f $projects_list) {2668open(my$fd,'<',$projects_list);2669while(my$line= <$fd>) {2670chomp$line;2671my($pr,$ow) =split' ',$line;2672$pr= unescape($pr);2673$ow= unescape($ow);2674$gitweb_project_owner->{$pr} = to_utf8($ow);2675}2676close$fd;2677}2678}26792680sub git_get_project_owner {2681my$project=shift;2682my$owner;26832684returnundefunless$project;2685$git_dir="$projectroot/$project";26862687if(!defined$gitweb_project_owner) {2688 git_get_project_list_from_file();2689}26902691if(exists$gitweb_project_owner->{$project}) {2692$owner=$gitweb_project_owner->{$project};2693}2694if(!defined$owner){2695$owner= git_get_project_config('owner');2696}2697if(!defined$owner) {2698$owner= get_file_owner("$git_dir");2699}27002701return$owner;2702}27032704sub git_get_last_activity {2705my($path) =@_;2706my$fd;27072708$git_dir="$projectroot/$path";2709open($fd,"-|", git_cmd(),'for-each-ref',2710'--format=%(committer)',2711'--sort=-committerdate',2712'--count=1',2713'refs/heads')orreturn;2714my$most_recent= <$fd>;2715close$fdorreturn;2716if(defined$most_recent&&2717$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {2718my$timestamp=$1;2719my$age=time-$timestamp;2720return($age, age_string($age));2721}2722return(undef,undef);2723}27242725sub git_get_references {2726my$type=shift||"";2727my%refs;2728# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.112729# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}2730open my$fd,"-|", git_cmd(),"show-ref","--dereference",2731($type? ("--","refs/$type") : ())# use -- <pattern> if $type2732orreturn;27332734while(my$line= <$fd>) {2735chomp$line;2736if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {2737if(defined$refs{$1}) {2738push@{$refs{$1}},$2;2739}else{2740$refs{$1} = [$2];2741}2742}2743}2744close$fdorreturn;2745return \%refs;2746}27472748sub git_get_rev_name_tags {2749my$hash=shift||returnundef;27502751open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash2752orreturn;2753my$name_rev= <$fd>;2754close$fd;27552756if($name_rev=~ m|^$hash tags/(.*)$|) {2757return$1;2758}else{2759# catches also '$hash undefined' output2760returnundef;2761}2762}27632764## ----------------------------------------------------------------------2765## parse to hash functions27662767sub parse_date {2768my$epoch=shift;2769my$tz=shift||"-0000";27702771my%date;2772my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");2773my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");2774my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);2775$date{'hour'} =$hour;2776$date{'minute'} =$min;2777$date{'mday'} =$mday;2778$date{'day'} =$days[$wday];2779$date{'month'} =$months[$mon];2780$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",2781$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;2782$date{'mday-time'} =sprintf"%d%s%02d:%02d",2783$mday,$months[$mon],$hour,$min;2784$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",27851900+$year,1+$mon,$mday,$hour,$min,$sec;27862787$tz=~m/^([+\-][0-9][0-9])([0-9][0-9])$/;2788my$local=$epoch+ ((int$1+ ($2/60)) *3600);2789($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);2790$date{'hour_local'} =$hour;2791$date{'minute_local'} =$min;2792$date{'tz_local'} =$tz;2793$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",27941900+$year,$mon+1,$mday,2795$hour,$min,$sec,$tz);2796return%date;2797}27982799sub parse_tag {2800my$tag_id=shift;2801my%tag;2802my@comment;28032804open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;2805$tag{'id'} =$tag_id;2806while(my$line= <$fd>) {2807chomp$line;2808if($line=~m/^object ([0-9a-fA-F]{40})$/) {2809$tag{'object'} =$1;2810}elsif($line=~m/^type (.+)$/) {2811$tag{'type'} =$1;2812}elsif($line=~m/^tag (.+)$/) {2813$tag{'name'} =$1;2814}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {2815$tag{'author'} =$1;2816$tag{'author_epoch'} =$2;2817$tag{'author_tz'} =$3;2818if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {2819$tag{'author_name'} =$1;2820$tag{'author_email'} =$2;2821}else{2822$tag{'author_name'} =$tag{'author'};2823}2824}elsif($line=~m/--BEGIN/) {2825push@comment,$line;2826last;2827}elsif($lineeq"") {2828last;2829}2830}2831push@comment, <$fd>;2832$tag{'comment'} = \@comment;2833close$fdorreturn;2834if(!defined$tag{'name'}) {2835return2836};2837return%tag2838}28392840sub parse_commit_text {2841my($commit_text,$withparents) =@_;2842my@commit_lines=split'\n',$commit_text;2843my%co;28442845pop@commit_lines;# Remove '\0'28462847if(!@commit_lines) {2848return;2849}28502851my$header=shift@commit_lines;2852if($header!~m/^[0-9a-fA-F]{40}/) {2853return;2854}2855($co{'id'},my@parents) =split' ',$header;2856while(my$line=shift@commit_lines) {2857last if$lineeq"\n";2858if($line=~m/^tree ([0-9a-fA-F]{40})$/) {2859$co{'tree'} =$1;2860}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {2861push@parents,$1;2862}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {2863$co{'author'} = to_utf8($1);2864$co{'author_epoch'} =$2;2865$co{'author_tz'} =$3;2866if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {2867$co{'author_name'} =$1;2868$co{'author_email'} =$2;2869}else{2870$co{'author_name'} =$co{'author'};2871}2872}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {2873$co{'committer'} = to_utf8($1);2874$co{'committer_epoch'} =$2;2875$co{'committer_tz'} =$3;2876if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {2877$co{'committer_name'} =$1;2878$co{'committer_email'} =$2;2879}else{2880$co{'committer_name'} =$co{'committer'};2881}2882}2883}2884if(!defined$co{'tree'}) {2885return;2886};2887$co{'parents'} = \@parents;2888$co{'parent'} =$parents[0];28892890foreachmy$title(@commit_lines) {2891$title=~s/^ //;2892if($titlene"") {2893$co{'title'} = chop_str($title,80,5);2894# remove leading stuff of merges to make the interesting part visible2895if(length($title) >50) {2896$title=~s/^Automatic //;2897$title=~s/^merge (of|with) /Merge ... /i;2898if(length($title) >50) {2899$title=~s/(http|rsync):\/\///;2900}2901if(length($title) >50) {2902$title=~s/(master|www|rsync)\.//;2903}2904if(length($title) >50) {2905$title=~s/kernel.org:?//;2906}2907if(length($title) >50) {2908$title=~s/\/pub\/scm//;2909}2910}2911$co{'title_short'} = chop_str($title,50,5);2912last;2913}2914}2915if(!defined$co{'title'} ||$co{'title'}eq"") {2916$co{'title'} =$co{'title_short'} ='(no commit message)';2917}2918# remove added spaces2919foreachmy$line(@commit_lines) {2920$line=~s/^ //;2921}2922$co{'comment'} = \@commit_lines;29232924my$age=time-$co{'committer_epoch'};2925$co{'age'} =$age;2926$co{'age_string'} = age_string($age);2927my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});2928if($age>60*60*24*7*2) {2929$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;2930$co{'age_string_age'} =$co{'age_string'};2931}else{2932$co{'age_string_date'} =$co{'age_string'};2933$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;2934}2935return%co;2936}29372938sub parse_commit {2939my($commit_id) =@_;2940my%co;29412942local$/="\0";29432944open my$fd,"-|", git_cmd(),"rev-list",2945"--parents",2946"--header",2947"--max-count=1",2948$commit_id,2949"--",2950or die_error(500,"Open git-rev-list failed");2951%co= parse_commit_text(<$fd>,1);2952close$fd;29532954return%co;2955}29562957sub parse_commits {2958my($commit_id,$maxcount,$skip,$filename,@args) =@_;2959my@cos;29602961$maxcount||=1;2962$skip||=0;29632964local$/="\0";29652966open my$fd,"-|", git_cmd(),"rev-list",2967"--header",2968@args,2969("--max-count=".$maxcount),2970("--skip=".$skip),2971@extra_options,2972$commit_id,2973"--",2974($filename? ($filename) : ())2975or die_error(500,"Open git-rev-list failed");2976while(my$line= <$fd>) {2977my%co= parse_commit_text($line);2978push@cos, \%co;2979}2980close$fd;29812982returnwantarray?@cos: \@cos;2983}29842985# parse line of git-diff-tree "raw" output2986sub parse_difftree_raw_line {2987my$line=shift;2988my%res;29892990# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'2991# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'2992if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {2993$res{'from_mode'} =$1;2994$res{'to_mode'} =$2;2995$res{'from_id'} =$3;2996$res{'to_id'} =$4;2997$res{'status'} =$5;2998$res{'similarity'} =$6;2999if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3000($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3001}else{3002$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3003}3004}3005# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3006# combined diff (for merge commit)3007elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3008$res{'nparents'} =length($1);3009$res{'from_mode'} = [split(' ',$2) ];3010$res{'to_mode'} =pop@{$res{'from_mode'}};3011$res{'from_id'} = [split(' ',$3) ];3012$res{'to_id'} =pop@{$res{'from_id'}};3013$res{'status'} = [split('',$4) ];3014$res{'to_file'} = unquote($5);3015}3016# 'c512b523472485aef4fff9e57b229d9d243c967f'3017elsif($line=~m/^([0-9a-fA-F]{40})$/) {3018$res{'commit'} =$1;3019}30203021returnwantarray?%res: \%res;3022}30233024# wrapper: return parsed line of git-diff-tree "raw" output3025# (the argument might be raw line, or parsed info)3026sub parsed_difftree_line {3027my$line_or_ref=shift;30283029if(ref($line_or_ref)eq"HASH") {3030# pre-parsed (or generated by hand)3031return$line_or_ref;3032}else{3033return parse_difftree_raw_line($line_or_ref);3034}3035}30363037# parse line of git-ls-tree output3038sub parse_ls_tree_line {3039my$line=shift;3040my%opts=@_;3041my%res;30423043if($opts{'-l'}) {3044#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3045$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;30463047$res{'mode'} =$1;3048$res{'type'} =$2;3049$res{'hash'} =$3;3050$res{'size'} =$4;3051if($opts{'-z'}) {3052$res{'name'} =$5;3053}else{3054$res{'name'} = unquote($5);3055}3056}else{3057#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3058$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;30593060$res{'mode'} =$1;3061$res{'type'} =$2;3062$res{'hash'} =$3;3063if($opts{'-z'}) {3064$res{'name'} =$4;3065}else{3066$res{'name'} = unquote($4);3067}3068}30693070returnwantarray?%res: \%res;3071}30723073# generates _two_ hashes, references to which are passed as 2 and 3 argument3074sub parse_from_to_diffinfo {3075my($diffinfo,$from,$to,@parents) =@_;30763077if($diffinfo->{'nparents'}) {3078# combined diff3079$from->{'file'} = [];3080$from->{'href'} = [];3081 fill_from_file_info($diffinfo,@parents)3082unlessexists$diffinfo->{'from_file'};3083for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3084$from->{'file'}[$i] =3085defined$diffinfo->{'from_file'}[$i] ?3086$diffinfo->{'from_file'}[$i] :3087$diffinfo->{'to_file'};3088if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3089$from->{'href'}[$i] = href(action=>"blob",3090 hash_base=>$parents[$i],3091 hash=>$diffinfo->{'from_id'}[$i],3092 file_name=>$from->{'file'}[$i]);3093}else{3094$from->{'href'}[$i] =undef;3095}3096}3097}else{3098# ordinary (not combined) diff3099$from->{'file'} =$diffinfo->{'from_file'};3100if($diffinfo->{'status'}ne"A") {# not new (added) file3101$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3102 hash=>$diffinfo->{'from_id'},3103 file_name=>$from->{'file'});3104}else{3105delete$from->{'href'};3106}3107}31083109$to->{'file'} =$diffinfo->{'to_file'};3110if(!is_deleted($diffinfo)) {# file exists in result3111$to->{'href'} = href(action=>"blob", hash_base=>$hash,3112 hash=>$diffinfo->{'to_id'},3113 file_name=>$to->{'file'});3114}else{3115delete$to->{'href'};3116}3117}31183119## ......................................................................3120## parse to array of hashes functions31213122sub git_get_heads_list {3123my$limit=shift;3124my@headslist;31253126open my$fd,'-|', git_cmd(),'for-each-ref',3127($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3128'--format=%(objectname) %(refname) %(subject)%00%(committer)',3129'refs/heads'3130orreturn;3131while(my$line= <$fd>) {3132my%ref_item;31333134chomp$line;3135my($refinfo,$committerinfo) =split(/\0/,$line);3136my($hash,$name,$title) =split(' ',$refinfo,3);3137my($committer,$epoch,$tz) =3138($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3139$ref_item{'fullname'} =$name;3140$name=~s!^refs/heads/!!;31413142$ref_item{'name'} =$name;3143$ref_item{'id'} =$hash;3144$ref_item{'title'} =$title||'(no commit message)';3145$ref_item{'epoch'} =$epoch;3146if($epoch) {3147$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3148}else{3149$ref_item{'age'} ="unknown";3150}31513152push@headslist, \%ref_item;3153}3154close$fd;31553156returnwantarray?@headslist: \@headslist;3157}31583159sub git_get_tags_list {3160my$limit=shift;3161my@tagslist;31623163open my$fd,'-|', git_cmd(),'for-each-ref',3164($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3165'--format=%(objectname) %(objecttype) %(refname) '.3166'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3167'refs/tags'3168orreturn;3169while(my$line= <$fd>) {3170my%ref_item;31713172chomp$line;3173my($refinfo,$creatorinfo) =split(/\0/,$line);3174my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3175my($creator,$epoch,$tz) =3176($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3177$ref_item{'fullname'} =$name;3178$name=~s!^refs/tags/!!;31793180$ref_item{'type'} =$type;3181$ref_item{'id'} =$id;3182$ref_item{'name'} =$name;3183if($typeeq"tag") {3184$ref_item{'subject'} =$title;3185$ref_item{'reftype'} =$reftype;3186$ref_item{'refid'} =$refid;3187}else{3188$ref_item{'reftype'} =$type;3189$ref_item{'refid'} =$id;3190}31913192if($typeeq"tag"||$typeeq"commit") {3193$ref_item{'epoch'} =$epoch;3194if($epoch) {3195$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3196}else{3197$ref_item{'age'} ="unknown";3198}3199}32003201push@tagslist, \%ref_item;3202}3203close$fd;32043205returnwantarray?@tagslist: \@tagslist;3206}32073208## ----------------------------------------------------------------------3209## filesystem-related functions32103211sub get_file_owner {3212my$path=shift;32133214my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3215my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3216if(!defined$gcos) {3217returnundef;3218}3219my$owner=$gcos;3220$owner=~s/[,;].*$//;3221return to_utf8($owner);3222}32233224# assume that file exists3225sub insert_file {3226my$filename=shift;32273228open my$fd,'<',$filename;3229print map{ to_utf8($_) } <$fd>;3230close$fd;3231}32323233## ......................................................................3234## mimetype related functions32353236sub mimetype_guess_file {3237my$filename=shift;3238my$mimemap=shift;3239-r $mimemaporreturnundef;32403241my%mimemap;3242open(my$mh,'<',$mimemap)orreturnundef;3243while(<$mh>) {3244next ifm/^#/;# skip comments3245my($mimetype,$exts) =split(/\t+/);3246if(defined$exts) {3247my@exts=split(/\s+/,$exts);3248foreachmy$ext(@exts) {3249$mimemap{$ext} =$mimetype;3250}3251}3252}3253close($mh);32543255$filename=~/\.([^.]*)$/;3256return$mimemap{$1};3257}32583259sub mimetype_guess {3260my$filename=shift;3261my$mime;3262$filename=~/\./orreturnundef;32633264if($mimetypes_file) {3265my$file=$mimetypes_file;3266if($file!~m!^/!) {# if it is relative path3267# it is relative to project3268$file="$projectroot/$project/$file";3269}3270$mime= mimetype_guess_file($filename,$file);3271}3272$mime||= mimetype_guess_file($filename,'/etc/mime.types');3273return$mime;3274}32753276sub blob_mimetype {3277my$fd=shift;3278my$filename=shift;32793280if($filename) {3281my$mime= mimetype_guess($filename);3282$mimeandreturn$mime;3283}32843285# just in case3286return$default_blob_plain_mimetypeunless$fd;32873288if(-T $fd) {3289return'text/plain';3290}elsif(!$filename) {3291return'application/octet-stream';3292}elsif($filename=~m/\.png$/i) {3293return'image/png';3294}elsif($filename=~m/\.gif$/i) {3295return'image/gif';3296}elsif($filename=~m/\.jpe?g$/i) {3297return'image/jpeg';3298}else{3299return'application/octet-stream';3300}3301}33023303sub blob_contenttype {3304my($fd,$file_name,$type) =@_;33053306$type||= blob_mimetype($fd,$file_name);3307if($typeeq'text/plain'&&defined$default_text_plain_charset) {3308$type.="; charset=$default_text_plain_charset";3309}33103311return$type;3312}33133314# guess file syntax for syntax highlighting; return undef if no highlighting3315# the name of syntax can (in the future) depend on syntax highlighter used3316sub guess_file_syntax {3317my($highlight,$mimetype,$file_name) =@_;3318returnundefunless($highlight&&defined$file_name);33193320# configuration for 'highlight' (http://www.andre-simon.de/)3321# match by basename3322my%highlight_basename= (3323#'Program' => 'py',3324#'Library' => 'py',3325'SConstruct'=>'py',# SCons equivalent of Makefile3326'Makefile'=>'make',3327);3328# match by extension3329my%highlight_ext= (3330# main extensions, defining name of syntax;3331# see files in /usr/share/highlight/langDefs/ directory3332map{$_=>$_}3333qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl),3334# alternate extensions, see /etc/highlight/filetypes.conf3335'h'=>'c',3336map{$_=>'cpp'}qw(cxx c++ cc),3337map{$_=>'php'}qw(php3 php4),3338map{$_=>'pl'}qw(perl pm),# perhaps also 'cgi'3339'mak'=>'make',3340map{$_=>'xml'}qw(xhtml html htm),3341);33423343my$basename= basename($file_name,'.in');3344return$highlight_basename{$basename}3345ifexists$highlight_basename{$basename};33463347$basename=~/\.([^.]*)$/;3348my$ext=$1orreturnundef;3349return$highlight_ext{$ext}3350ifexists$highlight_ext{$ext};33513352returnundef;3353}33543355# run highlighter and return FD of its output,3356# or return original FD if no highlighting3357sub run_highlighter {3358my($fd,$highlight,$syntax) =@_;3359return$fdunless($highlight&&defined$syntax);33603361close$fd3362or die_error(404,"Reading blob failed");3363open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3364"highlight --xhtml --fragment --syntax$syntax|"3365or die_error(500,"Couldn't open file or run syntax highlighter");3366return$fd;3367}33683369## ======================================================================3370## functions printing HTML: header, footer, error page33713372sub get_page_title {3373my$title= to_utf8($site_name);33743375return$titleunless(defined$project);3376$title.=" - ". to_utf8($project);33773378return$titleunless(defined$action);3379$title.="/$action";# $action is US-ASCII (7bit ASCII)33803381return$titleunless(defined$file_name);3382$title.=" - ". esc_path($file_name);3383if($actioneq"tree"&&$file_name!~ m|/$|) {3384$title.="/";3385}33863387return$title;3388}33893390sub git_header_html {3391my$status=shift||"200 OK";3392my$expires=shift;3393my%opts=@_;33943395my$title= get_page_title();3396my$content_type;3397# require explicit support from the UA if we are to send the page as3398# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3399# we have to do this because MSIE sometimes globs '*/*', pretending to3400# support xhtml+xml but choking when it gets what it asked for.3401if(defined$cgi->http('HTTP_ACCEPT') &&3402$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3403$cgi->Accept('application/xhtml+xml') !=0) {3404$content_type='application/xhtml+xml';3405}else{3406$content_type='text/html';3407}3408print$cgi->header(-type=>$content_type, -charset =>'utf-8',3409-status=>$status, -expires =>$expires)3410unless($opts{'-no_http_header'});3411my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3412print<<EOF;3413<?xml version="1.0" encoding="utf-8"?>3414<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3415<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3416<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3417<!-- git core binaries version$git_version-->3418<head>3419<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3420<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3421<meta name="robots" content="index, nofollow"/>3422<title>$title</title>3423EOF3424# the stylesheet, favicon etc urls won't work correctly with path_info3425# unless we set the appropriate base URL3426if($ENV{'PATH_INFO'}) {3427print"<base href=\"".esc_url($base_url)."\"/>\n";3428}3429# print out each stylesheet that exist, providing backwards capability3430# for those people who defined $stylesheet in a config file3431if(defined$stylesheet) {3432print'<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";3433}else{3434foreachmy$stylesheet(@stylesheets) {3435next unless$stylesheet;3436print'<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";3437}3438}3439if(defined$project) {3440my%href_params= get_feed_info();3441if(!exists$href_params{'-title'}) {3442$href_params{'-title'} ='log';3443}34443445foreachmy$formatqw(RSS Atom){3446my$type=lc($format);3447my%link_attr= (3448'-rel'=>'alternate',3449'-title'=>"$project-$href_params{'-title'} -$formatfeed",3450'-type'=>"application/$type+xml"3451);34523453$href_params{'action'} =$type;3454$link_attr{'-href'} = href(%href_params);3455print"<link ".3456"rel=\"$link_attr{'-rel'}\"".3457"title=\"$link_attr{'-title'}\"".3458"href=\"$link_attr{'-href'}\"".3459"type=\"$link_attr{'-type'}\"".3460"/>\n";34613462$href_params{'extra_options'} ='--no-merges';3463$link_attr{'-href'} = href(%href_params);3464$link_attr{'-title'} .=' (no merges)';3465print"<link ".3466"rel=\"$link_attr{'-rel'}\"".3467"title=\"$link_attr{'-title'}\"".3468"href=\"$link_attr{'-href'}\"".3469"type=\"$link_attr{'-type'}\"".3470"/>\n";3471}34723473}else{3474printf('<link rel="alternate" title="%sprojects list" '.3475'href="%s" type="text/plain; charset=utf-8" />'."\n",3476$site_name, href(project=>undef, action=>"project_index"));3477printf('<link rel="alternate" title="%sprojects feeds" '.3478'href="%s" type="text/x-opml" />'."\n",3479$site_name, href(project=>undef, action=>"opml"));3480}3481if(defined$favicon) {3482printqq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);3483}34843485print"</head>\n".3486"<body>\n";34873488if(defined$site_header&& -f $site_header) {3489 insert_file($site_header);3490}34913492print"<div class=\"page_header\">\n".3493$cgi->a({-href => esc_url($logo_url),3494-title =>$logo_label},3495qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));3496print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3497if(defined$project) {3498print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3499if(defined$action) {3500print" /$action";3501}3502print"\n";3503}3504print"</div>\n";35053506my$have_search= gitweb_check_feature('search');3507if(defined$project&&$have_search) {3508if(!defined$searchtext) {3509$searchtext="";3510}3511my$search_hash;3512if(defined$hash_base) {3513$search_hash=$hash_base;3514}elsif(defined$hash) {3515$search_hash=$hash;3516}else{3517$search_hash="HEAD";3518}3519my$action=$my_uri;3520my$use_pathinfo= gitweb_check_feature('pathinfo');3521if($use_pathinfo) {3522$action.="/".esc_url($project);3523}3524print$cgi->startform(-method=>"get", -action =>$action) .3525"<div class=\"search\">\n".3526(!$use_pathinfo&&3527$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3528$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3529$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3530$cgi->popup_menu(-name =>'st', -default=>'commit',3531-values=> ['commit','grep','author','committer','pickaxe']) .3532$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3533" search:\n",3534$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3535"<span title=\"Extended regular expression\">".3536$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3537-checked =>$search_use_regexp) .3538"</span>".3539"</div>".3540$cgi->end_form() ."\n";3541}3542}35433544sub git_footer_html {3545my$feed_class='rss_logo';35463547print"<div class=\"page_footer\">\n";3548if(defined$project) {3549my$descr= git_get_project_description($project);3550if(defined$descr) {3551print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3552}35533554my%href_params= get_feed_info();3555if(!%href_params) {3556$feed_class.=' generic';3557}3558$href_params{'-title'} ||='log';35593560foreachmy$formatqw(RSS Atom){3561$href_params{'action'} =lc($format);3562print$cgi->a({-href => href(%href_params),3563-title =>"$href_params{'-title'}$formatfeed",3564-class=>$feed_class},$format)."\n";3565}35663567}else{3568print$cgi->a({-href => href(project=>undef, action=>"opml"),3569-class=>$feed_class},"OPML") ." ";3570print$cgi->a({-href => href(project=>undef, action=>"project_index"),3571-class=>$feed_class},"TXT") ."\n";3572}3573print"</div>\n";# class="page_footer"35743575if(defined$t0&& gitweb_check_feature('timed')) {3576print"<div id=\"generating_info\">\n";3577print'This page took '.3578'<span id="generating_time" class="time_span">'.3579 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).3580' seconds </span>'.3581' and '.3582'<span id="generating_cmd">'.3583$number_of_git_cmds.3584'</span> git commands '.3585" to generate.\n";3586print"</div>\n";# class="page_footer"3587}35883589if(defined$site_footer&& -f $site_footer) {3590 insert_file($site_footer);3591}35923593print qq!<script type="text/javascript" src="$javascript"></script>\n!;3594if(defined$action&&3595$actioneq'blame_incremental') {3596print qq!<script type="text/javascript">\n!.3597 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.3598 qq!"!. href() .qq!");\n!.3599 qq!</script>\n!;3600}elsif(gitweb_check_feature('javascript-actions')) {3601print qq!<script type="text/javascript">\n!.3602 qq!window.onload = fixLinks;\n!.3603 qq!</script>\n!;3604}36053606print"</body>\n".3607"</html>";3608}36093610# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])3611# Example: die_error(404, 'Hash not found')3612# By convention, use the following status codes (as defined in RFC 2616):3613# 400: Invalid or missing CGI parameters, or3614# requested object exists but has wrong type.3615# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3616# this server or project.3617# 404: Requested object/revision/project doesn't exist.3618# 500: The server isn't configured properly, or3619# an internal error occurred (e.g. failed assertions caused by bugs), or3620# an unknown error occurred (e.g. the git binary died unexpectedly).3621# 503: The server is currently unavailable (because it is overloaded,3622# or down for maintenance). Generally, this is a temporary state.3623sub die_error {3624my$status=shift||500;3625my$error= esc_html(shift) ||"Internal Server Error";3626my$extra=shift;3627my%opts=@_;36283629my%http_responses= (3630400=>'400 Bad Request',3631403=>'403 Forbidden',3632404=>'404 Not Found',3633500=>'500 Internal Server Error',3634503=>'503 Service Unavailable',3635);3636 git_header_html($http_responses{$status},undef,%opts);3637print<<EOF;3638<div class="page_body">3639<br /><br />3640$status-$error3641<br />3642EOF3643if(defined$extra) {3644print"<hr />\n".3645"$extra\n";3646}3647print"</div>\n";36483649 git_footer_html();3650goto DONE_GITWEB3651unless($opts{'-error_handler'});3652}36533654## ----------------------------------------------------------------------3655## functions printing or outputting HTML: navigation36563657sub git_print_page_nav {3658my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;3659$extra=''if!defined$extra;# pager or formats36603661my@navs=qw(summary shortlog log commit commitdiff tree);3662if($suppress) {3663@navs=grep{$_ne$suppress}@navs;3664}36653666my%arg=map{$_=> {action=>$_} }@navs;3667if(defined$head) {3668for(qw(commit commitdiff)) {3669$arg{$_}{'hash'} =$head;3670}3671if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {3672for(qw(shortlog log)) {3673$arg{$_}{'hash'} =$head;3674}3675}3676}36773678$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;3679$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;36803681my@actions= gitweb_get_feature('actions');3682my%repl= (3683'%'=>'%',3684'n'=>$project,# project name3685'f'=>$git_dir,# project path within filesystem3686'h'=>$treehead||'',# current hash ('h' parameter)3687'b'=>$treebase||'',# hash base ('hb' parameter)3688);3689while(@actions) {3690my($label,$link,$pos) =splice(@actions,0,3);3691# insert3692@navs=map{$_eq$pos? ($_,$label) :$_}@navs;3693# munch munch3694$link=~s/%([%nfhb])/$repl{$1}/g;3695$arg{$label}{'_href'} =$link;3696}36973698print"<div class=\"page_nav\">\n".3699(join" | ",3700map{$_eq$current?3701$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")3702}@navs);3703print"<br/>\n$extra<br/>\n".3704"</div>\n";3705}37063707sub format_paging_nav {3708my($action,$page,$has_next_link) =@_;3709my$paging_nav;371037113712if($page>0) {3713$paging_nav.=3714$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .3715" ⋅ ".3716$cgi->a({-href => href(-replay=>1, page=>$page-1),3717-accesskey =>"p", -title =>"Alt-p"},"prev");3718}else{3719$paging_nav.="first ⋅ prev";3720}37213722if($has_next_link) {3723$paging_nav.=" ⋅ ".3724$cgi->a({-href => href(-replay=>1, page=>$page+1),3725-accesskey =>"n", -title =>"Alt-n"},"next");3726}else{3727$paging_nav.=" ⋅ next";3728}37293730return$paging_nav;3731}37323733## ......................................................................3734## functions printing or outputting HTML: div37353736sub git_print_header_div {3737my($action,$title,$hash,$hash_base) =@_;3738my%args= ();37393740$args{'action'} =$action;3741$args{'hash'} =$hashif$hash;3742$args{'hash_base'} =$hash_baseif$hash_base;37433744print"<div class=\"header\">\n".3745$cgi->a({-href => href(%args), -class=>"title"},3746$title?$title:$action) .3747"\n</div>\n";3748}37493750sub print_local_time {3751print format_local_time(@_);3752}37533754sub format_local_time {3755my$localtime='';3756my%date=@_;3757if($date{'hour_local'} <6) {3758$localtime.=sprintf(" (<span class=\"atnight\">%02d:%02d</span>%s)",3759$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});3760}else{3761$localtime.=sprintf(" (%02d:%02d%s)",3762$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});3763}37643765return$localtime;3766}37673768# Outputs the author name and date in long form3769sub git_print_authorship {3770my$co=shift;3771my%opts=@_;3772my$tag=$opts{-tag} ||'div';3773my$author=$co->{'author_name'};37743775my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});3776print"<$tagclass=\"author_date\">".3777 format_search_author($author,"author", esc_html($author)) .3778" [$ad{'rfc2822'}";3779 print_local_time(%ad)if($opts{-localtime});3780print"]". git_get_avatar($co->{'author_email'}, -pad_before =>1)3781."</$tag>\n";3782}37833784# Outputs table rows containing the full author or committer information,3785# in the format expected for 'commit' view (& similia).3786# Parameters are a commit hash reference, followed by the list of people3787# to output information for. If the list is empty it defalts to both3788# author and committer.3789sub git_print_authorship_rows {3790my$co=shift;3791# too bad we can't use @people = @_ || ('author', 'committer')3792my@people=@_;3793@people= ('author','committer')unless@people;3794foreachmy$who(@people) {3795my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});3796print"<tr><td>$who</td><td>".3797 format_search_author($co->{"${who}_name"},$who,3798 esc_html($co->{"${who}_name"})) ." ".3799 format_search_author($co->{"${who}_email"},$who,3800 esc_html("<".$co->{"${who}_email"} .">")) .3801"</td><td rowspan=\"2\">".3802 git_get_avatar($co->{"${who}_email"}, -size =>'double') .3803"</td></tr>\n".3804"<tr>".3805"<td></td><td>$wd{'rfc2822'}";3806 print_local_time(%wd);3807print"</td>".3808"</tr>\n";3809}3810}38113812sub git_print_page_path {3813my$name=shift;3814my$type=shift;3815my$hb=shift;381638173818print"<div class=\"page_path\">";3819print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),3820-title =>'tree root'}, to_utf8("[$project]"));3821print" / ";3822if(defined$name) {3823my@dirname=split'/',$name;3824my$basename=pop@dirname;3825my$fullname='';38263827foreachmy$dir(@dirname) {3828$fullname.= ($fullname?'/':'') .$dir;3829print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,3830 hash_base=>$hb),3831-title =>$fullname}, esc_path($dir));3832print" / ";3833}3834if(defined$type&&$typeeq'blob') {3835print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,3836 hash_base=>$hb),3837-title =>$name}, esc_path($basename));3838}elsif(defined$type&&$typeeq'tree') {3839print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,3840 hash_base=>$hb),3841-title =>$name}, esc_path($basename));3842print" / ";3843}else{3844print esc_path($basename);3845}3846}3847print"<br/></div>\n";3848}38493850sub git_print_log {3851my$log=shift;3852my%opts=@_;38533854if($opts{'-remove_title'}) {3855# remove title, i.e. first line of log3856shift@$log;3857}3858# remove leading empty lines3859while(defined$log->[0] &&$log->[0]eq"") {3860shift@$log;3861}38623863# print log3864my$signoff=0;3865my$empty=0;3866foreachmy$line(@$log) {3867if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {3868$signoff=1;3869$empty=0;3870if(!$opts{'-remove_signoff'}) {3871print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";3872next;3873}else{3874# remove signoff lines3875next;3876}3877}else{3878$signoff=0;3879}38803881# print only one empty line3882# do not print empty line after signoff3883if($lineeq"") {3884next if($empty||$signoff);3885$empty=1;3886}else{3887$empty=0;3888}38893890print format_log_line_html($line) ."<br/>\n";3891}38923893if($opts{'-final_empty_line'}) {3894# end with single empty line3895print"<br/>\n"unless$empty;3896}3897}38983899# return link target (what link points to)3900sub git_get_link_target {3901my$hash=shift;3902my$link_target;39033904# read link3905open my$fd,"-|", git_cmd(),"cat-file","blob",$hash3906orreturn;3907{3908local$/=undef;3909$link_target= <$fd>;3910}3911close$fd3912orreturn;39133914return$link_target;3915}39163917# given link target, and the directory (basedir) the link is in,3918# return target of link relative to top directory (top tree);3919# return undef if it is not possible (including absolute links).3920sub normalize_link_target {3921my($link_target,$basedir) =@_;39223923# absolute symlinks (beginning with '/') cannot be normalized3924return if(substr($link_target,0,1)eq'/');39253926# normalize link target to path from top (root) tree (dir)3927my$path;3928if($basedir) {3929$path=$basedir.'/'.$link_target;3930}else{3931# we are in top (root) tree (dir)3932$path=$link_target;3933}39343935# remove //, /./, and /../3936my@path_parts;3937foreachmy$part(split('/',$path)) {3938# discard '.' and ''3939next if(!$part||$parteq'.');3940# handle '..'3941if($parteq'..') {3942if(@path_parts) {3943pop@path_parts;3944}else{3945# link leads outside repository (outside top dir)3946return;3947}3948}else{3949push@path_parts,$part;3950}3951}3952$path=join('/',@path_parts);39533954return$path;3955}39563957# print tree entry (row of git_tree), but without encompassing <tr> element3958sub git_print_tree_entry {3959my($t,$basedir,$hash_base,$have_blame) =@_;39603961my%base_key= ();3962$base_key{'hash_base'} =$hash_baseifdefined$hash_base;39633964# The format of a table row is: mode list link. Where mode is3965# the mode of the entry, list is the name of the entry, an href,3966# and link is the action links of the entry.39673968print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";3969if(exists$t->{'size'}) {3970print"<td class=\"size\">$t->{'size'}</td>\n";3971}3972if($t->{'type'}eq"blob") {3973print"<td class=\"list\">".3974$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},3975 file_name=>"$basedir$t->{'name'}",%base_key),3976-class=>"list"}, esc_path($t->{'name'}));3977if(S_ISLNK(oct$t->{'mode'})) {3978my$link_target= git_get_link_target($t->{'hash'});3979if($link_target) {3980my$norm_target= normalize_link_target($link_target,$basedir);3981if(defined$norm_target) {3982print" -> ".3983$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,3984 file_name=>$norm_target),3985-title =>$norm_target}, esc_path($link_target));3986}else{3987print" -> ". esc_path($link_target);3988}3989}3990}3991print"</td>\n";3992print"<td class=\"link\">";3993print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},3994 file_name=>"$basedir$t->{'name'}",%base_key)},3995"blob");3996if($have_blame) {3997print" | ".3998$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},3999 file_name=>"$basedir$t->{'name'}",%base_key)},4000"blame");4001}4002if(defined$hash_base) {4003print" | ".4004$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4005 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4006"history");4007}4008print" | ".4009$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4010 file_name=>"$basedir$t->{'name'}")},4011"raw");4012print"</td>\n";40134014}elsif($t->{'type'}eq"tree") {4015print"<td class=\"list\">";4016print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4017 file_name=>"$basedir$t->{'name'}",4018%base_key)},4019 esc_path($t->{'name'}));4020print"</td>\n";4021print"<td class=\"link\">";4022print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4023 file_name=>"$basedir$t->{'name'}",4024%base_key)},4025"tree");4026if(defined$hash_base) {4027print" | ".4028$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4029 file_name=>"$basedir$t->{'name'}")},4030"history");4031}4032print"</td>\n";4033}else{4034# unknown object: we can only present history for it4035# (this includes 'commit' object, i.e. submodule support)4036print"<td class=\"list\">".4037 esc_path($t->{'name'}) .4038"</td>\n";4039print"<td class=\"link\">";4040if(defined$hash_base) {4041print$cgi->a({-href => href(action=>"history",4042 hash_base=>$hash_base,4043 file_name=>"$basedir$t->{'name'}")},4044"history");4045}4046print"</td>\n";4047}4048}40494050## ......................................................................4051## functions printing large fragments of HTML40524053# get pre-image filenames for merge (combined) diff4054sub fill_from_file_info {4055my($diff,@parents) =@_;40564057$diff->{'from_file'} = [ ];4058$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4059for(my$i=0;$i<$diff->{'nparents'};$i++) {4060if($diff->{'status'}[$i]eq'R'||4061$diff->{'status'}[$i]eq'C') {4062$diff->{'from_file'}[$i] =4063 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4064}4065}40664067return$diff;4068}40694070# is current raw difftree line of file deletion4071sub is_deleted {4072my$diffinfo=shift;40734074return$diffinfo->{'to_id'}eq('0' x 40);4075}40764077# does patch correspond to [previous] difftree raw line4078# $diffinfo - hashref of parsed raw diff format4079# $patchinfo - hashref of parsed patch diff format4080# (the same keys as in $diffinfo)4081sub is_patch_split {4082my($diffinfo,$patchinfo) =@_;40834084returndefined$diffinfo&&defined$patchinfo4085&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4086}408740884089sub git_difftree_body {4090my($difftree,$hash,@parents) =@_;4091my($parent) =$parents[0];4092my$have_blame= gitweb_check_feature('blame');4093print"<div class=\"list_head\">\n";4094if($#{$difftree} >10) {4095print(($#{$difftree} +1) ." files changed:\n");4096}4097print"</div>\n";40984099print"<table class=\"".4100(@parents>1?"combined ":"") .4101"diff_tree\">\n";41024103# header only for combined diff in 'commitdiff' view4104my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4105if($has_header) {4106# table header4107print"<thead><tr>\n".4108"<th></th><th></th>\n";# filename, patchN link4109for(my$i=0;$i<@parents;$i++) {4110my$par=$parents[$i];4111print"<th>".4112$cgi->a({-href => href(action=>"commitdiff",4113 hash=>$hash, hash_parent=>$par),4114-title =>'commitdiff to parent number '.4115($i+1) .': '.substr($par,0,7)},4116$i+1) .4117" </th>\n";4118}4119print"</tr></thead>\n<tbody>\n";4120}41214122my$alternate=1;4123my$patchno=0;4124foreachmy$line(@{$difftree}) {4125my$diff= parsed_difftree_line($line);41264127if($alternate) {4128print"<tr class=\"dark\">\n";4129}else{4130print"<tr class=\"light\">\n";4131}4132$alternate^=1;41334134if(exists$diff->{'nparents'}) {# combined diff41354136 fill_from_file_info($diff,@parents)4137unlessexists$diff->{'from_file'};41384139if(!is_deleted($diff)) {4140# file exists in the result (child) commit4141print"<td>".4142$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4143 file_name=>$diff->{'to_file'},4144 hash_base=>$hash),4145-class=>"list"}, esc_path($diff->{'to_file'})) .4146"</td>\n";4147}else{4148print"<td>".4149 esc_path($diff->{'to_file'}) .4150"</td>\n";4151}41524153if($actioneq'commitdiff') {4154# link to patch4155$patchno++;4156print"<td class=\"link\">".4157$cgi->a({-href =>"#patch$patchno"},"patch") .4158" | ".4159"</td>\n";4160}41614162my$has_history=0;4163my$not_deleted=0;4164for(my$i=0;$i<$diff->{'nparents'};$i++) {4165my$hash_parent=$parents[$i];4166my$from_hash=$diff->{'from_id'}[$i];4167my$from_path=$diff->{'from_file'}[$i];4168my$status=$diff->{'status'}[$i];41694170$has_history||= ($statusne'A');4171$not_deleted||= ($statusne'D');41724173if($statuseq'A') {4174print"<td class=\"link\"align=\"right\"> | </td>\n";4175}elsif($statuseq'D') {4176print"<td class=\"link\">".4177$cgi->a({-href => href(action=>"blob",4178 hash_base=>$hash,4179 hash=>$from_hash,4180 file_name=>$from_path)},4181"blob". ($i+1)) .4182" | </td>\n";4183}else{4184if($diff->{'to_id'}eq$from_hash) {4185print"<td class=\"link nochange\">";4186}else{4187print"<td class=\"link\">";4188}4189print$cgi->a({-href => href(action=>"blobdiff",4190 hash=>$diff->{'to_id'},4191 hash_parent=>$from_hash,4192 hash_base=>$hash,4193 hash_parent_base=>$hash_parent,4194 file_name=>$diff->{'to_file'},4195 file_parent=>$from_path)},4196"diff". ($i+1)) .4197" | </td>\n";4198}4199}42004201print"<td class=\"link\">";4202if($not_deleted) {4203print$cgi->a({-href => href(action=>"blob",4204 hash=>$diff->{'to_id'},4205 file_name=>$diff->{'to_file'},4206 hash_base=>$hash)},4207"blob");4208print" | "if($has_history);4209}4210if($has_history) {4211print$cgi->a({-href => href(action=>"history",4212 file_name=>$diff->{'to_file'},4213 hash_base=>$hash)},4214"history");4215}4216print"</td>\n";42174218print"</tr>\n";4219next;# instead of 'else' clause, to avoid extra indent4220}4221# else ordinary diff42224223my($to_mode_oct,$to_mode_str,$to_file_type);4224my($from_mode_oct,$from_mode_str,$from_file_type);4225if($diff->{'to_mode'}ne('0' x 6)) {4226$to_mode_oct=oct$diff->{'to_mode'};4227if(S_ISREG($to_mode_oct)) {# only for regular file4228$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4229}4230$to_file_type= file_type($diff->{'to_mode'});4231}4232if($diff->{'from_mode'}ne('0' x 6)) {4233$from_mode_oct=oct$diff->{'from_mode'};4234if(S_ISREG($to_mode_oct)) {# only for regular file4235$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4236}4237$from_file_type= file_type($diff->{'from_mode'});4238}42394240if($diff->{'status'}eq"A") {# created4241my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4242$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4243$mode_chng.="]</span>";4244print"<td>";4245print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4246 hash_base=>$hash, file_name=>$diff->{'file'}),4247-class=>"list"}, esc_path($diff->{'file'}));4248print"</td>\n";4249print"<td>$mode_chng</td>\n";4250print"<td class=\"link\">";4251if($actioneq'commitdiff') {4252# link to patch4253$patchno++;4254print$cgi->a({-href =>"#patch$patchno"},"patch");4255print" | ";4256}4257print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4258 hash_base=>$hash, file_name=>$diff->{'file'})},4259"blob");4260print"</td>\n";42614262}elsif($diff->{'status'}eq"D") {# deleted4263my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4264print"<td>";4265print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4266 hash_base=>$parent, file_name=>$diff->{'file'}),4267-class=>"list"}, esc_path($diff->{'file'}));4268print"</td>\n";4269print"<td>$mode_chng</td>\n";4270print"<td class=\"link\">";4271if($actioneq'commitdiff') {4272# link to patch4273$patchno++;4274print$cgi->a({-href =>"#patch$patchno"},"patch");4275print" | ";4276}4277print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4278 hash_base=>$parent, file_name=>$diff->{'file'})},4279"blob") ." | ";4280if($have_blame) {4281print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4282 file_name=>$diff->{'file'})},4283"blame") ." | ";4284}4285print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4286 file_name=>$diff->{'file'})},4287"history");4288print"</td>\n";42894290}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4291my$mode_chnge="";4292if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4293$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4294if($from_file_typene$to_file_type) {4295$mode_chnge.=" from$from_file_typeto$to_file_type";4296}4297if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4298if($from_mode_str&&$to_mode_str) {4299$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4300}elsif($to_mode_str) {4301$mode_chnge.=" mode:$to_mode_str";4302}4303}4304$mode_chnge.="]</span>\n";4305}4306print"<td>";4307print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4308 hash_base=>$hash, file_name=>$diff->{'file'}),4309-class=>"list"}, esc_path($diff->{'file'}));4310print"</td>\n";4311print"<td>$mode_chnge</td>\n";4312print"<td class=\"link\">";4313if($actioneq'commitdiff') {4314# link to patch4315$patchno++;4316print$cgi->a({-href =>"#patch$patchno"},"patch") .4317" | ";4318}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4319# "commit" view and modified file (not onlu mode changed)4320print$cgi->a({-href => href(action=>"blobdiff",4321 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4322 hash_base=>$hash, hash_parent_base=>$parent,4323 file_name=>$diff->{'file'})},4324"diff") .4325" | ";4326}4327print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4328 hash_base=>$hash, file_name=>$diff->{'file'})},4329"blob") ." | ";4330if($have_blame) {4331print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4332 file_name=>$diff->{'file'})},4333"blame") ." | ";4334}4335print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4336 file_name=>$diff->{'file'})},4337"history");4338print"</td>\n";43394340}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4341my%status_name= ('R'=>'moved','C'=>'copied');4342my$nstatus=$status_name{$diff->{'status'}};4343my$mode_chng="";4344if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4345# mode also for directories, so we cannot use $to_mode_str4346$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4347}4348print"<td>".4349$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4350 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4351-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4352"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4353$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4354 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4355-class=>"list"}, esc_path($diff->{'from_file'})) .4356" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4357"<td class=\"link\">";4358if($actioneq'commitdiff') {4359# link to patch4360$patchno++;4361print$cgi->a({-href =>"#patch$patchno"},"patch") .4362" | ";4363}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4364# "commit" view and modified file (not only pure rename or copy)4365print$cgi->a({-href => href(action=>"blobdiff",4366 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4367 hash_base=>$hash, hash_parent_base=>$parent,4368 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4369"diff") .4370" | ";4371}4372print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4373 hash_base=>$parent, file_name=>$diff->{'to_file'})},4374"blob") ." | ";4375if($have_blame) {4376print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4377 file_name=>$diff->{'to_file'})},4378"blame") ." | ";4379}4380print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4381 file_name=>$diff->{'to_file'})},4382"history");4383print"</td>\n";43844385}# we should not encounter Unmerged (U) or Unknown (X) status4386print"</tr>\n";4387}4388print"</tbody>"if$has_header;4389print"</table>\n";4390}43914392sub git_patchset_body {4393my($fd,$difftree,$hash,@hash_parents) =@_;4394my($hash_parent) =$hash_parents[0];43954396my$is_combined= (@hash_parents>1);4397my$patch_idx=0;4398my$patch_number=0;4399my$patch_line;4400my$diffinfo;4401my$to_name;4402my(%from,%to);44034404print"<div class=\"patchset\">\n";44054406# skip to first patch4407while($patch_line= <$fd>) {4408chomp$patch_line;44094410last if($patch_line=~m/^diff /);4411}44124413 PATCH:4414while($patch_line) {44154416# parse "git diff" header line4417if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4418# $1 is from_name, which we do not use4419$to_name= unquote($2);4420$to_name=~s!^b/!!;4421}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4422# $1 is 'cc' or 'combined', which we do not use4423$to_name= unquote($2);4424}else{4425$to_name=undef;4426}44274428# check if current patch belong to current raw line4429# and parse raw git-diff line if needed4430if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4431# this is continuation of a split patch4432print"<div class=\"patch cont\">\n";4433}else{4434# advance raw git-diff output if needed4435$patch_idx++ifdefined$diffinfo;44364437# read and prepare patch information4438$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);44394440# compact combined diff output can have some patches skipped4441# find which patch (using pathname of result) we are at now;4442if($is_combined) {4443while($to_namene$diffinfo->{'to_file'}) {4444print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4445 format_diff_cc_simplified($diffinfo,@hash_parents) .4446"</div>\n";# class="patch"44474448$patch_idx++;4449$patch_number++;44504451last if$patch_idx>$#$difftree;4452$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4453}4454}44554456# modifies %from, %to hashes4457 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);44584459# this is first patch for raw difftree line with $patch_idx index4460# we index @$difftree array from 0, but number patches from 14461print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4462}44634464# git diff header4465#assert($patch_line =~ m/^diff /) if DEBUG;4466#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4467$patch_number++;4468# print "git diff" header4469print format_git_diff_header_line($patch_line,$diffinfo,4470 \%from, \%to);44714472# print extended diff header4473print"<div class=\"diff extended_header\">\n";4474 EXTENDED_HEADER:4475while($patch_line= <$fd>) {4476chomp$patch_line;44774478last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);44794480print format_extended_diff_header_line($patch_line,$diffinfo,4481 \%from, \%to);4482}4483print"</div>\n";# class="diff extended_header"44844485# from-file/to-file diff header4486if(!$patch_line) {4487print"</div>\n";# class="patch"4488last PATCH;4489}4490next PATCH if($patch_line=~m/^diff /);4491#assert($patch_line =~ m/^---/) if DEBUG;44924493my$last_patch_line=$patch_line;4494$patch_line= <$fd>;4495chomp$patch_line;4496#assert($patch_line =~ m/^\+\+\+/) if DEBUG;44974498print format_diff_from_to_header($last_patch_line,$patch_line,4499$diffinfo, \%from, \%to,4500@hash_parents);45014502# the patch itself4503 LINE:4504while($patch_line= <$fd>) {4505chomp$patch_line;45064507next PATCH if($patch_line=~m/^diff /);45084509print format_diff_line($patch_line, \%from, \%to);4510}45114512}continue{4513print"</div>\n";# class="patch"4514}45154516# for compact combined (--cc) format, with chunk and patch simpliciaction4517# patchset might be empty, but there might be unprocessed raw lines4518for(++$patch_idxif$patch_number>0;4519$patch_idx<@$difftree;4520++$patch_idx) {4521# read and prepare patch information4522$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);45234524# generate anchor for "patch" links in difftree / whatchanged part4525print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4526 format_diff_cc_simplified($diffinfo,@hash_parents) .4527"</div>\n";# class="patch"45284529$patch_number++;4530}45314532if($patch_number==0) {4533if(@hash_parents>1) {4534print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4535}else{4536print"<div class=\"diff nodifferences\">No differences found</div>\n";4537}4538}45394540print"</div>\n";# class="patchset"4541}45424543# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .45444545# fills project list info (age, description, owner, forks) for each4546# project in the list, removing invalid projects from returned list4547# NOTE: modifies $projlist, but does not remove entries from it4548sub fill_project_list_info {4549my($projlist,$check_forks) =@_;4550my@projects;45514552my$show_ctags= gitweb_check_feature('ctags');4553 PROJECT:4554foreachmy$pr(@$projlist) {4555my(@activity) = git_get_last_activity($pr->{'path'});4556unless(@activity) {4557next PROJECT;4558}4559($pr->{'age'},$pr->{'age_string'}) =@activity;4560if(!defined$pr->{'descr'}) {4561my$descr= git_get_project_description($pr->{'path'}) ||"";4562$descr= to_utf8($descr);4563$pr->{'descr_long'} =$descr;4564$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);4565}4566if(!defined$pr->{'owner'}) {4567$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";4568}4569if($check_forks) {4570my$pname=$pr->{'path'};4571if(($pname=~s/\.git$//) &&4572($pname!~/\/$/) &&4573(-d "$projectroot/$pname")) {4574$pr->{'forks'} ="-d$projectroot/$pname";4575}else{4576$pr->{'forks'} =0;4577}4578}4579$show_ctagsand$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});4580push@projects,$pr;4581}45824583return@projects;4584}45854586# print 'sort by' <th> element, generating 'sort by $name' replay link4587# if that order is not selected4588sub print_sort_th {4589print format_sort_th(@_);4590}45914592sub format_sort_th {4593my($name,$order,$header) =@_;4594my$sort_th="";4595$header||=ucfirst($name);45964597if($ordereq$name) {4598$sort_th.="<th>$header</th>\n";4599}else{4600$sort_th.="<th>".4601$cgi->a({-href => href(-replay=>1, order=>$name),4602-class=>"header"},$header) .4603"</th>\n";4604}46054606return$sort_th;4607}46084609sub git_project_list_body {4610# actually uses global variable $project4611my($projlist,$order,$from,$to,$extra,$no_header) =@_;46124613my$check_forks= gitweb_check_feature('forks');4614my@projects= fill_project_list_info($projlist,$check_forks);46154616$order||=$default_projects_order;4617$from=0unlessdefined$from;4618$to=$#projectsif(!defined$to||$#projects<$to);46194620my%order_info= (4621 project => { key =>'path', type =>'str'},4622 descr => { key =>'descr_long', type =>'str'},4623 owner => { key =>'owner', type =>'str'},4624 age => { key =>'age', type =>'num'}4625);4626my$oi=$order_info{$order};4627if($oi->{'type'}eq'str') {4628@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@projects;4629}else{4630@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@projects;4631}46324633my$show_ctags= gitweb_check_feature('ctags');4634if($show_ctags) {4635my%ctags;4636foreachmy$p(@projects) {4637foreachmy$ct(keys%{$p->{'ctags'}}) {4638$ctags{$ct} +=$p->{'ctags'}->{$ct};4639}4640}4641my$cloud= git_populate_project_tagcloud(\%ctags);4642print git_show_project_tagcloud($cloud,64);4643}46444645print"<table class=\"project_list\">\n";4646unless($no_header) {4647print"<tr>\n";4648if($check_forks) {4649print"<th></th>\n";4650}4651 print_sort_th('project',$order,'Project');4652 print_sort_th('descr',$order,'Description');4653 print_sort_th('owner',$order,'Owner');4654 print_sort_th('age',$order,'Last Change');4655print"<th></th>\n".# for links4656"</tr>\n";4657}4658my$alternate=1;4659my$tagfilter=$cgi->param('by_tag');4660for(my$i=$from;$i<=$to;$i++) {4661my$pr=$projects[$i];46624663next if$tagfilterand$show_ctagsand not grep{lc$_eq lc$tagfilter}keys%{$pr->{'ctags'}};4664next if$searchtextand not$pr->{'path'} =~/$searchtext/4665and not$pr->{'descr_long'} =~/$searchtext/;4666# Weed out forks or non-matching entries of search4667if($check_forks) {4668my$forkbase=$project;$forkbase||='';$forkbase=~ s#\.git$#/#;4669$forkbase="^$forkbase"if$forkbase;4670next ifnot$searchtextand not$tagfilterand$show_ctags4671and$pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe4672}46734674if($alternate) {4675print"<tr class=\"dark\">\n";4676}else{4677print"<tr class=\"light\">\n";4678}4679$alternate^=1;4680if($check_forks) {4681print"<td>";4682if($pr->{'forks'}) {4683print"<!--$pr->{'forks'} -->\n";4684print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"+");4685}4686print"</td>\n";4687}4688print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),4689-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".4690"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),4691-class=>"list", -title =>$pr->{'descr_long'}},4692 esc_html($pr->{'descr'})) ."</td>\n".4693"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";4694print"<td class=\"". age_class($pr->{'age'}) ."\">".4695(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".4696"<td class=\"link\">".4697$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".4698$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".4699$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".4700$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .4701($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .4702"</td>\n".4703"</tr>\n";4704}4705if(defined$extra) {4706print"<tr>\n";4707if($check_forks) {4708print"<td></td>\n";4709}4710print"<td colspan=\"5\">$extra</td>\n".4711"</tr>\n";4712}4713print"</table>\n";4714}47154716sub git_log_body {4717# uses global variable $project4718my($commitlist,$from,$to,$refs,$extra) =@_;47194720$from=0unlessdefined$from;4721$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);47224723for(my$i=0;$i<=$to;$i++) {4724my%co= %{$commitlist->[$i]};4725next if!%co;4726my$commit=$co{'id'};4727my$ref= format_ref_marker($refs,$commit);4728my%ad= parse_date($co{'author_epoch'});4729 git_print_header_div('commit',4730"<span class=\"age\">$co{'age_string'}</span>".4731 esc_html($co{'title'}) .$ref,4732$commit);4733print"<div class=\"title_text\">\n".4734"<div class=\"log_link\">\n".4735$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .4736" | ".4737$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .4738" | ".4739$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .4740"<br/>\n".4741"</div>\n";4742 git_print_authorship(\%co, -tag =>'span');4743print"<br/>\n</div>\n";47444745print"<div class=\"log_body\">\n";4746 git_print_log($co{'comment'}, -final_empty_line=>1);4747print"</div>\n";4748}4749if($extra) {4750print"<div class=\"page_nav\">\n";4751print"$extra\n";4752print"</div>\n";4753}4754}47554756sub git_shortlog_body {4757# uses global variable $project4758my($commitlist,$from,$to,$refs,$extra) =@_;47594760$from=0unlessdefined$from;4761$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);47624763print"<table class=\"shortlog\">\n";4764my$alternate=1;4765for(my$i=$from;$i<=$to;$i++) {4766my%co= %{$commitlist->[$i]};4767my$commit=$co{'id'};4768my$ref= format_ref_marker($refs,$commit);4769if($alternate) {4770print"<tr class=\"dark\">\n";4771}else{4772print"<tr class=\"light\">\n";4773}4774$alternate^=1;4775# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .4776print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4777 format_author_html('td', \%co,10) ."<td>";4778print format_subject_html($co{'title'},$co{'title_short'},4779 href(action=>"commit", hash=>$commit),$ref);4780print"</td>\n".4781"<td class=\"link\">".4782$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".4783$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".4784$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");4785my$snapshot_links= format_snapshot_links($commit);4786if(defined$snapshot_links) {4787print" | ".$snapshot_links;4788}4789print"</td>\n".4790"</tr>\n";4791}4792if(defined$extra) {4793print"<tr>\n".4794"<td colspan=\"4\">$extra</td>\n".4795"</tr>\n";4796}4797print"</table>\n";4798}47994800sub git_history_body {4801# Warning: assumes constant type (blob or tree) during history4802my($commitlist,$from,$to,$refs,$extra,4803$file_name,$file_hash,$ftype) =@_;48044805$from=0unlessdefined$from;4806$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});48074808print"<table class=\"history\">\n";4809my$alternate=1;4810for(my$i=$from;$i<=$to;$i++) {4811my%co= %{$commitlist->[$i]};4812if(!%co) {4813next;4814}4815my$commit=$co{'id'};48164817my$ref= format_ref_marker($refs,$commit);48184819if($alternate) {4820print"<tr class=\"dark\">\n";4821}else{4822print"<tr class=\"light\">\n";4823}4824$alternate^=1;4825print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4826# shortlog: format_author_html('td', \%co, 10)4827 format_author_html('td', \%co,15,3) ."<td>";4828# originally git_history used chop_str($co{'title'}, 50)4829print format_subject_html($co{'title'},$co{'title_short'},4830 href(action=>"commit", hash=>$commit),$ref);4831print"</td>\n".4832"<td class=\"link\">".4833$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".4834$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");48354836if($ftypeeq'blob') {4837my$blob_current=$file_hash;4838my$blob_parent= git_get_hash_by_path($commit,$file_name);4839if(defined$blob_current&&defined$blob_parent&&4840$blob_currentne$blob_parent) {4841print" | ".4842$cgi->a({-href => href(action=>"blobdiff",4843 hash=>$blob_current, hash_parent=>$blob_parent,4844 hash_base=>$hash_base, hash_parent_base=>$commit,4845 file_name=>$file_name)},4846"diff to current");4847}4848}4849print"</td>\n".4850"</tr>\n";4851}4852if(defined$extra) {4853print"<tr>\n".4854"<td colspan=\"4\">$extra</td>\n".4855"</tr>\n";4856}4857print"</table>\n";4858}48594860sub git_tags_body {4861# uses global variable $project4862my($taglist,$from,$to,$extra) =@_;4863$from=0unlessdefined$from;4864$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);48654866print"<table class=\"tags\">\n";4867my$alternate=1;4868for(my$i=$from;$i<=$to;$i++) {4869my$entry=$taglist->[$i];4870my%tag=%$entry;4871my$comment=$tag{'subject'};4872my$comment_short;4873if(defined$comment) {4874$comment_short= chop_str($comment,30,5);4875}4876if($alternate) {4877print"<tr class=\"dark\">\n";4878}else{4879print"<tr class=\"light\">\n";4880}4881$alternate^=1;4882if(defined$tag{'age'}) {4883print"<td><i>$tag{'age'}</i></td>\n";4884}else{4885print"<td></td>\n";4886}4887print"<td>".4888$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),4889-class=>"list name"}, esc_html($tag{'name'})) .4890"</td>\n".4891"<td>";4892if(defined$comment) {4893print format_subject_html($comment,$comment_short,4894 href(action=>"tag", hash=>$tag{'id'}));4895}4896print"</td>\n".4897"<td class=\"selflink\">";4898if($tag{'type'}eq"tag") {4899print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");4900}else{4901print" ";4902}4903print"</td>\n".4904"<td class=\"link\">"." | ".4905$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});4906if($tag{'reftype'}eq"commit") {4907print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .4908" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");4909}elsif($tag{'reftype'}eq"blob") {4910print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");4911}4912print"</td>\n".4913"</tr>";4914}4915if(defined$extra) {4916print"<tr>\n".4917"<td colspan=\"5\">$extra</td>\n".4918"</tr>\n";4919}4920print"</table>\n";4921}49224923sub git_heads_body {4924# uses global variable $project4925my($headlist,$head,$from,$to,$extra) =@_;4926$from=0unlessdefined$from;4927$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);49284929print"<table class=\"heads\">\n";4930my$alternate=1;4931for(my$i=$from;$i<=$to;$i++) {4932my$entry=$headlist->[$i];4933my%ref=%$entry;4934my$curr=$ref{'id'}eq$head;4935if($alternate) {4936print"<tr class=\"dark\">\n";4937}else{4938print"<tr class=\"light\">\n";4939}4940$alternate^=1;4941print"<td><i>$ref{'age'}</i></td>\n".4942($curr?"<td class=\"current_head\">":"<td>") .4943$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),4944-class=>"list name"},esc_html($ref{'name'})) .4945"</td>\n".4946"<td class=\"link\">".4947$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".4948$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".4949$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})},"tree") .4950"</td>\n".4951"</tr>";4952}4953if(defined$extra) {4954print"<tr>\n".4955"<td colspan=\"3\">$extra</td>\n".4956"</tr>\n";4957}4958print"</table>\n";4959}49604961sub git_search_grep_body {4962my($commitlist,$from,$to,$extra) =@_;4963$from=0unlessdefined$from;4964$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);49654966print"<table class=\"commit_search\">\n";4967my$alternate=1;4968for(my$i=$from;$i<=$to;$i++) {4969my%co= %{$commitlist->[$i]};4970if(!%co) {4971next;4972}4973my$commit=$co{'id'};4974if($alternate) {4975print"<tr class=\"dark\">\n";4976}else{4977print"<tr class=\"light\">\n";4978}4979$alternate^=1;4980print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4981 format_author_html('td', \%co,15,5) .4982"<td>".4983$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),4984-class=>"list subject"},4985 chop_and_escape_str($co{'title'},50) ."<br/>");4986my$comment=$co{'comment'};4987foreachmy$line(@$comment) {4988if($line=~m/^(.*?)($search_regexp)(.*)$/i) {4989my($lead,$match,$trail) = ($1,$2,$3);4990$match= chop_str($match,70,5,'center');4991my$contextlen=int((80-length($match))/2);4992$contextlen=30if($contextlen>30);4993$lead= chop_str($lead,$contextlen,10,'left');4994$trail= chop_str($trail,$contextlen,10,'right');49954996$lead= esc_html($lead);4997$match= esc_html($match);4998$trail= esc_html($trail);49995000print"$lead<span class=\"match\">$match</span>$trail<br />";5001}5002}5003print"</td>\n".5004"<td class=\"link\">".5005$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .5006" | ".5007$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .5008" | ".5009$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");5010print"</td>\n".5011"</tr>\n";5012}5013if(defined$extra) {5014print"<tr>\n".5015"<td colspan=\"3\">$extra</td>\n".5016"</tr>\n";5017}5018print"</table>\n";5019}50205021## ======================================================================5022## ======================================================================5023## actions50245025sub git_project_list {5026my$order=$input_params{'order'};5027if(defined$order&&$order!~m/none|project|descr|owner|age/) {5028 die_error(400,"Unknown order parameter");5029}50305031my@list= git_get_projects_list();5032if(!@list) {5033 die_error(404,"No projects found");5034}50355036 git_header_html();5037if(defined$home_text&& -f $home_text) {5038print"<div class=\"index_include\">\n";5039 insert_file($home_text);5040print"</div>\n";5041}5042print$cgi->startform(-method=>"get") .5043"<p class=\"projsearch\">Search:\n".5044$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".5045"</p>".5046$cgi->end_form() ."\n";5047 git_project_list_body(\@list,$order);5048 git_footer_html();5049}50505051sub git_forks {5052my$order=$input_params{'order'};5053if(defined$order&&$order!~m/none|project|descr|owner|age/) {5054 die_error(400,"Unknown order parameter");5055}50565057my@list= git_get_projects_list($project);5058if(!@list) {5059 die_error(404,"No forks found");5060}50615062 git_header_html();5063 git_print_page_nav('','');5064 git_print_header_div('summary',"$projectforks");5065 git_project_list_body(\@list,$order);5066 git_footer_html();5067}50685069sub git_project_index {5070my@projects= git_get_projects_list($project);50715072print$cgi->header(5073-type =>'text/plain',5074-charset =>'utf-8',5075-content_disposition =>'inline; filename="index.aux"');50765077foreachmy$pr(@projects) {5078if(!exists$pr->{'owner'}) {5079$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");5080}50815082my($path,$owner) = ($pr->{'path'},$pr->{'owner'});5083# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '5084$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5085$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5086$path=~s/ /\+/g;5087$owner=~s/ /\+/g;50885089print"$path$owner\n";5090}5091}50925093sub git_summary {5094my$descr= git_get_project_description($project) ||"none";5095my%co= parse_commit("HEAD");5096my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();5097my$head=$co{'id'};50985099my$owner= git_get_project_owner($project);51005101my$refs= git_get_references();5102# These get_*_list functions return one more to allow us to see if5103# there are more ...5104my@taglist= git_get_tags_list(16);5105my@headlist= git_get_heads_list(16);5106my@forklist;5107my$check_forks= gitweb_check_feature('forks');51085109if($check_forks) {5110@forklist= git_get_projects_list($project);5111}51125113 git_header_html();5114 git_print_page_nav('summary','',$head);51155116print"<div class=\"title\"> </div>\n";5117print"<table class=\"projects_list\">\n".5118"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".5119"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";5120if(defined$cd{'rfc2822'}) {5121print"<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";5122}51235124# use per project git URL list in $projectroot/$project/cloneurl5125# or make project git URL from git base URL and project name5126my$url_tag="URL";5127my@url_list= git_get_project_url_list($project);5128@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;5129foreachmy$git_url(@url_list) {5130next unless$git_url;5131print"<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";5132$url_tag="";5133}51345135# Tag cloud5136my$show_ctags= gitweb_check_feature('ctags');5137if($show_ctags) {5138my$ctags= git_get_project_ctags($project);5139my$cloud= git_populate_project_tagcloud($ctags);5140print"<tr id=\"metadata_ctags\"><td>Content tags:<br />";5141print"</td>\n<td>"unless%$ctags;5142print"<form action=\"$show_ctags\"method=\"post\"><input type=\"hidden\"name=\"p\"value=\"$project\"/>Add: <input type=\"text\"name=\"t\"size=\"8\"/></form>";5143print"</td>\n<td>"if%$ctags;5144print git_show_project_tagcloud($cloud,48);5145print"</td></tr>";5146}51475148print"</table>\n";51495150# If XSS prevention is on, we don't include README.html.5151# TODO: Allow a readme in some safe format.5152if(!$prevent_xss&& -s "$projectroot/$project/README.html") {5153print"<div class=\"title\">readme</div>\n".5154"<div class=\"readme\">\n";5155 insert_file("$projectroot/$project/README.html");5156print"\n</div>\n";# class="readme"5157}51585159# we need to request one more than 16 (0..15) to check if5160# those 16 are all5161my@commitlist=$head? parse_commits($head,17) : ();5162if(@commitlist) {5163 git_print_header_div('shortlog');5164 git_shortlog_body(\@commitlist,0,15,$refs,5165$#commitlist<=15?undef:5166$cgi->a({-href => href(action=>"shortlog")},"..."));5167}51685169if(@taglist) {5170 git_print_header_div('tags');5171 git_tags_body(\@taglist,0,15,5172$#taglist<=15?undef:5173$cgi->a({-href => href(action=>"tags")},"..."));5174}51755176if(@headlist) {5177 git_print_header_div('heads');5178 git_heads_body(\@headlist,$head,0,15,5179$#headlist<=15?undef:5180$cgi->a({-href => href(action=>"heads")},"..."));5181}51825183if(@forklist) {5184 git_print_header_div('forks');5185 git_project_list_body(\@forklist,'age',0,15,5186$#forklist<=15?undef:5187$cgi->a({-href => href(action=>"forks")},"..."),5188'no_header');5189}51905191 git_footer_html();5192}51935194sub git_tag {5195my$head= git_get_head_hash($project);5196 git_header_html();5197 git_print_page_nav('','',$head,undef,$head);5198my%tag= parse_tag($hash);51995200if(!%tag) {5201 die_error(404,"Unknown tag object");5202}52035204 git_print_header_div('commit', esc_html($tag{'name'}),$hash);5205print"<div class=\"title_text\">\n".5206"<table class=\"object_header\">\n".5207"<tr>\n".5208"<td>object</td>\n".5209"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5210$tag{'object'}) ."</td>\n".5211"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5212$tag{'type'}) ."</td>\n".5213"</tr>\n";5214if(defined($tag{'author'})) {5215 git_print_authorship_rows(\%tag,'author');5216}5217print"</table>\n\n".5218"</div>\n";5219print"<div class=\"page_body\">";5220my$comment=$tag{'comment'};5221foreachmy$line(@$comment) {5222chomp$line;5223print esc_html($line, -nbsp=>1) ."<br/>\n";5224}5225print"</div>\n";5226 git_footer_html();5227}52285229sub git_blame_common {5230my$format=shift||'porcelain';5231if($formateq'porcelain'&&$cgi->param('js')) {5232$format='incremental';5233$action='blame_incremental';# for page title etc5234}52355236# permissions5237 gitweb_check_feature('blame')5238or die_error(403,"Blame view not allowed");52395240# error checking5241 die_error(400,"No file name given")unless$file_name;5242$hash_base||= git_get_head_hash($project);5243 die_error(404,"Couldn't find base commit")unless$hash_base;5244my%co= parse_commit($hash_base)5245or die_error(404,"Commit not found");5246my$ftype="blob";5247if(!defined$hash) {5248$hash= git_get_hash_by_path($hash_base,$file_name,"blob")5249or die_error(404,"Error looking up file");5250}else{5251$ftype= git_get_type($hash);5252if($ftype!~"blob") {5253 die_error(400,"Object is not a blob");5254}5255}52565257my$fd;5258if($formateq'incremental') {5259# get file contents (as base)5260open$fd,"-|", git_cmd(),'cat-file','blob',$hash5261or die_error(500,"Open git-cat-file failed");5262}elsif($formateq'data') {5263# run git-blame --incremental5264open$fd,"-|", git_cmd(),"blame","--incremental",5265$hash_base,"--",$file_name5266or die_error(500,"Open git-blame --incremental failed");5267}else{5268# run git-blame --porcelain5269open$fd,"-|", git_cmd(),"blame",'-p',5270$hash_base,'--',$file_name5271or die_error(500,"Open git-blame --porcelain failed");5272}52735274# incremental blame data returns early5275if($formateq'data') {5276print$cgi->header(5277-type=>"text/plain", -charset =>"utf-8",5278-status=>"200 OK");5279local$| =1;# output autoflush5280printwhile<$fd>;5281close$fd5282or print"ERROR$!\n";52835284print'END';5285if(defined$t0&& gitweb_check_feature('timed')) {5286print' '.5287 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).5288' '.$number_of_git_cmds;5289}5290print"\n";52915292return;5293}52945295# page header5296 git_header_html();5297my$formats_nav=5298$cgi->a({-href => href(action=>"blob", -replay=>1)},5299"blob") .5300" | ";5301if($formateq'incremental') {5302$formats_nav.=5303$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},5304"blame") ." (non-incremental)";5305}else{5306$formats_nav.=5307$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},5308"blame") ." (incremental)";5309}5310$formats_nav.=5311" | ".5312$cgi->a({-href => href(action=>"history", -replay=>1)},5313"history") .5314" | ".5315$cgi->a({-href => href(action=>$action, file_name=>$file_name)},5316"HEAD");5317 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5318 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5319 git_print_page_path($file_name,$ftype,$hash_base);53205321# page body5322if($formateq'incremental') {5323print"<noscript>\n<div class=\"error\"><center><b>\n".5324"This page requires JavaScript to run.\nUse ".5325$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},5326'this page').5327" instead.\n".5328"</b></center></div>\n</noscript>\n";53295330print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;5331}53325333print qq!<div class="page_body">\n!;5334print qq!<div id="progress_info">.../ ...</div>\n!5335if($formateq'incremental');5336print qq!<table id="blame_table"class="blame" width="100%">\n!.5337#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.5338 qq!<thead>\n!.5339 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.5340 qq!</thead>\n!.5341 qq!<tbody>\n!;53425343my@rev_color=qw(light dark);5344my$num_colors=scalar(@rev_color);5345my$current_color=0;53465347if($formateq'incremental') {5348my$color_class=$rev_color[$current_color];53495350#contents of a file5351my$linenr=0;5352 LINE:5353while(my$line= <$fd>) {5354chomp$line;5355$linenr++;53565357print qq!<tr id="l$linenr"class="$color_class">!.5358 qq!<td class="sha1"><a href=""> </a></td>!.5359 qq!<td class="linenr">!.5360 qq!<a class="linenr" href="">$linenr</a></td>!;5361print qq!<td class="pre">! . esc_html($line) ."</td>\n";5362print qq!</tr>\n!;5363}53645365}else{# porcelain, i.e. ordinary blame5366my%metainfo= ();# saves information about commits53675368# blame data5369 LINE:5370while(my$line= <$fd>) {5371chomp$line;5372# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]5373# no <lines in group> for subsequent lines in group of lines5374my($full_rev,$orig_lineno,$lineno,$group_size) =5375($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);5376if(!exists$metainfo{$full_rev}) {5377$metainfo{$full_rev} = {'nprevious'=>0};5378}5379my$meta=$metainfo{$full_rev};5380my$data;5381while($data= <$fd>) {5382chomp$data;5383last if($data=~s/^\t//);# contents of line5384if($data=~/^(\S+)(?: (.*))?$/) {5385$meta->{$1} =$2unlessexists$meta->{$1};5386}5387if($data=~/^previous /) {5388$meta->{'nprevious'}++;5389}5390}5391my$short_rev=substr($full_rev,0,8);5392my$author=$meta->{'author'};5393my%date=5394 parse_date($meta->{'author-time'},$meta->{'author-tz'});5395my$date=$date{'iso-tz'};5396if($group_size) {5397$current_color= ($current_color+1) %$num_colors;5398}5399my$tr_class=$rev_color[$current_color];5400$tr_class.=' boundary'if(exists$meta->{'boundary'});5401$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);5402$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);5403print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";5404if($group_size) {5405print"<td class=\"sha1\"";5406print" title=\"". esc_html($author) .",$date\"";5407print" rowspan=\"$group_size\""if($group_size>1);5408print">";5409print$cgi->a({-href => href(action=>"commit",5410 hash=>$full_rev,5411 file_name=>$file_name)},5412 esc_html($short_rev));5413if($group_size>=2) {5414my@author_initials= ($author=~/\b([[:upper:]])\B/g);5415if(@author_initials) {5416print"<br />".5417 esc_html(join('',@author_initials));5418# or join('.', ...)5419}5420}5421print"</td>\n";5422}5423# 'previous' <sha1 of parent commit> <filename at commit>5424if(exists$meta->{'previous'} &&5425$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {5426$meta->{'parent'} =$1;5427$meta->{'file_parent'} = unquote($2);5428}5429my$linenr_commit=5430exists($meta->{'parent'}) ?5431$meta->{'parent'} :$full_rev;5432my$linenr_filename=5433exists($meta->{'file_parent'}) ?5434$meta->{'file_parent'} : unquote($meta->{'filename'});5435my$blamed= href(action =>'blame',5436 file_name =>$linenr_filename,5437 hash_base =>$linenr_commit);5438print"<td class=\"linenr\">";5439print$cgi->a({ -href =>"$blamed#l$orig_lineno",5440-class=>"linenr"},5441 esc_html($lineno));5442print"</td>";5443print"<td class=\"pre\">". esc_html($data) ."</td>\n";5444print"</tr>\n";5445}# end while54465447}54485449# footer5450print"</tbody>\n".5451"</table>\n";# class="blame"5452print"</div>\n";# class="blame_body"5453close$fd5454or print"Reading blob failed\n";54555456 git_footer_html();5457}54585459sub git_blame {5460 git_blame_common();5461}54625463sub git_blame_incremental {5464 git_blame_common('incremental');5465}54665467sub git_blame_data {5468 git_blame_common('data');5469}54705471sub git_tags {5472my$head= git_get_head_hash($project);5473 git_header_html();5474 git_print_page_nav('','',$head,undef,$head);5475 git_print_header_div('summary',$project);54765477my@tagslist= git_get_tags_list();5478if(@tagslist) {5479 git_tags_body(\@tagslist);5480}5481 git_footer_html();5482}54835484sub git_heads {5485my$head= git_get_head_hash($project);5486 git_header_html();5487 git_print_page_nav('','',$head,undef,$head);5488 git_print_header_div('summary',$project);54895490my@headslist= git_get_heads_list();5491if(@headslist) {5492 git_heads_body(\@headslist,$head);5493}5494 git_footer_html();5495}54965497sub git_blob_plain {5498my$type=shift;5499my$expires;55005501if(!defined$hash) {5502if(defined$file_name) {5503my$base=$hash_base|| git_get_head_hash($project);5504$hash= git_get_hash_by_path($base,$file_name,"blob")5505or die_error(404,"Cannot find file");5506}else{5507 die_error(400,"No file name defined");5508}5509}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {5510# blobs defined by non-textual hash id's can be cached5511$expires="+1d";5512}55135514open my$fd,"-|", git_cmd(),"cat-file","blob",$hash5515or die_error(500,"Open git-cat-file blob '$hash' failed");55165517# content-type (can include charset)5518$type= blob_contenttype($fd,$file_name,$type);55195520# "save as" filename, even when no $file_name is given5521my$save_as="$hash";5522if(defined$file_name) {5523$save_as=$file_name;5524}elsif($type=~m/^text\//) {5525$save_as.='.txt';5526}55275528# With XSS prevention on, blobs of all types except a few known safe5529# ones are served with "Content-Disposition: attachment" to make sure5530# they don't run in our security domain. For certain image types,5531# blob view writes an <img> tag referring to blob_plain view, and we5532# want to be sure not to break that by serving the image as an5533# attachment (though Firefox 3 doesn't seem to care).5534my$sandbox=$prevent_xss&&5535$type!~m!^(?:text/plain|image/(?:gif|png|jpeg))$!;55365537print$cgi->header(5538-type =>$type,5539-expires =>$expires,5540-content_disposition =>5541($sandbox?'attachment':'inline')5542.'; filename="'.$save_as.'"');5543local$/=undef;5544binmode STDOUT,':raw';5545print<$fd>;5546binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi5547close$fd;5548}55495550sub git_blob {5551my$expires;55525553if(!defined$hash) {5554if(defined$file_name) {5555my$base=$hash_base|| git_get_head_hash($project);5556$hash= git_get_hash_by_path($base,$file_name,"blob")5557or die_error(404,"Cannot find file");5558}else{5559 die_error(400,"No file name defined");5560}5561}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {5562# blobs defined by non-textual hash id's can be cached5563$expires="+1d";5564}55655566my$have_blame= gitweb_check_feature('blame');5567open my$fd,"-|", git_cmd(),"cat-file","blob",$hash5568or die_error(500,"Couldn't cat$file_name,$hash");5569my$mimetype= blob_mimetype($fd,$file_name);5570# use 'blob_plain' (aka 'raw') view for files that cannot be displayed5571if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {5572close$fd;5573return git_blob_plain($mimetype);5574}5575# we can have blame only for text/* mimetype5576$have_blame&&= ($mimetype=~m!^text/!);55775578my$highlight= gitweb_check_feature('highlight');5579my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);5580$fd= run_highlighter($fd,$highlight,$syntax)5581if$syntax;55825583 git_header_html(undef,$expires);5584my$formats_nav='';5585if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5586if(defined$file_name) {5587if($have_blame) {5588$formats_nav.=5589$cgi->a({-href => href(action=>"blame", -replay=>1)},5590"blame") .5591" | ";5592}5593$formats_nav.=5594$cgi->a({-href => href(action=>"history", -replay=>1)},5595"history") .5596" | ".5597$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},5598"raw") .5599" | ".5600$cgi->a({-href => href(action=>"blob",5601 hash_base=>"HEAD", file_name=>$file_name)},5602"HEAD");5603}else{5604$formats_nav.=5605$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},5606"raw");5607}5608 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5609 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5610}else{5611print"<div class=\"page_nav\">\n".5612"<br/><br/></div>\n".5613"<div class=\"title\">$hash</div>\n";5614}5615 git_print_page_path($file_name,"blob",$hash_base);5616print"<div class=\"page_body\">\n";5617if($mimetype=~m!^image/!) {5618print qq!<img type="$mimetype"!;5619if($file_name) {5620print qq! alt="$file_name" title="$file_name"!;5621}5622print qq! src="! .5623 href(action=>"blob_plain", hash=>$hash,5624 hash_base=>$hash_base, file_name=>$file_name) .5625 qq!"/>\n!;5626}else{5627my$nr;5628while(my$line= <$fd>) {5629chomp$line;5630$nr++;5631$line= untabify($line);5632printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,5633$nr, href(-replay =>1),$nr,$nr,$syntax?$line: esc_html($line, -nbsp=>1);5634}5635}5636close$fd5637or print"Reading blob failed.\n";5638print"</div>";5639 git_footer_html();5640}56415642sub git_tree {5643if(!defined$hash_base) {5644$hash_base="HEAD";5645}5646if(!defined$hash) {5647if(defined$file_name) {5648$hash= git_get_hash_by_path($hash_base,$file_name,"tree");5649}else{5650$hash=$hash_base;5651}5652}5653 die_error(404,"No such tree")unlessdefined($hash);56545655my$show_sizes= gitweb_check_feature('show-sizes');5656my$have_blame= gitweb_check_feature('blame');56575658my@entries= ();5659{5660local$/="\0";5661open my$fd,"-|", git_cmd(),"ls-tree",'-z',5662($show_sizes?'-l': ()),@extra_options,$hash5663or die_error(500,"Open git-ls-tree failed");5664@entries=map{chomp;$_} <$fd>;5665close$fd5666or die_error(404,"Reading tree failed");5667}56685669my$refs= git_get_references();5670my$ref= format_ref_marker($refs,$hash_base);5671 git_header_html();5672my$basedir='';5673if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5674my@views_nav= ();5675if(defined$file_name) {5676push@views_nav,5677$cgi->a({-href => href(action=>"history", -replay=>1)},5678"history"),5679$cgi->a({-href => href(action=>"tree",5680 hash_base=>"HEAD", file_name=>$file_name)},5681"HEAD"),5682}5683my$snapshot_links= format_snapshot_links($hash);5684if(defined$snapshot_links) {5685# FIXME: Should be available when we have no hash base as well.5686push@views_nav,$snapshot_links;5687}5688 git_print_page_nav('tree','',$hash_base,undef,undef,5689join(' | ',@views_nav));5690 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);5691}else{5692undef$hash_base;5693print"<div class=\"page_nav\">\n";5694print"<br/><br/></div>\n";5695print"<div class=\"title\">$hash</div>\n";5696}5697if(defined$file_name) {5698$basedir=$file_name;5699if($basedirne''&&substr($basedir, -1)ne'/') {5700$basedir.='/';5701}5702 git_print_page_path($file_name,'tree',$hash_base);5703}5704print"<div class=\"page_body\">\n";5705print"<table class=\"tree\">\n";5706my$alternate=1;5707# '..' (top directory) link if possible5708if(defined$hash_base&&5709defined$file_name&&$file_name=~m![^/]+$!) {5710if($alternate) {5711print"<tr class=\"dark\">\n";5712}else{5713print"<tr class=\"light\">\n";5714}5715$alternate^=1;57165717my$up=$file_name;5718$up=~s!/?[^/]+$!!;5719undef$upunless$up;5720# based on git_print_tree_entry5721print'<td class="mode">'. mode_str('040000') ."</td>\n";5722print'<td class="size"> </td>'."\n"if$show_sizes;5723print'<td class="list">';5724print$cgi->a({-href => href(action=>"tree",5725 hash_base=>$hash_base,5726 file_name=>$up)},5727"..");5728print"</td>\n";5729print"<td class=\"link\"></td>\n";57305731print"</tr>\n";5732}5733foreachmy$line(@entries) {5734my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);57355736if($alternate) {5737print"<tr class=\"dark\">\n";5738}else{5739print"<tr class=\"light\">\n";5740}5741$alternate^=1;57425743 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);57445745print"</tr>\n";5746}5747print"</table>\n".5748"</div>";5749 git_footer_html();5750}57515752sub snapshot_name {5753my($project,$hash) =@_;57545755# path/to/project.git -> project5756# path/to/project/.git -> project5757my$name= to_utf8($project);5758$name=~ s,([^/])/*\.git$,$1,;5759$name= basename($name);5760# sanitize name5761$name=~s/[[:cntrl:]]/?/g;57625763my$ver=$hash;5764if($hash=~/^[0-9a-fA-F]+$/) {5765# shorten SHA-1 hash5766my$full_hash= git_get_full_hash($project,$hash);5767if($full_hash=~/^$hash/&&length($hash) >7) {5768$ver= git_get_short_hash($project,$hash);5769}5770}elsif($hash=~m!^refs/tags/(.*)$!) {5771# tags don't need shortened SHA-1 hash5772$ver=$1;5773}else{5774# branches and other need shortened SHA-1 hash5775if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {5776$ver=$1;5777}5778$ver.='-'. git_get_short_hash($project,$hash);5779}5780# in case of hierarchical branch names5781$ver=~s!/!.!g;57825783# name = project-version_string5784$name="$name-$ver";57855786returnwantarray? ($name,$name) :$name;5787}57885789sub git_snapshot {5790my$format=$input_params{'snapshot_format'};5791if(!@snapshot_fmts) {5792 die_error(403,"Snapshots not allowed");5793}5794# default to first supported snapshot format5795$format||=$snapshot_fmts[0];5796if($format!~m/^[a-z0-9]+$/) {5797 die_error(400,"Invalid snapshot format parameter");5798}elsif(!exists($known_snapshot_formats{$format})) {5799 die_error(400,"Unknown snapshot format");5800}elsif($known_snapshot_formats{$format}{'disabled'}) {5801 die_error(403,"Snapshot format not allowed");5802}elsif(!grep($_eq$format,@snapshot_fmts)) {5803 die_error(403,"Unsupported snapshot format");5804}58055806my$type= git_get_type("$hash^{}");5807if(!$type) {5808 die_error(404,'Object does not exist');5809}elsif($typeeq'blob') {5810 die_error(400,'Object is not a tree-ish');5811}58125813my($name,$prefix) = snapshot_name($project,$hash);5814my$filename="$name$known_snapshot_formats{$format}{'suffix'}";5815my$cmd= quote_command(5816 git_cmd(),'archive',5817"--format=$known_snapshot_formats{$format}{'format'}",5818"--prefix=$prefix/",$hash);5819if(exists$known_snapshot_formats{$format}{'compressor'}) {5820$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});5821}58225823$filename=~s/(["\\])/\\$1/g;5824print$cgi->header(5825-type =>$known_snapshot_formats{$format}{'type'},5826-content_disposition =>'inline; filename="'.$filename.'"',5827-status =>'200 OK');58285829open my$fd,"-|",$cmd5830or die_error(500,"Execute git-archive failed");5831binmode STDOUT,':raw';5832print<$fd>;5833binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi5834close$fd;5835}58365837sub git_log_generic {5838my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;58395840my$head= git_get_head_hash($project);5841if(!defined$base) {5842$base=$head;5843}5844if(!defined$page) {5845$page=0;5846}5847my$refs= git_get_references();58485849my$commit_hash=$base;5850if(defined$parent) {5851$commit_hash="$parent..$base";5852}5853my@commitlist=5854 parse_commits($commit_hash,101, (100*$page),5855defined$file_name? ($file_name,"--full-history") : ());58565857my$ftype;5858if(!defined$file_hash&&defined$file_name) {5859# some commits could have deleted file in question,5860# and not have it in tree, but one of them has to have it5861for(my$i=0;$i<@commitlist;$i++) {5862$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);5863last ifdefined$file_hash;5864}5865}5866if(defined$file_hash) {5867$ftype= git_get_type($file_hash);5868}5869if(defined$file_name&& !defined$ftype) {5870 die_error(500,"Unknown type of object");5871}5872my%co;5873if(defined$file_name) {5874%co= parse_commit($base)5875or die_error(404,"Unknown commit object");5876}587758785879my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);5880my$next_link='';5881if($#commitlist>=100) {5882$next_link=5883$cgi->a({-href => href(-replay=>1, page=>$page+1),5884-accesskey =>"n", -title =>"Alt-n"},"next");5885}5886my$patch_max= gitweb_get_feature('patches');5887if($patch_max&& !defined$file_name) {5888if($patch_max<0||@commitlist<=$patch_max) {5889$paging_nav.=" ⋅ ".5890$cgi->a({-href => href(action=>"patches", -replay=>1)},5891"patches");5892}5893}58945895 git_header_html();5896 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);5897if(defined$file_name) {5898 git_print_header_div('commit', esc_html($co{'title'}),$base);5899}else{5900 git_print_header_div('summary',$project)5901}5902 git_print_page_path($file_name,$ftype,$hash_base)5903if(defined$file_name);59045905$body_subr->(\@commitlist,0,99,$refs,$next_link,5906$file_name,$file_hash,$ftype);59075908 git_footer_html();5909}59105911sub git_log {5912 git_log_generic('log', \&git_log_body,5913$hash,$hash_parent);5914}59155916sub git_commit {5917$hash||=$hash_base||"HEAD";5918my%co= parse_commit($hash)5919or die_error(404,"Unknown commit object");59205921my$parent=$co{'parent'};5922my$parents=$co{'parents'};# listref59235924# we need to prepare $formats_nav before any parameter munging5925my$formats_nav;5926if(!defined$parent) {5927# --root commitdiff5928$formats_nav.='(initial)';5929}elsif(@$parents==1) {5930# single parent commit5931$formats_nav.=5932'(parent: '.5933$cgi->a({-href => href(action=>"commit",5934 hash=>$parent)},5935 esc_html(substr($parent,0,7))) .5936')';5937}else{5938# merge commit5939$formats_nav.=5940'(merge: '.5941join(' ',map{5942$cgi->a({-href => href(action=>"commit",5943 hash=>$_)},5944 esc_html(substr($_,0,7)));5945}@$parents) .5946')';5947}5948if(gitweb_check_feature('patches') &&@$parents<=1) {5949$formats_nav.=" | ".5950$cgi->a({-href => href(action=>"patch", -replay=>1)},5951"patch");5952}59535954if(!defined$parent) {5955$parent="--root";5956}5957my@difftree;5958open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",5959@diff_opts,5960(@$parents<=1?$parent:'-c'),5961$hash,"--"5962or die_error(500,"Open git-diff-tree failed");5963@difftree=map{chomp;$_} <$fd>;5964close$fdor die_error(404,"Reading git-diff-tree failed");59655966# non-textual hash id's can be cached5967my$expires;5968if($hash=~m/^[0-9a-fA-F]{40}$/) {5969$expires="+1d";5970}5971my$refs= git_get_references();5972my$ref= format_ref_marker($refs,$co{'id'});59735974 git_header_html(undef,$expires);5975 git_print_page_nav('commit','',5976$hash,$co{'tree'},$hash,5977$formats_nav);59785979if(defined$co{'parent'}) {5980 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);5981}else{5982 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);5983}5984print"<div class=\"title_text\">\n".5985"<table class=\"object_header\">\n";5986 git_print_authorship_rows(\%co);5987print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";5988print"<tr>".5989"<td>tree</td>".5990"<td class=\"sha1\">".5991$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),5992class=>"list"},$co{'tree'}) .5993"</td>".5994"<td class=\"link\">".5995$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},5996"tree");5997my$snapshot_links= format_snapshot_links($hash);5998if(defined$snapshot_links) {5999print" | ".$snapshot_links;6000}6001print"</td>".6002"</tr>\n";60036004foreachmy$par(@$parents) {6005print"<tr>".6006"<td>parent</td>".6007"<td class=\"sha1\">".6008$cgi->a({-href => href(action=>"commit", hash=>$par),6009class=>"list"},$par) .6010"</td>".6011"<td class=\"link\">".6012$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .6013" | ".6014$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .6015"</td>".6016"</tr>\n";6017}6018print"</table>".6019"</div>\n";60206021print"<div class=\"page_body\">\n";6022 git_print_log($co{'comment'});6023print"</div>\n";60246025 git_difftree_body(\@difftree,$hash,@$parents);60266027 git_footer_html();6028}60296030sub git_object {6031# object is defined by:6032# - hash or hash_base alone6033# - hash_base and file_name6034my$type;60356036# - hash or hash_base alone6037if($hash|| ($hash_base&& !defined$file_name)) {6038my$object_id=$hash||$hash_base;60396040open my$fd,"-|", quote_command(6041 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'6042or die_error(404,"Object does not exist");6043$type= <$fd>;6044chomp$type;6045close$fd6046or die_error(404,"Object does not exist");60476048# - hash_base and file_name6049}elsif($hash_base&&defined$file_name) {6050$file_name=~ s,/+$,,;60516052system(git_cmd(),"cat-file",'-e',$hash_base) ==06053or die_error(404,"Base object does not exist");60546055# here errors should not hapen6056open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name6057or die_error(500,"Open git-ls-tree failed");6058my$line= <$fd>;6059close$fd;60606061#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'6062unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {6063 die_error(404,"File or directory for given base does not exist");6064}6065$type=$2;6066$hash=$3;6067}else{6068 die_error(400,"Not enough information to find object");6069}60706071print$cgi->redirect(-uri => href(action=>$type, -full=>1,6072 hash=>$hash, hash_base=>$hash_base,6073 file_name=>$file_name),6074-status =>'302 Found');6075}60766077sub git_blobdiff {6078my$format=shift||'html';60796080my$fd;6081my@difftree;6082my%diffinfo;6083my$expires;60846085# preparing $fd and %diffinfo for git_patchset_body6086# new style URI6087if(defined$hash_base&&defined$hash_parent_base) {6088if(defined$file_name) {6089# read raw output6090open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6091$hash_parent_base,$hash_base,6092"--", (defined$file_parent?$file_parent: ()),$file_name6093or die_error(500,"Open git-diff-tree failed");6094@difftree=map{chomp;$_} <$fd>;6095close$fd6096or die_error(404,"Reading git-diff-tree failed");6097@difftree6098or die_error(404,"Blob diff not found");60996100}elsif(defined$hash&&6101$hash=~/[0-9a-fA-F]{40}/) {6102# try to find filename from $hash61036104# read filtered raw output6105open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6106$hash_parent_base,$hash_base,"--"6107or die_error(500,"Open git-diff-tree failed");6108@difftree=6109# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'6110# $hash == to_id6111grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}6112map{chomp;$_} <$fd>;6113close$fd6114or die_error(404,"Reading git-diff-tree failed");6115@difftree6116or die_error(404,"Blob diff not found");61176118}else{6119 die_error(400,"Missing one of the blob diff parameters");6120}61216122if(@difftree>1) {6123 die_error(400,"Ambiguous blob diff specification");6124}61256126%diffinfo= parse_difftree_raw_line($difftree[0]);6127$file_parent||=$diffinfo{'from_file'} ||$file_name;6128$file_name||=$diffinfo{'to_file'};61296130$hash_parent||=$diffinfo{'from_id'};6131$hash||=$diffinfo{'to_id'};61326133# non-textual hash id's can be cached6134if($hash_base=~m/^[0-9a-fA-F]{40}$/&&6135$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {6136$expires='+1d';6137}61386139# open patch output6140open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6141'-p', ($formateq'html'?"--full-index": ()),6142$hash_parent_base,$hash_base,6143"--", (defined$file_parent?$file_parent: ()),$file_name6144or die_error(500,"Open git-diff-tree failed");6145}61466147# old/legacy style URI -- not generated anymore since 1.4.3.6148if(!%diffinfo) {6149 die_error('404 Not Found',"Missing one of the blob diff parameters")6150}61516152# header6153if($formateq'html') {6154my$formats_nav=6155$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},6156"raw");6157 git_header_html(undef,$expires);6158if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6159 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6160 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6161}else{6162print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";6163print"<div class=\"title\">$hashvs$hash_parent</div>\n";6164}6165if(defined$file_name) {6166 git_print_page_path($file_name,"blob",$hash_base);6167}else{6168print"<div class=\"page_path\"></div>\n";6169}61706171}elsif($formateq'plain') {6172print$cgi->header(6173-type =>'text/plain',6174-charset =>'utf-8',6175-expires =>$expires,6176-content_disposition =>'inline; filename="'."$file_name".'.patch"');61776178print"X-Git-Url: ".$cgi->self_url() ."\n\n";61796180}else{6181 die_error(400,"Unknown blobdiff format");6182}61836184# patch6185if($formateq'html') {6186print"<div class=\"page_body\">\n";61876188 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);6189close$fd;61906191print"</div>\n";# class="page_body"6192 git_footer_html();61936194}else{6195while(my$line= <$fd>) {6196$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;6197$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;61986199print$line;62006201last if$line=~m!^\+\+\+!;6202}6203local$/=undef;6204print<$fd>;6205close$fd;6206}6207}62086209sub git_blobdiff_plain {6210 git_blobdiff('plain');6211}62126213sub git_commitdiff {6214my%params=@_;6215my$format=$params{-format} ||'html';62166217my($patch_max) = gitweb_get_feature('patches');6218if($formateq'patch') {6219 die_error(403,"Patch view not allowed")unless$patch_max;6220}62216222$hash||=$hash_base||"HEAD";6223my%co= parse_commit($hash)6224or die_error(404,"Unknown commit object");62256226# choose format for commitdiff for merge6227if(!defined$hash_parent&& @{$co{'parents'}} >1) {6228$hash_parent='--cc';6229}6230# we need to prepare $formats_nav before almost any parameter munging6231my$formats_nav;6232if($formateq'html') {6233$formats_nav=6234$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},6235"raw");6236if($patch_max&& @{$co{'parents'}} <=1) {6237$formats_nav.=" | ".6238$cgi->a({-href => href(action=>"patch", -replay=>1)},6239"patch");6240}62416242if(defined$hash_parent&&6243$hash_parentne'-c'&&$hash_parentne'--cc') {6244# commitdiff with two commits given6245my$hash_parent_short=$hash_parent;6246if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {6247$hash_parent_short=substr($hash_parent,0,7);6248}6249$formats_nav.=6250' (from';6251for(my$i=0;$i< @{$co{'parents'}};$i++) {6252if($co{'parents'}[$i]eq$hash_parent) {6253$formats_nav.=' parent '. ($i+1);6254last;6255}6256}6257$formats_nav.=': '.6258$cgi->a({-href => href(action=>"commitdiff",6259 hash=>$hash_parent)},6260 esc_html($hash_parent_short)) .6261')';6262}elsif(!$co{'parent'}) {6263# --root commitdiff6264$formats_nav.=' (initial)';6265}elsif(scalar@{$co{'parents'}} ==1) {6266# single parent commit6267$formats_nav.=6268' (parent: '.6269$cgi->a({-href => href(action=>"commitdiff",6270 hash=>$co{'parent'})},6271 esc_html(substr($co{'parent'},0,7))) .6272')';6273}else{6274# merge commit6275if($hash_parenteq'--cc') {6276$formats_nav.=' | '.6277$cgi->a({-href => href(action=>"commitdiff",6278 hash=>$hash, hash_parent=>'-c')},6279'combined');6280}else{# $hash_parent eq '-c'6281$formats_nav.=' | '.6282$cgi->a({-href => href(action=>"commitdiff",6283 hash=>$hash, hash_parent=>'--cc')},6284'compact');6285}6286$formats_nav.=6287' (merge: '.6288join(' ',map{6289$cgi->a({-href => href(action=>"commitdiff",6290 hash=>$_)},6291 esc_html(substr($_,0,7)));6292} @{$co{'parents'}} ) .6293')';6294}6295}62966297my$hash_parent_param=$hash_parent;6298if(!defined$hash_parent_param) {6299# --cc for multiple parents, --root for parentless6300$hash_parent_param=6301@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';6302}63036304# read commitdiff6305my$fd;6306my@difftree;6307if($formateq'html') {6308open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6309"--no-commit-id","--patch-with-raw","--full-index",6310$hash_parent_param,$hash,"--"6311or die_error(500,"Open git-diff-tree failed");63126313while(my$line= <$fd>) {6314chomp$line;6315# empty line ends raw part of diff-tree output6316last unless$line;6317push@difftree,scalar parse_difftree_raw_line($line);6318}63196320}elsif($formateq'plain') {6321open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6322'-p',$hash_parent_param,$hash,"--"6323or die_error(500,"Open git-diff-tree failed");6324}elsif($formateq'patch') {6325# For commit ranges, we limit the output to the number of6326# patches specified in the 'patches' feature.6327# For single commits, we limit the output to a single patch,6328# diverging from the git-format-patch default.6329my@commit_spec= ();6330if($hash_parent) {6331if($patch_max>0) {6332push@commit_spec,"-$patch_max";6333}6334push@commit_spec,'-n',"$hash_parent..$hash";6335}else{6336if($params{-single}) {6337push@commit_spec,'-1';6338}else{6339if($patch_max>0) {6340push@commit_spec,"-$patch_max";6341}6342push@commit_spec,"-n";6343}6344push@commit_spec,'--root',$hash;6345}6346open$fd,"-|", git_cmd(),"format-patch",@diff_opts,6347'--encoding=utf8','--stdout',@commit_spec6348or die_error(500,"Open git-format-patch failed");6349}else{6350 die_error(400,"Unknown commitdiff format");6351}63526353# non-textual hash id's can be cached6354my$expires;6355if($hash=~m/^[0-9a-fA-F]{40}$/) {6356$expires="+1d";6357}63586359# write commit message6360if($formateq'html') {6361my$refs= git_get_references();6362my$ref= format_ref_marker($refs,$co{'id'});63636364 git_header_html(undef,$expires);6365 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);6366 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);6367print"<div class=\"title_text\">\n".6368"<table class=\"object_header\">\n";6369 git_print_authorship_rows(\%co);6370print"</table>".6371"</div>\n";6372print"<div class=\"page_body\">\n";6373if(@{$co{'comment'}} >1) {6374print"<div class=\"log\">\n";6375 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);6376print"</div>\n";# class="log"6377}63786379}elsif($formateq'plain') {6380my$refs= git_get_references("tags");6381my$tagname= git_get_rev_name_tags($hash);6382my$filename= basename($project) ."-$hash.patch";63836384print$cgi->header(6385-type =>'text/plain',6386-charset =>'utf-8',6387-expires =>$expires,6388-content_disposition =>'inline; filename="'."$filename".'"');6389my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});6390print"From: ". to_utf8($co{'author'}) ."\n";6391print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";6392print"Subject: ". to_utf8($co{'title'}) ."\n";63936394print"X-Git-Tag:$tagname\n"if$tagname;6395print"X-Git-Url: ".$cgi->self_url() ."\n\n";63966397foreachmy$line(@{$co{'comment'}}) {6398print to_utf8($line) ."\n";6399}6400print"---\n\n";6401}elsif($formateq'patch') {6402my$filename= basename($project) ."-$hash.patch";64036404print$cgi->header(6405-type =>'text/plain',6406-charset =>'utf-8',6407-expires =>$expires,6408-content_disposition =>'inline; filename="'."$filename".'"');6409}64106411# write patch6412if($formateq'html') {6413my$use_parents= !defined$hash_parent||6414$hash_parenteq'-c'||$hash_parenteq'--cc';6415 git_difftree_body(\@difftree,$hash,6416$use_parents? @{$co{'parents'}} :$hash_parent);6417print"<br/>\n";64186419 git_patchset_body($fd, \@difftree,$hash,6420$use_parents? @{$co{'parents'}} :$hash_parent);6421close$fd;6422print"</div>\n";# class="page_body"6423 git_footer_html();64246425}elsif($formateq'plain') {6426local$/=undef;6427print<$fd>;6428close$fd6429or print"Reading git-diff-tree failed\n";6430}elsif($formateq'patch') {6431local$/=undef;6432print<$fd>;6433close$fd6434or print"Reading git-format-patch failed\n";6435}6436}64376438sub git_commitdiff_plain {6439 git_commitdiff(-format =>'plain');6440}64416442# format-patch-style patches6443sub git_patch {6444 git_commitdiff(-format =>'patch', -single =>1);6445}64466447sub git_patches {6448 git_commitdiff(-format =>'patch');6449}64506451sub git_history {6452 git_log_generic('history', \&git_history_body,6453$hash_base,$hash_parent_base,6454$file_name,$hash);6455}64566457sub git_search {6458 gitweb_check_feature('search')or die_error(403,"Search is disabled");6459if(!defined$searchtext) {6460 die_error(400,"Text field is empty");6461}6462if(!defined$hash) {6463$hash= git_get_head_hash($project);6464}6465my%co= parse_commit($hash);6466if(!%co) {6467 die_error(404,"Unknown commit object");6468}6469if(!defined$page) {6470$page=0;6471}64726473$searchtype||='commit';6474if($searchtypeeq'pickaxe') {6475# pickaxe may take all resources of your box and run for several minutes6476# with every query - so decide by yourself how public you make this feature6477 gitweb_check_feature('pickaxe')6478or die_error(403,"Pickaxe is disabled");6479}6480if($searchtypeeq'grep') {6481 gitweb_check_feature('grep')6482or die_error(403,"Grep is disabled");6483}64846485 git_header_html();64866487if($searchtypeeq'commit'or$searchtypeeq'author'or$searchtypeeq'committer') {6488my$greptype;6489if($searchtypeeq'commit') {6490$greptype="--grep=";6491}elsif($searchtypeeq'author') {6492$greptype="--author=";6493}elsif($searchtypeeq'committer') {6494$greptype="--committer=";6495}6496$greptype.=$searchtext;6497my@commitlist= parse_commits($hash,101, (100*$page),undef,6498$greptype,'--regexp-ignore-case',6499$search_use_regexp?'--extended-regexp':'--fixed-strings');65006501my$paging_nav='';6502if($page>0) {6503$paging_nav.=6504$cgi->a({-href => href(action=>"search", hash=>$hash,6505 searchtext=>$searchtext,6506 searchtype=>$searchtype)},6507"first");6508$paging_nav.=" ⋅ ".6509$cgi->a({-href => href(-replay=>1, page=>$page-1),6510-accesskey =>"p", -title =>"Alt-p"},"prev");6511}else{6512$paging_nav.="first";6513$paging_nav.=" ⋅ prev";6514}6515my$next_link='';6516if($#commitlist>=100) {6517$next_link=6518$cgi->a({-href => href(-replay=>1, page=>$page+1),6519-accesskey =>"n", -title =>"Alt-n"},"next");6520$paging_nav.=" ⋅$next_link";6521}else{6522$paging_nav.=" ⋅ next";6523}65246525if($#commitlist>=100) {6526}65276528 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);6529 git_print_header_div('commit', esc_html($co{'title'}),$hash);6530 git_search_grep_body(\@commitlist,0,99,$next_link);6531}65326533if($searchtypeeq'pickaxe') {6534 git_print_page_nav('','',$hash,$co{'tree'},$hash);6535 git_print_header_div('commit', esc_html($co{'title'}),$hash);65366537print"<table class=\"pickaxe search\">\n";6538my$alternate=1;6539local$/="\n";6540open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,6541'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",6542($search_use_regexp?'--pickaxe-regex': ());6543undef%co;6544my@files;6545while(my$line= <$fd>) {6546chomp$line;6547next unless$line;65486549my%set= parse_difftree_raw_line($line);6550if(defined$set{'commit'}) {6551# finish previous commit6552if(%co) {6553print"</td>\n".6554"<td class=\"link\">".6555$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6556" | ".6557$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6558print"</td>\n".6559"</tr>\n";6560}65616562if($alternate) {6563print"<tr class=\"dark\">\n";6564}else{6565print"<tr class=\"light\">\n";6566}6567$alternate^=1;6568%co= parse_commit($set{'commit'});6569my$author= chop_and_escape_str($co{'author_name'},15,5);6570print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6571"<td><i>$author</i></td>\n".6572"<td>".6573$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6574-class=>"list subject"},6575 chop_and_escape_str($co{'title'},50) ."<br/>");6576}elsif(defined$set{'to_id'}) {6577next if($set{'to_id'} =~m/^0{40}$/);65786579print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},6580 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),6581-class=>"list"},6582"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .6583"<br/>\n";6584}6585}6586close$fd;65876588# finish last commit (warning: repetition!)6589if(%co) {6590print"</td>\n".6591"<td class=\"link\">".6592$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6593" | ".6594$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6595print"</td>\n".6596"</tr>\n";6597}65986599print"</table>\n";6600}66016602if($searchtypeeq'grep') {6603 git_print_page_nav('','',$hash,$co{'tree'},$hash);6604 git_print_header_div('commit', esc_html($co{'title'}),$hash);66056606print"<table class=\"grep_search\">\n";6607my$alternate=1;6608my$matches=0;6609local$/="\n";6610open my$fd,"-|", git_cmd(),'grep','-n',6611$search_use_regexp? ('-E','-i') :'-F',6612$searchtext,$co{'tree'};6613my$lastfile='';6614while(my$line= <$fd>) {6615chomp$line;6616my($file,$lno,$ltext,$binary);6617last if($matches++>1000);6618if($line=~/^Binary file (.+) matches$/) {6619$file=$1;6620$binary=1;6621}else{6622(undef,$file,$lno,$ltext) =split(/:/,$line,4);6623}6624if($filene$lastfile) {6625$lastfileand print"</td></tr>\n";6626if($alternate++) {6627print"<tr class=\"dark\">\n";6628}else{6629print"<tr class=\"light\">\n";6630}6631print"<td class=\"list\">".6632$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},6633 file_name=>"$file"),6634-class=>"list"}, esc_path($file));6635print"</td><td>\n";6636$lastfile=$file;6637}6638if($binary) {6639print"<div class=\"binary\">Binary file</div>\n";6640}else{6641$ltext= untabify($ltext);6642if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6643$ltext= esc_html($1, -nbsp=>1);6644$ltext.='<span class="match">';6645$ltext.= esc_html($2, -nbsp=>1);6646$ltext.='</span>';6647$ltext.= esc_html($3, -nbsp=>1);6648}else{6649$ltext= esc_html($ltext, -nbsp=>1);6650}6651print"<div class=\"pre\">".6652$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},6653 file_name=>"$file").'#l'.$lno,6654-class=>"linenr"},sprintf('%4i',$lno))6655.' '.$ltext."</div>\n";6656}6657}6658if($lastfile) {6659print"</td></tr>\n";6660if($matches>1000) {6661print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6662}6663}else{6664print"<div class=\"diff nodifferences\">No matches found</div>\n";6665}6666close$fd;66676668print"</table>\n";6669}6670 git_footer_html();6671}66726673sub git_search_help {6674 git_header_html();6675 git_print_page_nav('','',$hash,$hash,$hash);6676print<<EOT;6677<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without6678regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,6679the pattern entered is recognized as the POSIX extended6680<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case6681insensitive).</p>6682<dl>6683<dt><b>commit</b></dt>6684<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>6685EOT6686my$have_grep= gitweb_check_feature('grep');6687if($have_grep) {6688print<<EOT;6689<dt><b>grep</b></dt>6690<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing6691 a different one) are searched for the given pattern. On large trees, this search can take6692a while and put some strain on the server, so please use it with some consideration. Note that6693due to git-grep peculiarity, currently if regexp mode is turned off, the matches are6694case-sensitive.</dd>6695EOT6696}6697print<<EOT;6698<dt><b>author</b></dt>6699<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>6700<dt><b>committer</b></dt>6701<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>6702EOT6703my$have_pickaxe= gitweb_check_feature('pickaxe');6704if($have_pickaxe) {6705print<<EOT;6706<dt><b>pickaxe</b></dt>6707<dd>All commits that caused the string to appear or disappear from any file (changes that6708added, removed or "modified" the string) will be listed. This search can take a while and6709takes a lot of strain on the server, so please use it wisely. Note that since you may be6710interested even in changes just changing the case as well, this search is case sensitive.</dd>6711EOT6712}6713print"</dl>\n";6714 git_footer_html();6715}67166717sub git_shortlog {6718 git_log_generic('shortlog', \&git_shortlog_body,6719$hash,$hash_parent);6720}67216722## ......................................................................6723## feeds (RSS, Atom; OPML)67246725sub git_feed {6726my$format=shift||'atom';6727my$have_blame= gitweb_check_feature('blame');67286729# Atom: http://www.atomenabled.org/developers/syndication/6730# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ6731if($formatne'rss'&&$formatne'atom') {6732 die_error(400,"Unknown web feed format");6733}67346735# log/feed of current (HEAD) branch, log of given branch, history of file/directory6736my$head=$hash||'HEAD';6737my@commitlist= parse_commits($head,150,0,$file_name);67386739my%latest_commit;6740my%latest_date;6741my$content_type="application/$format+xml";6742if(defined$cgi->http('HTTP_ACCEPT') &&6743$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {6744# browser (feed reader) prefers text/xml6745$content_type='text/xml';6746}6747if(defined($commitlist[0])) {6748%latest_commit= %{$commitlist[0]};6749my$latest_epoch=$latest_commit{'committer_epoch'};6750%latest_date= parse_date($latest_epoch);6751my$if_modified=$cgi->http('IF_MODIFIED_SINCE');6752if(defined$if_modified) {6753my$since;6754if(eval{require HTTP::Date;1; }) {6755$since= HTTP::Date::str2time($if_modified);6756}elsif(eval{require Time::ParseDate;1; }) {6757$since= Time::ParseDate::parsedate($if_modified, GMT =>1);6758}6759if(defined$since&&$latest_epoch<=$since) {6760print$cgi->header(6761-type =>$content_type,6762-charset =>'utf-8',6763-last_modified =>$latest_date{'rfc2822'},6764-status =>'304 Not Modified');6765return;6766}6767}6768print$cgi->header(6769-type =>$content_type,6770-charset =>'utf-8',6771-last_modified =>$latest_date{'rfc2822'});6772}else{6773print$cgi->header(6774-type =>$content_type,6775-charset =>'utf-8');6776}67776778# Optimization: skip generating the body if client asks only6779# for Last-Modified date.6780return if($cgi->request_method()eq'HEAD');67816782# header variables6783my$title="$site_name-$project/$action";6784my$feed_type='log';6785if(defined$hash) {6786$title.=" - '$hash'";6787$feed_type='branch log';6788if(defined$file_name) {6789$title.=" ::$file_name";6790$feed_type='history';6791}6792}elsif(defined$file_name) {6793$title.=" -$file_name";6794$feed_type='history';6795}6796$title.="$feed_type";6797my$descr= git_get_project_description($project);6798if(defined$descr) {6799$descr= esc_html($descr);6800}else{6801$descr="$project".6802($formateq'rss'?'RSS':'Atom') .6803" feed";6804}6805my$owner= git_get_project_owner($project);6806$owner= esc_html($owner);68076808#header6809my$alt_url;6810if(defined$file_name) {6811$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);6812}elsif(defined$hash) {6813$alt_url= href(-full=>1, action=>"log", hash=>$hash);6814}else{6815$alt_url= href(-full=>1, action=>"summary");6816}6817print qq!<?xml version="1.0" encoding="utf-8"?>\n!;6818if($formateq'rss') {6819print<<XML;6820<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">6821<channel>6822XML6823print"<title>$title</title>\n".6824"<link>$alt_url</link>\n".6825"<description>$descr</description>\n".6826"<language>en</language>\n".6827# project owner is responsible for 'editorial' content6828"<managingEditor>$owner</managingEditor>\n";6829if(defined$logo||defined$favicon) {6830# prefer the logo to the favicon, since RSS6831# doesn't allow both6832my$img= esc_url($logo||$favicon);6833print"<image>\n".6834"<url>$img</url>\n".6835"<title>$title</title>\n".6836"<link>$alt_url</link>\n".6837"</image>\n";6838}6839if(%latest_date) {6840print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";6841print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";6842}6843print"<generator>gitweb v.$version/$git_version</generator>\n";6844}elsif($formateq'atom') {6845print<<XML;6846<feed xmlns="http://www.w3.org/2005/Atom">6847XML6848print"<title>$title</title>\n".6849"<subtitle>$descr</subtitle>\n".6850'<link rel="alternate" type="text/html" href="'.6851$alt_url.'" />'."\n".6852'<link rel="self" type="'.$content_type.'" href="'.6853$cgi->self_url() .'" />'."\n".6854"<id>". href(-full=>1) ."</id>\n".6855# use project owner for feed author6856"<author><name>$owner</name></author>\n";6857if(defined$favicon) {6858print"<icon>". esc_url($favicon) ."</icon>\n";6859}6860if(defined$logo_url) {6861# not twice as wide as tall: 72 x 27 pixels6862print"<logo>". esc_url($logo) ."</logo>\n";6863}6864if(!%latest_date) {6865# dummy date to keep the feed valid until commits trickle in:6866print"<updated>1970-01-01T00:00:00Z</updated>\n";6867}else{6868print"<updated>$latest_date{'iso-8601'}</updated>\n";6869}6870print"<generator version='$version/$git_version'>gitweb</generator>\n";6871}68726873# contents6874for(my$i=0;$i<=$#commitlist;$i++) {6875my%co= %{$commitlist[$i]};6876my$commit=$co{'id'};6877# we read 150, we always show 30 and the ones more recent than 48 hours6878if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {6879last;6880}6881my%cd= parse_date($co{'author_epoch'});68826883# get list of changed files6884open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6885$co{'parent'} ||"--root",6886$co{'id'},"--", (defined$file_name?$file_name: ())6887ornext;6888my@difftree=map{chomp;$_} <$fd>;6889close$fd6890ornext;68916892# print element (entry, item)6893my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);6894if($formateq'rss') {6895print"<item>\n".6896"<title>". esc_html($co{'title'}) ."</title>\n".6897"<author>". esc_html($co{'author'}) ."</author>\n".6898"<pubDate>$cd{'rfc2822'}</pubDate>\n".6899"<guid isPermaLink=\"true\">$co_url</guid>\n".6900"<link>$co_url</link>\n".6901"<description>". esc_html($co{'title'}) ."</description>\n".6902"<content:encoded>".6903"<![CDATA[\n";6904}elsif($formateq'atom') {6905print"<entry>\n".6906"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".6907"<updated>$cd{'iso-8601'}</updated>\n".6908"<author>\n".6909" <name>". esc_html($co{'author_name'}) ."</name>\n";6910if($co{'author_email'}) {6911print" <email>". esc_html($co{'author_email'}) ."</email>\n";6912}6913print"</author>\n".6914# use committer for contributor6915"<contributor>\n".6916" <name>". esc_html($co{'committer_name'}) ."</name>\n";6917if($co{'committer_email'}) {6918print" <email>". esc_html($co{'committer_email'}) ."</email>\n";6919}6920print"</contributor>\n".6921"<published>$cd{'iso-8601'}</published>\n".6922"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".6923"<id>$co_url</id>\n".6924"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".6925"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";6926}6927my$comment=$co{'comment'};6928print"<pre>\n";6929foreachmy$line(@$comment) {6930$line= esc_html($line);6931print"$line\n";6932}6933print"</pre><ul>\n";6934foreachmy$difftree_line(@difftree) {6935my%difftree= parse_difftree_raw_line($difftree_line);6936next if!$difftree{'from_id'};69376938my$file=$difftree{'file'} ||$difftree{'to_file'};69396940print"<li>".6941"[".6942$cgi->a({-href => href(-full=>1, action=>"blobdiff",6943 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},6944 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},6945 file_name=>$file, file_parent=>$difftree{'from_file'}),6946-title =>"diff"},'D');6947if($have_blame) {6948print$cgi->a({-href => href(-full=>1, action=>"blame",6949 file_name=>$file, hash_base=>$commit),6950-title =>"blame"},'B');6951}6952# if this is not a feed of a file history6953if(!defined$file_name||$file_namene$file) {6954print$cgi->a({-href => href(-full=>1, action=>"history",6955 file_name=>$file, hash=>$commit),6956-title =>"history"},'H');6957}6958$file= esc_path($file);6959print"] ".6960"$file</li>\n";6961}6962if($formateq'rss') {6963print"</ul>]]>\n".6964"</content:encoded>\n".6965"</item>\n";6966}elsif($formateq'atom') {6967print"</ul>\n</div>\n".6968"</content>\n".6969"</entry>\n";6970}6971}69726973# end of feed6974if($formateq'rss') {6975print"</channel>\n</rss>\n";6976}elsif($formateq'atom') {6977print"</feed>\n";6978}6979}69806981sub git_rss {6982 git_feed('rss');6983}69846985sub git_atom {6986 git_feed('atom');6987}69886989sub git_opml {6990my@list= git_get_projects_list();69916992print$cgi->header(6993-type =>'text/xml',6994-charset =>'utf-8',6995-content_disposition =>'inline; filename="opml.xml"');69966997print<<XML;6998<?xml version="1.0" encoding="utf-8"?>6999<opml version="1.0">7000<head>7001 <title>$site_nameOPML Export</title>7002</head>7003<body>7004<outline text="git RSS feeds">7005XML70067007foreachmy$pr(@list) {7008my%proj=%$pr;7009my$head= git_get_head_hash($proj{'path'});7010if(!defined$head) {7011next;7012}7013$git_dir="$projectroot/$proj{'path'}";7014my%co= parse_commit($head);7015if(!%co) {7016next;7017}70187019my$path= esc_html(chop_str($proj{'path'},25,5));7020my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);7021my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);7022print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";7023}7024print<<XML;7025</outline>7026</body>7027</opml>7028XML7029}