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 run_request {1031our$t0= [Time::HiRes::gettimeofday()]1032ifdefined$t0;10331034 evaluate_uri();1035 evaluate_gitweb_config();1036 evaluate_git_version();1037 check_loadavg();10381039# $projectroot and $projects_list might be set in gitweb config file1040$projects_list||=$projectroot;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();10891090$pre_listen_hook->()1091if$pre_listen_hook;10921093 REQUEST:1094while($cgi=$CGI->new()) {1095$pre_dispatch_hook->()1096if$pre_dispatch_hook;10971098 run_request();10991100$pre_dispatch_hook->()1101if$post_dispatch_hook;11021103last REQUEST if($is_last_request->());1104}11051106 DONE_GITWEB:11071;1108}11091110run();11111112if(defined caller) {1113# wrapped in a subroutine processing requests,1114# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1115return;1116}else{1117# pure CGI script, serving single request1118exit;1119}11201121## ======================================================================1122## action links11231124# possible values of extra options1125# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1126# -replay => 1 - start from a current view (replay with modifications)1127# -path_info => 0|1 - don't use/use path_info URL (if possible)1128sub href {1129my%params=@_;1130# default is to use -absolute url() i.e. $my_uri1131my$href=$params{-full} ?$my_url:$my_uri;11321133$params{'project'} =$projectunlessexists$params{'project'};11341135if($params{-replay}) {1136while(my($name,$symbol) =each%cgi_param_mapping) {1137if(!exists$params{$name}) {1138$params{$name} =$input_params{$name};1139}1140}1141}11421143my$use_pathinfo= gitweb_check_feature('pathinfo');1144if(defined$params{'project'} &&1145(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1146# try to put as many parameters as possible in PATH_INFO:1147# - project name1148# - action1149# - hash_parent or hash_parent_base:/file_parent1150# - hash or hash_base:/filename1151# - the snapshot_format as an appropriate suffix11521153# When the script is the root DirectoryIndex for the domain,1154# $href here would be something like http://gitweb.example.com/1155# Thus, we strip any trailing / from $href, to spare us double1156# slashes in the final URL1157$href=~ s,/$,,;11581159# Then add the project name, if present1160$href.="/".esc_url($params{'project'});1161delete$params{'project'};11621163# since we destructively absorb parameters, we keep this1164# boolean that remembers if we're handling a snapshot1165my$is_snapshot=$params{'action'}eq'snapshot';11661167# Summary just uses the project path URL, any other action is1168# added to the URL1169if(defined$params{'action'}) {1170$href.="/".esc_url($params{'action'})unless$params{'action'}eq'summary';1171delete$params{'action'};1172}11731174# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1175# stripping nonexistent or useless pieces1176$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1177||$params{'hash_parent'} ||$params{'hash'});1178if(defined$params{'hash_base'}) {1179if(defined$params{'hash_parent_base'}) {1180$href.= esc_url($params{'hash_parent_base'});1181# skip the file_parent if it's the same as the file_name1182if(defined$params{'file_parent'}) {1183if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1184delete$params{'file_parent'};1185}elsif($params{'file_parent'} !~/\.\./) {1186$href.=":/".esc_url($params{'file_parent'});1187delete$params{'file_parent'};1188}1189}1190$href.="..";1191delete$params{'hash_parent'};1192delete$params{'hash_parent_base'};1193}elsif(defined$params{'hash_parent'}) {1194$href.= esc_url($params{'hash_parent'})."..";1195delete$params{'hash_parent'};1196}11971198$href.= esc_url($params{'hash_base'});1199if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1200$href.=":/".esc_url($params{'file_name'});1201delete$params{'file_name'};1202}1203delete$params{'hash'};1204delete$params{'hash_base'};1205}elsif(defined$params{'hash'}) {1206$href.= esc_url($params{'hash'});1207delete$params{'hash'};1208}12091210# If the action was a snapshot, we can absorb the1211# snapshot_format parameter too1212if($is_snapshot) {1213my$fmt=$params{'snapshot_format'};1214# snapshot_format should always be defined when href()1215# is called, but just in case some code forgets, we1216# fall back to the default1217$fmt||=$snapshot_fmts[0];1218$href.=$known_snapshot_formats{$fmt}{'suffix'};1219delete$params{'snapshot_format'};1220}1221}12221223# now encode the parameters explicitly1224my@result= ();1225for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1226my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1227if(defined$params{$name}) {1228if(ref($params{$name})eq"ARRAY") {1229foreachmy$par(@{$params{$name}}) {1230push@result,$symbol."=". esc_param($par);1231}1232}else{1233push@result,$symbol."=". esc_param($params{$name});1234}1235}1236}1237$href.="?".join(';',@result)ifscalar@result;12381239return$href;1240}124112421243## ======================================================================1244## validation, quoting/unquoting and escaping12451246sub validate_action {1247my$input=shift||returnundef;1248returnundefunlessexists$actions{$input};1249return$input;1250}12511252sub validate_project {1253my$input=shift||returnundef;1254if(!validate_pathname($input) ||1255!(-d "$projectroot/$input") ||1256!check_export_ok("$projectroot/$input") ||1257($strict_export&& !project_in_list($input))) {1258returnundef;1259}else{1260return$input;1261}1262}12631264sub validate_pathname {1265my$input=shift||returnundef;12661267# no '.' or '..' as elements of path, i.e. no '.' nor '..'1268# at the beginning, at the end, and between slashes.1269# also this catches doubled slashes1270if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1271returnundef;1272}1273# no null characters1274if($input=~m!\0!) {1275returnundef;1276}1277return$input;1278}12791280sub validate_refname {1281my$input=shift||returnundef;12821283# textual hashes are O.K.1284if($input=~m/^[0-9a-fA-F]{40}$/) {1285return$input;1286}1287# it must be correct pathname1288$input= validate_pathname($input)1289orreturnundef;1290# restrictions on ref name according to git-check-ref-format1291if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1292returnundef;1293}1294return$input;1295}12961297# decode sequences of octets in utf8 into Perl's internal form,1298# which is utf-8 with utf8 flag set if needed. gitweb writes out1299# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1300sub to_utf8 {1301my$str=shift;1302returnundefunlessdefined$str;1303if(utf8::valid($str)) {1304 utf8::decode($str);1305return$str;1306}else{1307return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1308}1309}13101311# quote unsafe chars, but keep the slash, even when it's not1312# correct, but quoted slashes look too horrible in bookmarks1313sub esc_param {1314my$str=shift;1315returnundefunlessdefined$str;1316$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1317$str=~s/ /\+/g;1318return$str;1319}13201321# quote unsafe chars in whole URL, so some charactrs cannot be quoted1322sub esc_url {1323my$str=shift;1324returnundefunlessdefined$str;1325$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X",ord($1))/eg;1326$str=~s/\+/%2B/g;1327$str=~s/ /\+/g;1328return$str;1329}13301331# replace invalid utf8 character with SUBSTITUTION sequence1332sub esc_html {1333my$str=shift;1334my%opts=@_;13351336returnundefunlessdefined$str;13371338$str= to_utf8($str);1339$str=$cgi->escapeHTML($str);1340if($opts{'-nbsp'}) {1341$str=~s/ / /g;1342}1343$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1344return$str;1345}13461347# quote control characters and escape filename to HTML1348sub esc_path {1349my$str=shift;1350my%opts=@_;13511352returnundefunlessdefined$str;13531354$str= to_utf8($str);1355$str=$cgi->escapeHTML($str);1356if($opts{'-nbsp'}) {1357$str=~s/ / /g;1358}1359$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1360return$str;1361}13621363# Make control characters "printable", using character escape codes (CEC)1364sub quot_cec {1365my$cntrl=shift;1366my%opts=@_;1367my%es= (# character escape codes, aka escape sequences1368"\t"=>'\t',# tab (HT)1369"\n"=>'\n',# line feed (LF)1370"\r"=>'\r',# carrige return (CR)1371"\f"=>'\f',# form feed (FF)1372"\b"=>'\b',# backspace (BS)1373"\a"=>'\a',# alarm (bell) (BEL)1374"\e"=>'\e',# escape (ESC)1375"\013"=>'\v',# vertical tab (VT)1376"\000"=>'\0',# nul character (NUL)1377);1378my$chr= ( (exists$es{$cntrl})1379?$es{$cntrl}1380:sprintf('\%2x',ord($cntrl)) );1381if($opts{-nohtml}) {1382return$chr;1383}else{1384return"<span class=\"cntrl\">$chr</span>";1385}1386}13871388# Alternatively use unicode control pictures codepoints,1389# Unicode "printable representation" (PR)1390sub quot_upr {1391my$cntrl=shift;1392my%opts=@_;13931394my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1395if($opts{-nohtml}) {1396return$chr;1397}else{1398return"<span class=\"cntrl\">$chr</span>";1399}1400}14011402# git may return quoted and escaped filenames1403sub unquote {1404my$str=shift;14051406sub unq {1407my$seq=shift;1408my%es= (# character escape codes, aka escape sequences1409't'=>"\t",# tab (HT, TAB)1410'n'=>"\n",# newline (NL)1411'r'=>"\r",# return (CR)1412'f'=>"\f",# form feed (FF)1413'b'=>"\b",# backspace (BS)1414'a'=>"\a",# alarm (bell) (BEL)1415'e'=>"\e",# escape (ESC)1416'v'=>"\013",# vertical tab (VT)1417);14181419if($seq=~m/^[0-7]{1,3}$/) {1420# octal char sequence1421returnchr(oct($seq));1422}elsif(exists$es{$seq}) {1423# C escape sequence, aka character escape code1424return$es{$seq};1425}1426# quoted ordinary character1427return$seq;1428}14291430if($str=~m/^"(.*)"$/) {1431# needs unquoting1432$str=$1;1433$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1434}1435return$str;1436}14371438# escape tabs (convert tabs to spaces)1439sub untabify {1440my$line=shift;14411442while((my$pos=index($line,"\t")) != -1) {1443if(my$count= (8- ($pos%8))) {1444my$spaces=' ' x $count;1445$line=~s/\t/$spaces/;1446}1447}14481449return$line;1450}14511452sub project_in_list {1453my$project=shift;1454my@list= git_get_projects_list();1455return@list&&scalar(grep{$_->{'path'}eq$project}@list);1456}14571458## ----------------------------------------------------------------------1459## HTML aware string manipulation14601461# Try to chop given string on a word boundary between position1462# $len and $len+$add_len. If there is no word boundary there,1463# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1464# (marking chopped part) would be longer than given string.1465sub chop_str {1466my$str=shift;1467my$len=shift;1468my$add_len=shift||10;1469my$where=shift||'right';# 'left' | 'center' | 'right'14701471# Make sure perl knows it is utf8 encoded so we don't1472# cut in the middle of a utf8 multibyte char.1473$str= to_utf8($str);14741475# allow only $len chars, but don't cut a word if it would fit in $add_len1476# if it doesn't fit, cut it if it's still longer than the dots we would add1477# remove chopped character entities entirely14781479# when chopping in the middle, distribute $len into left and right part1480# return early if chopping wouldn't make string shorter1481if($whereeq'center') {1482return$strif($len+5>=length($str));# filler is length 51483$len=int($len/2);1484}else{1485return$strif($len+4>=length($str));# filler is length 41486}14871488# regexps: ending and beginning with word part up to $add_len1489my$endre=qr/.{$len}\w{0,$add_len}/;1490my$begre=qr/\w{0,$add_len}.{$len}/;14911492if($whereeq'left') {1493$str=~m/^(.*?)($begre)$/;1494my($lead,$body) = ($1,$2);1495if(length($lead) >4) {1496$lead=" ...";1497}1498return"$lead$body";14991500}elsif($whereeq'center') {1501$str=~m/^($endre)(.*)$/;1502my($left,$str) = ($1,$2);1503$str=~m/^(.*?)($begre)$/;1504my($mid,$right) = ($1,$2);1505if(length($mid) >5) {1506$mid=" ... ";1507}1508return"$left$mid$right";15091510}else{1511$str=~m/^($endre)(.*)$/;1512my$body=$1;1513my$tail=$2;1514if(length($tail) >4) {1515$tail="... ";1516}1517return"$body$tail";1518}1519}15201521# takes the same arguments as chop_str, but also wraps a <span> around the1522# result with a title attribute if it does get chopped. Additionally, the1523# string is HTML-escaped.1524sub chop_and_escape_str {1525my($str) =@_;15261527my$chopped= chop_str(@_);1528if($choppedeq$str) {1529return esc_html($chopped);1530}else{1531$str=~s/[[:cntrl:]]/?/g;1532return$cgi->span({-title=>$str}, esc_html($chopped));1533}1534}15351536## ----------------------------------------------------------------------1537## functions returning short strings15381539# CSS class for given age value (in seconds)1540sub age_class {1541my$age=shift;15421543if(!defined$age) {1544return"noage";1545}elsif($age<60*60*2) {1546return"age0";1547}elsif($age<60*60*24*2) {1548return"age1";1549}else{1550return"age2";1551}1552}15531554# convert age in seconds to "nn units ago" string1555sub age_string {1556my$age=shift;1557my$age_str;15581559if($age>60*60*24*365*2) {1560$age_str= (int$age/60/60/24/365);1561$age_str.=" years ago";1562}elsif($age>60*60*24*(365/12)*2) {1563$age_str=int$age/60/60/24/(365/12);1564$age_str.=" months ago";1565}elsif($age>60*60*24*7*2) {1566$age_str=int$age/60/60/24/7;1567$age_str.=" weeks ago";1568}elsif($age>60*60*24*2) {1569$age_str=int$age/60/60/24;1570$age_str.=" days ago";1571}elsif($age>60*60*2) {1572$age_str=int$age/60/60;1573$age_str.=" hours ago";1574}elsif($age>60*2) {1575$age_str=int$age/60;1576$age_str.=" min ago";1577}elsif($age>2) {1578$age_str=int$age;1579$age_str.=" sec ago";1580}else{1581$age_str.=" right now";1582}1583return$age_str;1584}15851586useconstant{1587 S_IFINVALID =>0030000,1588 S_IFGITLINK =>0160000,1589};15901591# submodule/subproject, a commit object reference1592sub S_ISGITLINK {1593my$mode=shift;15941595return(($mode& S_IFMT) == S_IFGITLINK)1596}15971598# convert file mode in octal to symbolic file mode string1599sub mode_str {1600my$mode=oct shift;16011602if(S_ISGITLINK($mode)) {1603return'm---------';1604}elsif(S_ISDIR($mode& S_IFMT)) {1605return'drwxr-xr-x';1606}elsif(S_ISLNK($mode)) {1607return'lrwxrwxrwx';1608}elsif(S_ISREG($mode)) {1609# git cares only about the executable bit1610if($mode& S_IXUSR) {1611return'-rwxr-xr-x';1612}else{1613return'-rw-r--r--';1614};1615}else{1616return'----------';1617}1618}16191620# convert file mode in octal to file type string1621sub file_type {1622my$mode=shift;16231624if($mode!~m/^[0-7]+$/) {1625return$mode;1626}else{1627$mode=oct$mode;1628}16291630if(S_ISGITLINK($mode)) {1631return"submodule";1632}elsif(S_ISDIR($mode& S_IFMT)) {1633return"directory";1634}elsif(S_ISLNK($mode)) {1635return"symlink";1636}elsif(S_ISREG($mode)) {1637return"file";1638}else{1639return"unknown";1640}1641}16421643# convert file mode in octal to file type description string1644sub file_type_long {1645my$mode=shift;16461647if($mode!~m/^[0-7]+$/) {1648return$mode;1649}else{1650$mode=oct$mode;1651}16521653if(S_ISGITLINK($mode)) {1654return"submodule";1655}elsif(S_ISDIR($mode& S_IFMT)) {1656return"directory";1657}elsif(S_ISLNK($mode)) {1658return"symlink";1659}elsif(S_ISREG($mode)) {1660if($mode& S_IXUSR) {1661return"executable";1662}else{1663return"file";1664};1665}else{1666return"unknown";1667}1668}166916701671## ----------------------------------------------------------------------1672## functions returning short HTML fragments, or transforming HTML fragments1673## which don't belong to other sections16741675# format line of commit message.1676sub format_log_line_html {1677my$line=shift;16781679$line= esc_html($line, -nbsp=>1);1680$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1681$cgi->a({-href => href(action=>"object", hash=>$1),1682-class=>"text"},$1);1683}eg;16841685return$line;1686}16871688# format marker of refs pointing to given object16891690# the destination action is chosen based on object type and current context:1691# - for annotated tags, we choose the tag view unless it's the current view1692# already, in which case we go to shortlog view1693# - for other refs, we keep the current view if we're in history, shortlog or1694# log view, and select shortlog otherwise1695sub format_ref_marker {1696my($refs,$id) =@_;1697my$markers='';16981699if(defined$refs->{$id}) {1700foreachmy$ref(@{$refs->{$id}}) {1701# this code exploits the fact that non-lightweight tags are the1702# only indirect objects, and that they are the only objects for which1703# we want to use tag instead of shortlog as action1704my($type,$name) =qw();1705my$indirect= ($ref=~s/\^\{\}$//);1706# e.g. tags/v2.6.11 or heads/next1707if($ref=~m!^(.*?)s?/(.*)$!) {1708$type=$1;1709$name=$2;1710}else{1711$type="ref";1712$name=$ref;1713}17141715my$class=$type;1716$class.=" indirect"if$indirect;17171718my$dest_action="shortlog";17191720if($indirect) {1721$dest_action="tag"unless$actioneq"tag";1722}elsif($action=~/^(history|(short)?log)$/) {1723$dest_action=$action;1724}17251726my$dest="";1727$dest.="refs/"unless$ref=~ m!^refs/!;1728$dest.=$ref;17291730my$link=$cgi->a({1731-href => href(1732 action=>$dest_action,1733 hash=>$dest1734)},$name);17351736$markers.=" <span class=\"$class\"title=\"$ref\">".1737$link."</span>";1738}1739}17401741if($markers) {1742return' <span class="refs">'.$markers.'</span>';1743}else{1744return"";1745}1746}17471748# format, perhaps shortened and with markers, title line1749sub format_subject_html {1750my($long,$short,$href,$extra) =@_;1751$extra=''unlessdefined($extra);17521753if(length($short) <length($long)) {1754$long=~s/[[:cntrl:]]/?/g;1755return$cgi->a({-href =>$href, -class=>"list subject",1756-title => to_utf8($long)},1757 esc_html($short)) .$extra;1758}else{1759return$cgi->a({-href =>$href, -class=>"list subject"},1760 esc_html($long)) .$extra;1761}1762}17631764# Rather than recomputing the url for an email multiple times, we cache it1765# after the first hit. This gives a visible benefit in views where the avatar1766# for the same email is used repeatedly (e.g. shortlog).1767# The cache is shared by all avatar engines (currently gravatar only), which1768# are free to use it as preferred. Since only one avatar engine is used for any1769# given page, there's no risk for cache conflicts.1770our%avatar_cache= ();17711772# Compute the picon url for a given email, by using the picon search service over at1773# http://www.cs.indiana.edu/picons/search.html1774sub picon_url {1775my$email=lc shift;1776if(!$avatar_cache{$email}) {1777my($user,$domain) =split('@',$email);1778$avatar_cache{$email} =1779"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1780"$domain/$user/".1781"users+domains+unknown/up/single";1782}1783return$avatar_cache{$email};1784}17851786# Compute the gravatar url for a given email, if it's not in the cache already.1787# Gravatar stores only the part of the URL before the size, since that's the1788# one computationally more expensive. This also allows reuse of the cache for1789# different sizes (for this particular engine).1790sub gravatar_url {1791my$email=lc shift;1792my$size=shift;1793$avatar_cache{$email} ||=1794"http://www.gravatar.com/avatar/".1795 Digest::MD5::md5_hex($email) ."?s=";1796return$avatar_cache{$email} .$size;1797}17981799# Insert an avatar for the given $email at the given $size if the feature1800# is enabled.1801sub git_get_avatar {1802my($email,%opts) =@_;1803my$pre_white= ($opts{-pad_before} ?" ":"");1804my$post_white= ($opts{-pad_after} ?" ":"");1805$opts{-size} ||='default';1806my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1807my$url="";1808if($git_avatareq'gravatar') {1809$url= gravatar_url($email,$size);1810}elsif($git_avatareq'picon') {1811$url= picon_url($email);1812}1813# Other providers can be added by extending the if chain, defining $url1814# as needed. If no variant puts something in $url, we assume avatars1815# are completely disabled/unavailable.1816if($url) {1817return$pre_white.1818"<img width=\"$size\"".1819"class=\"avatar\"".1820"src=\"$url\"".1821"alt=\"\"".1822"/>".$post_white;1823}else{1824return"";1825}1826}18271828sub format_search_author {1829my($author,$searchtype,$displaytext) =@_;1830my$have_search= gitweb_check_feature('search');18311832if($have_search) {1833my$performed="";1834if($searchtypeeq'author') {1835$performed="authored";1836}elsif($searchtypeeq'committer') {1837$performed="committed";1838}18391840return$cgi->a({-href => href(action=>"search", hash=>$hash,1841 searchtext=>$author,1842 searchtype=>$searchtype),class=>"list",1843 title=>"Search for commits$performedby$author"},1844$displaytext);18451846}else{1847return$displaytext;1848}1849}18501851# format the author name of the given commit with the given tag1852# the author name is chopped and escaped according to the other1853# optional parameters (see chop_str).1854sub format_author_html {1855my$tag=shift;1856my$co=shift;1857my$author= chop_and_escape_str($co->{'author_name'},@_);1858return"<$tagclass=\"author\">".1859 format_search_author($co->{'author_name'},"author",1860 git_get_avatar($co->{'author_email'}, -pad_after =>1) .1861$author) .1862"</$tag>";1863}18641865# format git diff header line, i.e. "diff --(git|combined|cc) ..."1866sub format_git_diff_header_line {1867my$line=shift;1868my$diffinfo=shift;1869my($from,$to) =@_;18701871if($diffinfo->{'nparents'}) {1872# combined diff1873$line=~s!^(diff (.*?) )"?.*$!$1!;1874if($to->{'href'}) {1875$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1876 esc_path($to->{'file'}));1877}else{# file was deleted (no href)1878$line.= esc_path($to->{'file'});1879}1880}else{1881# "ordinary" diff1882$line=~s!^(diff (.*?) )"?a/.*$!$1!;1883if($from->{'href'}) {1884$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},1885'a/'. esc_path($from->{'file'}));1886}else{# file was added (no href)1887$line.='a/'. esc_path($from->{'file'});1888}1889$line.=' ';1890if($to->{'href'}) {1891$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1892'b/'. esc_path($to->{'file'}));1893}else{# file was deleted1894$line.='b/'. esc_path($to->{'file'});1895}1896}18971898return"<div class=\"diff header\">$line</div>\n";1899}19001901# format extended diff header line, before patch itself1902sub format_extended_diff_header_line {1903my$line=shift;1904my$diffinfo=shift;1905my($from,$to) =@_;19061907# match <path>1908if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {1909$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},1910 esc_path($from->{'file'}));1911}1912if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {1913$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},1914 esc_path($to->{'file'}));1915}1916# match single <mode>1917if($line=~m/\s(\d{6})$/) {1918$line.='<span class="info"> ('.1919 file_type_long($1) .1920')</span>';1921}1922# match <hash>1923if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {1924# can match only for combined diff1925$line='index ';1926for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {1927if($from->{'href'}[$i]) {1928$line.=$cgi->a({-href=>$from->{'href'}[$i],1929-class=>"hash"},1930substr($diffinfo->{'from_id'}[$i],0,7));1931}else{1932$line.='0' x 7;1933}1934# separator1935$line.=','if($i<$diffinfo->{'nparents'} -1);1936}1937$line.='..';1938if($to->{'href'}) {1939$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},1940substr($diffinfo->{'to_id'},0,7));1941}else{1942$line.='0' x 7;1943}19441945}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {1946# can match only for ordinary diff1947my($from_link,$to_link);1948if($from->{'href'}) {1949$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},1950substr($diffinfo->{'from_id'},0,7));1951}else{1952$from_link='0' x 7;1953}1954if($to->{'href'}) {1955$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},1956substr($diffinfo->{'to_id'},0,7));1957}else{1958$to_link='0' x 7;1959}1960my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});1961$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;1962}19631964return$line."<br/>\n";1965}19661967# format from-file/to-file diff header1968sub format_diff_from_to_header {1969my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;1970my$line;1971my$result='';19721973$line=$from_line;1974#assert($line =~ m/^---/) if DEBUG;1975# no extra formatting for "^--- /dev/null"1976if(!$diffinfo->{'nparents'}) {1977# ordinary (single parent) diff1978if($line=~m!^--- "?a/!) {1979if($from->{'href'}) {1980$line='--- a/'.1981$cgi->a({-href=>$from->{'href'}, -class=>"path"},1982 esc_path($from->{'file'}));1983}else{1984$line='--- a/'.1985 esc_path($from->{'file'});1986}1987}1988$result.= qq!<div class="diff from_file">$line</div>\n!;19891990}else{1991# combined diff (merge commit)1992for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {1993if($from->{'href'}[$i]) {1994$line='--- '.1995$cgi->a({-href=>href(action=>"blobdiff",1996 hash_parent=>$diffinfo->{'from_id'}[$i],1997 hash_parent_base=>$parents[$i],1998 file_parent=>$from->{'file'}[$i],1999 hash=>$diffinfo->{'to_id'},2000 hash_base=>$hash,2001 file_name=>$to->{'file'}),2002-class=>"path",2003-title=>"diff". ($i+1)},2004$i+1) .2005'/'.2006$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2007 esc_path($from->{'file'}[$i]));2008}else{2009$line='--- /dev/null';2010}2011$result.= qq!<div class="diff from_file">$line</div>\n!;2012}2013}20142015$line=$to_line;2016#assert($line =~ m/^\+\+\+/) if DEBUG;2017# no extra formatting for "^+++ /dev/null"2018if($line=~m!^\+\+\+ "?b/!) {2019if($to->{'href'}) {2020$line='+++ b/'.2021$cgi->a({-href=>$to->{'href'}, -class=>"path"},2022 esc_path($to->{'file'}));2023}else{2024$line='+++ b/'.2025 esc_path($to->{'file'});2026}2027}2028$result.= qq!<div class="diff to_file">$line</div>\n!;20292030return$result;2031}20322033# create note for patch simplified by combined diff2034sub format_diff_cc_simplified {2035my($diffinfo,@parents) =@_;2036my$result='';20372038$result.="<div class=\"diff header\">".2039"diff --cc ";2040if(!is_deleted($diffinfo)) {2041$result.=$cgi->a({-href => href(action=>"blob",2042 hash_base=>$hash,2043 hash=>$diffinfo->{'to_id'},2044 file_name=>$diffinfo->{'to_file'}),2045-class=>"path"},2046 esc_path($diffinfo->{'to_file'}));2047}else{2048$result.= esc_path($diffinfo->{'to_file'});2049}2050$result.="</div>\n".# class="diff header"2051"<div class=\"diff nodifferences\">".2052"Simple merge".2053"</div>\n";# class="diff nodifferences"20542055return$result;2056}20572058# format patch (diff) line (not to be used for diff headers)2059sub format_diff_line {2060my$line=shift;2061my($from,$to) =@_;2062my$diff_class="";20632064chomp$line;20652066if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2067# combined diff2068my$prefix=substr($line,0,scalar@{$from->{'href'}});2069if($line=~m/^\@{3}/) {2070$diff_class=" chunk_header";2071}elsif($line=~m/^\\/) {2072$diff_class=" incomplete";2073}elsif($prefix=~tr/+/+/) {2074$diff_class=" add";2075}elsif($prefix=~tr/-/-/) {2076$diff_class=" rem";2077}2078}else{2079# assume ordinary diff2080my$char=substr($line,0,1);2081if($chareq'+') {2082$diff_class=" add";2083}elsif($chareq'-') {2084$diff_class=" rem";2085}elsif($chareq'@') {2086$diff_class=" chunk_header";2087}elsif($chareq"\\") {2088$diff_class=" incomplete";2089}2090}2091$line= untabify($line);2092if($from&&$to&&$line=~m/^\@{2} /) {2093my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2094$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;20952096$from_lines=0unlessdefined$from_lines;2097$to_lines=0unlessdefined$to_lines;20982099if($from->{'href'}) {2100$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2101-class=>"list"},$from_text);2102}2103if($to->{'href'}) {2104$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2105-class=>"list"},$to_text);2106}2107$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2108"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2109return"<div class=\"diff$diff_class\">$line</div>\n";2110}elsif($from&&$to&&$line=~m/^\@{3}/) {2111my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2112my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);21132114@from_text=split(' ',$ranges);2115for(my$i=0;$i<@from_text; ++$i) {2116($from_start[$i],$from_nlines[$i]) =2117(split(',',substr($from_text[$i],1)),0);2118}21192120$to_text=pop@from_text;2121$to_start=pop@from_start;2122$to_nlines=pop@from_nlines;21232124$line="<span class=\"chunk_info\">$prefix";2125for(my$i=0;$i<@from_text; ++$i) {2126if($from->{'href'}[$i]) {2127$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2128-class=>"list"},$from_text[$i]);2129}else{2130$line.=$from_text[$i];2131}2132$line.=" ";2133}2134if($to->{'href'}) {2135$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2136-class=>"list"},$to_text);2137}else{2138$line.=$to_text;2139}2140$line.="$prefix</span>".2141"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2142return"<div class=\"diff$diff_class\">$line</div>\n";2143}2144return"<div class=\"diff$diff_class\">". esc_html($line, -nbsp=>1) ."</div>\n";2145}21462147# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2148# linked. Pass the hash of the tree/commit to snapshot.2149sub format_snapshot_links {2150my($hash) =@_;2151my$num_fmts=@snapshot_fmts;2152if($num_fmts>1) {2153# A parenthesized list of links bearing format names.2154# e.g. "snapshot (_tar.gz_ _zip_)"2155return"snapshot (".join(' ',map2156$cgi->a({2157-href => href(2158 action=>"snapshot",2159 hash=>$hash,2160 snapshot_format=>$_2161)2162},$known_snapshot_formats{$_}{'display'})2163,@snapshot_fmts) .")";2164}elsif($num_fmts==1) {2165# A single "snapshot" link whose tooltip bears the format name.2166# i.e. "_snapshot_"2167my($fmt) =@snapshot_fmts;2168return2169$cgi->a({2170-href => href(2171 action=>"snapshot",2172 hash=>$hash,2173 snapshot_format=>$fmt2174),2175-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2176},"snapshot");2177}else{# $num_fmts == 02178returnundef;2179}2180}21812182## ......................................................................2183## functions returning values to be passed, perhaps after some2184## transformation, to other functions; e.g. returning arguments to href()21852186# returns hash to be passed to href to generate gitweb URL2187# in -title key it returns description of link2188sub get_feed_info {2189my$format=shift||'Atom';2190my%res= (action =>lc($format));21912192# feed links are possible only for project views2193return unless(defined$project);2194# some views should link to OPML, or to generic project feed,2195# or don't have specific feed yet (so they should use generic)2196return if($action=~/^(?:tags|heads|forks|tag|search)$/x);21972198my$branch;2199# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2200# from tag links; this also makes possible to detect branch links2201if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2202(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2203$branch=$1;2204}2205# find log type for feed description (title)2206my$type='log';2207if(defined$file_name) {2208$type="history of$file_name";2209$type.="/"if($actioneq'tree');2210$type.=" on '$branch'"if(defined$branch);2211}else{2212$type="log of$branch"if(defined$branch);2213}22142215$res{-title} =$type;2216$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2217$res{'file_name'} =$file_name;22182219return%res;2220}22212222## ----------------------------------------------------------------------2223## git utility subroutines, invoking git commands22242225# returns path to the core git executable and the --git-dir parameter as list2226sub git_cmd {2227$number_of_git_cmds++;2228return$GIT,'--git-dir='.$git_dir;2229}22302231# quote the given arguments for passing them to the shell2232# quote_command("command", "arg 1", "arg with ' and ! characters")2233# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2234# Try to avoid using this function wherever possible.2235sub quote_command {2236returnjoin(' ',2237map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2238}22392240# get HEAD ref of given project as hash2241sub git_get_head_hash {2242return git_get_full_hash(shift,'HEAD');2243}22442245sub git_get_full_hash {2246return git_get_hash(@_);2247}22482249sub git_get_short_hash {2250return git_get_hash(@_,'--short=7');2251}22522253sub git_get_hash {2254my($project,$hash,@options) =@_;2255my$o_git_dir=$git_dir;2256my$retval=undef;2257$git_dir="$projectroot/$project";2258if(open my$fd,'-|', git_cmd(),'rev-parse',2259'--verify','-q',@options,$hash) {2260$retval= <$fd>;2261chomp$retvalifdefined$retval;2262close$fd;2263}2264if(defined$o_git_dir) {2265$git_dir=$o_git_dir;2266}2267return$retval;2268}22692270# get type of given object2271sub git_get_type {2272my$hash=shift;22732274open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2275my$type= <$fd>;2276close$fdorreturn;2277chomp$type;2278return$type;2279}22802281# repository configuration2282our$config_file='';2283our%config;22842285# store multiple values for single key as anonymous array reference2286# single values stored directly in the hash, not as [ <value> ]2287sub hash_set_multi {2288my($hash,$key,$value) =@_;22892290if(!exists$hash->{$key}) {2291$hash->{$key} =$value;2292}elsif(!ref$hash->{$key}) {2293$hash->{$key} = [$hash->{$key},$value];2294}else{2295push@{$hash->{$key}},$value;2296}2297}22982299# return hash of git project configuration2300# optionally limited to some section, e.g. 'gitweb'2301sub git_parse_project_config {2302my$section_regexp=shift;2303my%config;23042305local$/="\0";23062307open my$fh,"-|", git_cmd(),"config",'-z','-l',2308orreturn;23092310while(my$keyval= <$fh>) {2311chomp$keyval;2312my($key,$value) =split(/\n/,$keyval,2);23132314 hash_set_multi(\%config,$key,$value)2315if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2316}2317close$fh;23182319return%config;2320}23212322# convert config value to boolean: 'true' or 'false'2323# no value, number > 0, 'true' and 'yes' values are true2324# rest of values are treated as false (never as error)2325sub config_to_bool {2326my$val=shift;23272328return1if!defined$val;# section.key23292330# strip leading and trailing whitespace2331$val=~s/^\s+//;2332$val=~s/\s+$//;23332334return(($val=~/^\d+$/&&$val) ||# section.key = 12335($val=~/^(?:true|yes)$/i));# section.key = true2336}23372338# convert config value to simple decimal number2339# an optional value suffix of 'k', 'm', or 'g' will cause the value2340# to be multiplied by 1024, 1048576, or 10737418242341sub config_to_int {2342my$val=shift;23432344# strip leading and trailing whitespace2345$val=~s/^\s+//;2346$val=~s/\s+$//;23472348if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2349$unit=lc($unit);2350# unknown unit is treated as 12351return$num* ($uniteq'g'?1073741824:2352$uniteq'm'?1048576:2353$uniteq'k'?1024:1);2354}2355return$val;2356}23572358# convert config value to array reference, if needed2359sub config_to_multi {2360my$val=shift;23612362returnref($val) ?$val: (defined($val) ? [$val] : []);2363}23642365sub git_get_project_config {2366my($key,$type) =@_;23672368return unlessdefined$git_dir;23692370# key sanity check2371return unless($key);2372$key=~s/^gitweb\.//;2373return if($key=~m/\W/);23742375# type sanity check2376if(defined$type) {2377$type=~s/^--//;2378$type=undef2379unless($typeeq'bool'||$typeeq'int');2380}23812382# get config2383if(!defined$config_file||2384$config_filene"$git_dir/config") {2385%config= git_parse_project_config('gitweb');2386$config_file="$git_dir/config";2387}23882389# check if config variable (key) exists2390return unlessexists$config{"gitweb.$key"};23912392# ensure given type2393if(!defined$type) {2394return$config{"gitweb.$key"};2395}elsif($typeeq'bool') {2396# backward compatibility: 'git config --bool' returns true/false2397return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2398}elsif($typeeq'int') {2399return config_to_int($config{"gitweb.$key"});2400}2401return$config{"gitweb.$key"};2402}24032404# get hash of given path at given ref2405sub git_get_hash_by_path {2406my$base=shift;2407my$path=shift||returnundef;2408my$type=shift;24092410$path=~ s,/+$,,;24112412open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2413or die_error(500,"Open git-ls-tree failed");2414my$line= <$fd>;2415close$fdorreturnundef;24162417if(!defined$line) {2418# there is no tree or hash given by $path at $base2419returnundef;2420}24212422#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2423$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2424if(defined$type&&$typene$2) {2425# type doesn't match2426returnundef;2427}2428return$3;2429}24302431# get path of entry with given hash at given tree-ish (ref)2432# used to get 'from' filename for combined diff (merge commit) for renames2433sub git_get_path_by_hash {2434my$base=shift||return;2435my$hash=shift||return;24362437local$/="\0";24382439open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2440orreturnundef;2441while(my$line= <$fd>) {2442chomp$line;24432444#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2445#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2446if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2447close$fd;2448return$1;2449}2450}2451close$fd;2452returnundef;2453}24542455## ......................................................................2456## git utility functions, directly accessing git repository24572458sub git_get_project_description {2459my$path=shift;24602461$git_dir="$projectroot/$path";2462open my$fd,'<',"$git_dir/description"2463orreturn git_get_project_config('description');2464my$descr= <$fd>;2465close$fd;2466if(defined$descr) {2467chomp$descr;2468}2469return$descr;2470}24712472sub git_get_project_ctags {2473my$path=shift;2474my$ctags= {};24752476$git_dir="$projectroot/$path";2477opendir my$dh,"$git_dir/ctags"2478orreturn$ctags;2479foreach(grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh)) {2480open my$ct,'<',$_ornext;2481my$val= <$ct>;2482chomp$val;2483close$ct;2484my$ctag=$_;$ctag=~ s#.*/##;2485$ctags->{$ctag} =$val;2486}2487closedir$dh;2488$ctags;2489}24902491sub git_populate_project_tagcloud {2492my$ctags=shift;24932494# First, merge different-cased tags; tags vote on casing2495my%ctags_lc;2496foreach(keys%$ctags) {2497$ctags_lc{lc$_}->{count} +=$ctags->{$_};2498if(not$ctags_lc{lc$_}->{topcount}2499or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2500$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2501$ctags_lc{lc$_}->{topname} =$_;2502}2503}25042505my$cloud;2506if(eval{require HTML::TagCloud;1; }) {2507$cloud= HTML::TagCloud->new;2508foreach(sort keys%ctags_lc) {2509# Pad the title with spaces so that the cloud looks2510# less crammed.2511my$title=$ctags_lc{$_}->{topname};2512$title=~s/ / /g;2513$title=~s/^/ /g;2514$title=~s/$/ /g;2515$cloud->add($title,$home_link."?by_tag=".$_,$ctags_lc{$_}->{count});2516}2517}else{2518$cloud= \%ctags_lc;2519}2520$cloud;2521}25222523sub git_show_project_tagcloud {2524my($cloud,$count) =@_;2525print STDERR ref($cloud)."..\n";2526if(ref$cloudeq'HTML::TagCloud') {2527return$cloud->html_and_css($count);2528}else{2529my@tags=sort{$cloud->{$a}->{count} <=>$cloud->{$b}->{count} }keys%$cloud;2530return'<p align="center">'.join(', ',map{2531"<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"2532}splice(@tags,0,$count)) .'</p>';2533}2534}25352536sub git_get_project_url_list {2537my$path=shift;25382539$git_dir="$projectroot/$path";2540open my$fd,'<',"$git_dir/cloneurl"2541orreturnwantarray?2542@{ config_to_multi(git_get_project_config('url')) } :2543 config_to_multi(git_get_project_config('url'));2544my@git_project_url_list=map{chomp;$_} <$fd>;2545close$fd;25462547returnwantarray?@git_project_url_list: \@git_project_url_list;2548}25492550sub git_get_projects_list {2551my($filter) =@_;2552my@list;25532554$filter||='';2555$filter=~s/\.git$//;25562557my$check_forks= gitweb_check_feature('forks');25582559if(-d $projects_list) {2560# search in directory2561my$dir=$projects_list. ($filter?"/$filter":'');2562# remove the trailing "/"2563$dir=~s!/+$!!;2564my$pfxlen=length("$dir");2565my$pfxdepth= ($dir=~tr!/!!);25662567 File::Find::find({2568 follow_fast =>1,# follow symbolic links2569 follow_skip =>2,# ignore duplicates2570 dangling_symlinks =>0,# ignore dangling symlinks, silently2571 wanted =>sub{2572# global variables2573our$project_maxdepth;2574our$projectroot;2575# skip project-list toplevel, if we get it.2576return if(m!^[/.]$!);2577# only directories can be git repositories2578return unless(-d $_);2579# don't traverse too deep (Find is super slow on os x)2580if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2581$File::Find::prune =1;2582return;2583}25842585my$subdir=substr($File::Find::name,$pfxlen+1);2586# we check related file in $projectroot2587my$path= ($filter?"$filter/":'') .$subdir;2588if(check_export_ok("$projectroot/$path")) {2589push@list, { path =>$path};2590$File::Find::prune =1;2591}2592},2593},"$dir");25942595}elsif(-f $projects_list) {2596# read from file(url-encoded):2597# 'git%2Fgit.git Linus+Torvalds'2598# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2599# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2600my%paths;2601open my$fd,'<',$projects_listorreturn;2602 PROJECT:2603while(my$line= <$fd>) {2604chomp$line;2605my($path,$owner) =split' ',$line;2606$path= unescape($path);2607$owner= unescape($owner);2608if(!defined$path) {2609next;2610}2611if($filterne'') {2612# looking for forks;2613my$pfx=substr($path,0,length($filter));2614if($pfxne$filter) {2615next PROJECT;2616}2617my$sfx=substr($path,length($filter));2618if($sfx!~/^\/.*\.git$/) {2619next PROJECT;2620}2621}elsif($check_forks) {2622 PATH:2623foreachmy$filter(keys%paths) {2624# looking for forks;2625my$pfx=substr($path,0,length($filter));2626if($pfxne$filter) {2627next PATH;2628}2629my$sfx=substr($path,length($filter));2630if($sfx!~/^\/.*\.git$/) {2631next PATH;2632}2633# is a fork, don't include it in2634# the list2635next PROJECT;2636}2637}2638if(check_export_ok("$projectroot/$path")) {2639my$pr= {2640 path =>$path,2641 owner => to_utf8($owner),2642};2643push@list,$pr;2644(my$forks_path=$path) =~s/\.git$//;2645$paths{$forks_path}++;2646}2647}2648close$fd;2649}2650return@list;2651}26522653our$gitweb_project_owner=undef;2654sub git_get_project_list_from_file {26552656return if(defined$gitweb_project_owner);26572658$gitweb_project_owner= {};2659# read from file (url-encoded):2660# 'git%2Fgit.git Linus+Torvalds'2661# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2662# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2663if(-f $projects_list) {2664open(my$fd,'<',$projects_list);2665while(my$line= <$fd>) {2666chomp$line;2667my($pr,$ow) =split' ',$line;2668$pr= unescape($pr);2669$ow= unescape($ow);2670$gitweb_project_owner->{$pr} = to_utf8($ow);2671}2672close$fd;2673}2674}26752676sub git_get_project_owner {2677my$project=shift;2678my$owner;26792680returnundefunless$project;2681$git_dir="$projectroot/$project";26822683if(!defined$gitweb_project_owner) {2684 git_get_project_list_from_file();2685}26862687if(exists$gitweb_project_owner->{$project}) {2688$owner=$gitweb_project_owner->{$project};2689}2690if(!defined$owner){2691$owner= git_get_project_config('owner');2692}2693if(!defined$owner) {2694$owner= get_file_owner("$git_dir");2695}26962697return$owner;2698}26992700sub git_get_last_activity {2701my($path) =@_;2702my$fd;27032704$git_dir="$projectroot/$path";2705open($fd,"-|", git_cmd(),'for-each-ref',2706'--format=%(committer)',2707'--sort=-committerdate',2708'--count=1',2709'refs/heads')orreturn;2710my$most_recent= <$fd>;2711close$fdorreturn;2712if(defined$most_recent&&2713$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {2714my$timestamp=$1;2715my$age=time-$timestamp;2716return($age, age_string($age));2717}2718return(undef,undef);2719}27202721sub git_get_references {2722my$type=shift||"";2723my%refs;2724# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.112725# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}2726open my$fd,"-|", git_cmd(),"show-ref","--dereference",2727($type? ("--","refs/$type") : ())# use -- <pattern> if $type2728orreturn;27292730while(my$line= <$fd>) {2731chomp$line;2732if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {2733if(defined$refs{$1}) {2734push@{$refs{$1}},$2;2735}else{2736$refs{$1} = [$2];2737}2738}2739}2740close$fdorreturn;2741return \%refs;2742}27432744sub git_get_rev_name_tags {2745my$hash=shift||returnundef;27462747open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash2748orreturn;2749my$name_rev= <$fd>;2750close$fd;27512752if($name_rev=~ m|^$hash tags/(.*)$|) {2753return$1;2754}else{2755# catches also '$hash undefined' output2756returnundef;2757}2758}27592760## ----------------------------------------------------------------------2761## parse to hash functions27622763sub parse_date {2764my$epoch=shift;2765my$tz=shift||"-0000";27662767my%date;2768my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");2769my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");2770my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);2771$date{'hour'} =$hour;2772$date{'minute'} =$min;2773$date{'mday'} =$mday;2774$date{'day'} =$days[$wday];2775$date{'month'} =$months[$mon];2776$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",2777$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;2778$date{'mday-time'} =sprintf"%d%s%02d:%02d",2779$mday,$months[$mon],$hour,$min;2780$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",27811900+$year,1+$mon,$mday,$hour,$min,$sec;27822783$tz=~m/^([+\-][0-9][0-9])([0-9][0-9])$/;2784my$local=$epoch+ ((int$1+ ($2/60)) *3600);2785($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);2786$date{'hour_local'} =$hour;2787$date{'minute_local'} =$min;2788$date{'tz_local'} =$tz;2789$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",27901900+$year,$mon+1,$mday,2791$hour,$min,$sec,$tz);2792return%date;2793}27942795sub parse_tag {2796my$tag_id=shift;2797my%tag;2798my@comment;27992800open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;2801$tag{'id'} =$tag_id;2802while(my$line= <$fd>) {2803chomp$line;2804if($line=~m/^object ([0-9a-fA-F]{40})$/) {2805$tag{'object'} =$1;2806}elsif($line=~m/^type (.+)$/) {2807$tag{'type'} =$1;2808}elsif($line=~m/^tag (.+)$/) {2809$tag{'name'} =$1;2810}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {2811$tag{'author'} =$1;2812$tag{'author_epoch'} =$2;2813$tag{'author_tz'} =$3;2814if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {2815$tag{'author_name'} =$1;2816$tag{'author_email'} =$2;2817}else{2818$tag{'author_name'} =$tag{'author'};2819}2820}elsif($line=~m/--BEGIN/) {2821push@comment,$line;2822last;2823}elsif($lineeq"") {2824last;2825}2826}2827push@comment, <$fd>;2828$tag{'comment'} = \@comment;2829close$fdorreturn;2830if(!defined$tag{'name'}) {2831return2832};2833return%tag2834}28352836sub parse_commit_text {2837my($commit_text,$withparents) =@_;2838my@commit_lines=split'\n',$commit_text;2839my%co;28402841pop@commit_lines;# Remove '\0'28422843if(!@commit_lines) {2844return;2845}28462847my$header=shift@commit_lines;2848if($header!~m/^[0-9a-fA-F]{40}/) {2849return;2850}2851($co{'id'},my@parents) =split' ',$header;2852while(my$line=shift@commit_lines) {2853last if$lineeq"\n";2854if($line=~m/^tree ([0-9a-fA-F]{40})$/) {2855$co{'tree'} =$1;2856}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {2857push@parents,$1;2858}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {2859$co{'author'} = to_utf8($1);2860$co{'author_epoch'} =$2;2861$co{'author_tz'} =$3;2862if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {2863$co{'author_name'} =$1;2864$co{'author_email'} =$2;2865}else{2866$co{'author_name'} =$co{'author'};2867}2868}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {2869$co{'committer'} = to_utf8($1);2870$co{'committer_epoch'} =$2;2871$co{'committer_tz'} =$3;2872if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {2873$co{'committer_name'} =$1;2874$co{'committer_email'} =$2;2875}else{2876$co{'committer_name'} =$co{'committer'};2877}2878}2879}2880if(!defined$co{'tree'}) {2881return;2882};2883$co{'parents'} = \@parents;2884$co{'parent'} =$parents[0];28852886foreachmy$title(@commit_lines) {2887$title=~s/^ //;2888if($titlene"") {2889$co{'title'} = chop_str($title,80,5);2890# remove leading stuff of merges to make the interesting part visible2891if(length($title) >50) {2892$title=~s/^Automatic //;2893$title=~s/^merge (of|with) /Merge ... /i;2894if(length($title) >50) {2895$title=~s/(http|rsync):\/\///;2896}2897if(length($title) >50) {2898$title=~s/(master|www|rsync)\.//;2899}2900if(length($title) >50) {2901$title=~s/kernel.org:?//;2902}2903if(length($title) >50) {2904$title=~s/\/pub\/scm//;2905}2906}2907$co{'title_short'} = chop_str($title,50,5);2908last;2909}2910}2911if(!defined$co{'title'} ||$co{'title'}eq"") {2912$co{'title'} =$co{'title_short'} ='(no commit message)';2913}2914# remove added spaces2915foreachmy$line(@commit_lines) {2916$line=~s/^ //;2917}2918$co{'comment'} = \@commit_lines;29192920my$age=time-$co{'committer_epoch'};2921$co{'age'} =$age;2922$co{'age_string'} = age_string($age);2923my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});2924if($age>60*60*24*7*2) {2925$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;2926$co{'age_string_age'} =$co{'age_string'};2927}else{2928$co{'age_string_date'} =$co{'age_string'};2929$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;2930}2931return%co;2932}29332934sub parse_commit {2935my($commit_id) =@_;2936my%co;29372938local$/="\0";29392940open my$fd,"-|", git_cmd(),"rev-list",2941"--parents",2942"--header",2943"--max-count=1",2944$commit_id,2945"--",2946or die_error(500,"Open git-rev-list failed");2947%co= parse_commit_text(<$fd>,1);2948close$fd;29492950return%co;2951}29522953sub parse_commits {2954my($commit_id,$maxcount,$skip,$filename,@args) =@_;2955my@cos;29562957$maxcount||=1;2958$skip||=0;29592960local$/="\0";29612962open my$fd,"-|", git_cmd(),"rev-list",2963"--header",2964@args,2965("--max-count=".$maxcount),2966("--skip=".$skip),2967@extra_options,2968$commit_id,2969"--",2970($filename? ($filename) : ())2971or die_error(500,"Open git-rev-list failed");2972while(my$line= <$fd>) {2973my%co= parse_commit_text($line);2974push@cos, \%co;2975}2976close$fd;29772978returnwantarray?@cos: \@cos;2979}29802981# parse line of git-diff-tree "raw" output2982sub parse_difftree_raw_line {2983my$line=shift;2984my%res;29852986# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'2987# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'2988if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {2989$res{'from_mode'} =$1;2990$res{'to_mode'} =$2;2991$res{'from_id'} =$3;2992$res{'to_id'} =$4;2993$res{'status'} =$5;2994$res{'similarity'} =$6;2995if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied2996($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);2997}else{2998$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);2999}3000}3001# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3002# combined diff (for merge commit)3003elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3004$res{'nparents'} =length($1);3005$res{'from_mode'} = [split(' ',$2) ];3006$res{'to_mode'} =pop@{$res{'from_mode'}};3007$res{'from_id'} = [split(' ',$3) ];3008$res{'to_id'} =pop@{$res{'from_id'}};3009$res{'status'} = [split('',$4) ];3010$res{'to_file'} = unquote($5);3011}3012# 'c512b523472485aef4fff9e57b229d9d243c967f'3013elsif($line=~m/^([0-9a-fA-F]{40})$/) {3014$res{'commit'} =$1;3015}30163017returnwantarray?%res: \%res;3018}30193020# wrapper: return parsed line of git-diff-tree "raw" output3021# (the argument might be raw line, or parsed info)3022sub parsed_difftree_line {3023my$line_or_ref=shift;30243025if(ref($line_or_ref)eq"HASH") {3026# pre-parsed (or generated by hand)3027return$line_or_ref;3028}else{3029return parse_difftree_raw_line($line_or_ref);3030}3031}30323033# parse line of git-ls-tree output3034sub parse_ls_tree_line {3035my$line=shift;3036my%opts=@_;3037my%res;30383039if($opts{'-l'}) {3040#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3041$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;30423043$res{'mode'} =$1;3044$res{'type'} =$2;3045$res{'hash'} =$3;3046$res{'size'} =$4;3047if($opts{'-z'}) {3048$res{'name'} =$5;3049}else{3050$res{'name'} = unquote($5);3051}3052}else{3053#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3054$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;30553056$res{'mode'} =$1;3057$res{'type'} =$2;3058$res{'hash'} =$3;3059if($opts{'-z'}) {3060$res{'name'} =$4;3061}else{3062$res{'name'} = unquote($4);3063}3064}30653066returnwantarray?%res: \%res;3067}30683069# generates _two_ hashes, references to which are passed as 2 and 3 argument3070sub parse_from_to_diffinfo {3071my($diffinfo,$from,$to,@parents) =@_;30723073if($diffinfo->{'nparents'}) {3074# combined diff3075$from->{'file'} = [];3076$from->{'href'} = [];3077 fill_from_file_info($diffinfo,@parents)3078unlessexists$diffinfo->{'from_file'};3079for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3080$from->{'file'}[$i] =3081defined$diffinfo->{'from_file'}[$i] ?3082$diffinfo->{'from_file'}[$i] :3083$diffinfo->{'to_file'};3084if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3085$from->{'href'}[$i] = href(action=>"blob",3086 hash_base=>$parents[$i],3087 hash=>$diffinfo->{'from_id'}[$i],3088 file_name=>$from->{'file'}[$i]);3089}else{3090$from->{'href'}[$i] =undef;3091}3092}3093}else{3094# ordinary (not combined) diff3095$from->{'file'} =$diffinfo->{'from_file'};3096if($diffinfo->{'status'}ne"A") {# not new (added) file3097$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3098 hash=>$diffinfo->{'from_id'},3099 file_name=>$from->{'file'});3100}else{3101delete$from->{'href'};3102}3103}31043105$to->{'file'} =$diffinfo->{'to_file'};3106if(!is_deleted($diffinfo)) {# file exists in result3107$to->{'href'} = href(action=>"blob", hash_base=>$hash,3108 hash=>$diffinfo->{'to_id'},3109 file_name=>$to->{'file'});3110}else{3111delete$to->{'href'};3112}3113}31143115## ......................................................................3116## parse to array of hashes functions31173118sub git_get_heads_list {3119my$limit=shift;3120my@headslist;31213122open my$fd,'-|', git_cmd(),'for-each-ref',3123($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3124'--format=%(objectname) %(refname) %(subject)%00%(committer)',3125'refs/heads'3126orreturn;3127while(my$line= <$fd>) {3128my%ref_item;31293130chomp$line;3131my($refinfo,$committerinfo) =split(/\0/,$line);3132my($hash,$name,$title) =split(' ',$refinfo,3);3133my($committer,$epoch,$tz) =3134($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3135$ref_item{'fullname'} =$name;3136$name=~s!^refs/heads/!!;31373138$ref_item{'name'} =$name;3139$ref_item{'id'} =$hash;3140$ref_item{'title'} =$title||'(no commit message)';3141$ref_item{'epoch'} =$epoch;3142if($epoch) {3143$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3144}else{3145$ref_item{'age'} ="unknown";3146}31473148push@headslist, \%ref_item;3149}3150close$fd;31513152returnwantarray?@headslist: \@headslist;3153}31543155sub git_get_tags_list {3156my$limit=shift;3157my@tagslist;31583159open my$fd,'-|', git_cmd(),'for-each-ref',3160($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3161'--format=%(objectname) %(objecttype) %(refname) '.3162'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3163'refs/tags'3164orreturn;3165while(my$line= <$fd>) {3166my%ref_item;31673168chomp$line;3169my($refinfo,$creatorinfo) =split(/\0/,$line);3170my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3171my($creator,$epoch,$tz) =3172($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3173$ref_item{'fullname'} =$name;3174$name=~s!^refs/tags/!!;31753176$ref_item{'type'} =$type;3177$ref_item{'id'} =$id;3178$ref_item{'name'} =$name;3179if($typeeq"tag") {3180$ref_item{'subject'} =$title;3181$ref_item{'reftype'} =$reftype;3182$ref_item{'refid'} =$refid;3183}else{3184$ref_item{'reftype'} =$type;3185$ref_item{'refid'} =$id;3186}31873188if($typeeq"tag"||$typeeq"commit") {3189$ref_item{'epoch'} =$epoch;3190if($epoch) {3191$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3192}else{3193$ref_item{'age'} ="unknown";3194}3195}31963197push@tagslist, \%ref_item;3198}3199close$fd;32003201returnwantarray?@tagslist: \@tagslist;3202}32033204## ----------------------------------------------------------------------3205## filesystem-related functions32063207sub get_file_owner {3208my$path=shift;32093210my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3211my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3212if(!defined$gcos) {3213returnundef;3214}3215my$owner=$gcos;3216$owner=~s/[,;].*$//;3217return to_utf8($owner);3218}32193220# assume that file exists3221sub insert_file {3222my$filename=shift;32233224open my$fd,'<',$filename;3225print map{ to_utf8($_) } <$fd>;3226close$fd;3227}32283229## ......................................................................3230## mimetype related functions32313232sub mimetype_guess_file {3233my$filename=shift;3234my$mimemap=shift;3235-r $mimemaporreturnundef;32363237my%mimemap;3238open(my$mh,'<',$mimemap)orreturnundef;3239while(<$mh>) {3240next ifm/^#/;# skip comments3241my($mimetype,$exts) =split(/\t+/);3242if(defined$exts) {3243my@exts=split(/\s+/,$exts);3244foreachmy$ext(@exts) {3245$mimemap{$ext} =$mimetype;3246}3247}3248}3249close($mh);32503251$filename=~/\.([^.]*)$/;3252return$mimemap{$1};3253}32543255sub mimetype_guess {3256my$filename=shift;3257my$mime;3258$filename=~/\./orreturnundef;32593260if($mimetypes_file) {3261my$file=$mimetypes_file;3262if($file!~m!^/!) {# if it is relative path3263# it is relative to project3264$file="$projectroot/$project/$file";3265}3266$mime= mimetype_guess_file($filename,$file);3267}3268$mime||= mimetype_guess_file($filename,'/etc/mime.types');3269return$mime;3270}32713272sub blob_mimetype {3273my$fd=shift;3274my$filename=shift;32753276if($filename) {3277my$mime= mimetype_guess($filename);3278$mimeandreturn$mime;3279}32803281# just in case3282return$default_blob_plain_mimetypeunless$fd;32833284if(-T $fd) {3285return'text/plain';3286}elsif(!$filename) {3287return'application/octet-stream';3288}elsif($filename=~m/\.png$/i) {3289return'image/png';3290}elsif($filename=~m/\.gif$/i) {3291return'image/gif';3292}elsif($filename=~m/\.jpe?g$/i) {3293return'image/jpeg';3294}else{3295return'application/octet-stream';3296}3297}32983299sub blob_contenttype {3300my($fd,$file_name,$type) =@_;33013302$type||= blob_mimetype($fd,$file_name);3303if($typeeq'text/plain'&&defined$default_text_plain_charset) {3304$type.="; charset=$default_text_plain_charset";3305}33063307return$type;3308}33093310# guess file syntax for syntax highlighting; return undef if no highlighting3311# the name of syntax can (in the future) depend on syntax highlighter used3312sub guess_file_syntax {3313my($highlight,$mimetype,$file_name) =@_;3314returnundefunless($highlight&&defined$file_name);33153316# configuration for 'highlight' (http://www.andre-simon.de/)3317# match by basename3318my%highlight_basename= (3319#'Program' => 'py',3320#'Library' => 'py',3321'SConstruct'=>'py',# SCons equivalent of Makefile3322'Makefile'=>'make',3323);3324# match by extension3325my%highlight_ext= (3326# main extensions, defining name of syntax;3327# see files in /usr/share/highlight/langDefs/ directory3328map{$_=>$_}3329qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl),3330# alternate extensions, see /etc/highlight/filetypes.conf3331'h'=>'c',3332map{$_=>'cpp'}qw(cxx c++ cc),3333map{$_=>'php'}qw(php3 php4),3334map{$_=>'pl'}qw(perl pm),# perhaps also 'cgi'3335'mak'=>'make',3336map{$_=>'xml'}qw(xhtml html htm),3337);33383339my$basename= basename($file_name,'.in');3340return$highlight_basename{$basename}3341ifexists$highlight_basename{$basename};33423343$basename=~/\.([^.]*)$/;3344my$ext=$1orreturnundef;3345return$highlight_ext{$ext}3346ifexists$highlight_ext{$ext};33473348returnundef;3349}33503351# run highlighter and return FD of its output,3352# or return original FD if no highlighting3353sub run_highlighter {3354my($fd,$highlight,$syntax) =@_;3355return$fdunless($highlight&&defined$syntax);33563357close$fd3358or die_error(404,"Reading blob failed");3359open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3360"highlight --xhtml --fragment --syntax$syntax|"3361or die_error(500,"Couldn't open file or run syntax highlighter");3362return$fd;3363}33643365## ======================================================================3366## functions printing HTML: header, footer, error page33673368sub get_page_title {3369my$title= to_utf8($site_name);33703371return$titleunless(defined$project);3372$title.=" - ". to_utf8($project);33733374return$titleunless(defined$action);3375$title.="/$action";# $action is US-ASCII (7bit ASCII)33763377return$titleunless(defined$file_name);3378$title.=" - ". esc_path($file_name);3379if($actioneq"tree"&&$file_name!~ m|/$|) {3380$title.="/";3381}33823383return$title;3384}33853386sub git_header_html {3387my$status=shift||"200 OK";3388my$expires=shift;3389my%opts=@_;33903391my$title= get_page_title();3392my$content_type;3393# require explicit support from the UA if we are to send the page as3394# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3395# we have to do this because MSIE sometimes globs '*/*', pretending to3396# support xhtml+xml but choking when it gets what it asked for.3397if(defined$cgi->http('HTTP_ACCEPT') &&3398$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3399$cgi->Accept('application/xhtml+xml') !=0) {3400$content_type='application/xhtml+xml';3401}else{3402$content_type='text/html';3403}3404print$cgi->header(-type=>$content_type, -charset =>'utf-8',3405-status=>$status, -expires =>$expires)3406unless($opts{'-no_http_header'});3407my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3408print<<EOF;3409<?xml version="1.0" encoding="utf-8"?>3410<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3411<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3412<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3413<!-- git core binaries version$git_version-->3414<head>3415<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3416<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3417<meta name="robots" content="index, nofollow"/>3418<title>$title</title>3419EOF3420# the stylesheet, favicon etc urls won't work correctly with path_info3421# unless we set the appropriate base URL3422if($ENV{'PATH_INFO'}) {3423print"<base href=\"".esc_url($base_url)."\"/>\n";3424}3425# print out each stylesheet that exist, providing backwards capability3426# for those people who defined $stylesheet in a config file3427if(defined$stylesheet) {3428print'<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";3429}else{3430foreachmy$stylesheet(@stylesheets) {3431next unless$stylesheet;3432print'<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";3433}3434}3435if(defined$project) {3436my%href_params= get_feed_info();3437if(!exists$href_params{'-title'}) {3438$href_params{'-title'} ='log';3439}34403441foreachmy$formatqw(RSS Atom){3442my$type=lc($format);3443my%link_attr= (3444'-rel'=>'alternate',3445'-title'=>"$project-$href_params{'-title'} -$formatfeed",3446'-type'=>"application/$type+xml"3447);34483449$href_params{'action'} =$type;3450$link_attr{'-href'} = href(%href_params);3451print"<link ".3452"rel=\"$link_attr{'-rel'}\"".3453"title=\"$link_attr{'-title'}\"".3454"href=\"$link_attr{'-href'}\"".3455"type=\"$link_attr{'-type'}\"".3456"/>\n";34573458$href_params{'extra_options'} ='--no-merges';3459$link_attr{'-href'} = href(%href_params);3460$link_attr{'-title'} .=' (no merges)';3461print"<link ".3462"rel=\"$link_attr{'-rel'}\"".3463"title=\"$link_attr{'-title'}\"".3464"href=\"$link_attr{'-href'}\"".3465"type=\"$link_attr{'-type'}\"".3466"/>\n";3467}34683469}else{3470printf('<link rel="alternate" title="%sprojects list" '.3471'href="%s" type="text/plain; charset=utf-8" />'."\n",3472$site_name, href(project=>undef, action=>"project_index"));3473printf('<link rel="alternate" title="%sprojects feeds" '.3474'href="%s" type="text/x-opml" />'."\n",3475$site_name, href(project=>undef, action=>"opml"));3476}3477if(defined$favicon) {3478printqq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);3479}34803481print"</head>\n".3482"<body>\n";34833484if(defined$site_header&& -f $site_header) {3485 insert_file($site_header);3486}34873488print"<div class=\"page_header\">\n".3489$cgi->a({-href => esc_url($logo_url),3490-title =>$logo_label},3491qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));3492print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3493if(defined$project) {3494print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3495if(defined$action) {3496print" /$action";3497}3498print"\n";3499}3500print"</div>\n";35013502my$have_search= gitweb_check_feature('search');3503if(defined$project&&$have_search) {3504if(!defined$searchtext) {3505$searchtext="";3506}3507my$search_hash;3508if(defined$hash_base) {3509$search_hash=$hash_base;3510}elsif(defined$hash) {3511$search_hash=$hash;3512}else{3513$search_hash="HEAD";3514}3515my$action=$my_uri;3516my$use_pathinfo= gitweb_check_feature('pathinfo');3517if($use_pathinfo) {3518$action.="/".esc_url($project);3519}3520print$cgi->startform(-method=>"get", -action =>$action) .3521"<div class=\"search\">\n".3522(!$use_pathinfo&&3523$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3524$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3525$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3526$cgi->popup_menu(-name =>'st', -default=>'commit',3527-values=> ['commit','grep','author','committer','pickaxe']) .3528$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3529" search:\n",3530$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3531"<span title=\"Extended regular expression\">".3532$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3533-checked =>$search_use_regexp) .3534"</span>".3535"</div>".3536$cgi->end_form() ."\n";3537}3538}35393540sub git_footer_html {3541my$feed_class='rss_logo';35423543print"<div class=\"page_footer\">\n";3544if(defined$project) {3545my$descr= git_get_project_description($project);3546if(defined$descr) {3547print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3548}35493550my%href_params= get_feed_info();3551if(!%href_params) {3552$feed_class.=' generic';3553}3554$href_params{'-title'} ||='log';35553556foreachmy$formatqw(RSS Atom){3557$href_params{'action'} =lc($format);3558print$cgi->a({-href => href(%href_params),3559-title =>"$href_params{'-title'}$formatfeed",3560-class=>$feed_class},$format)."\n";3561}35623563}else{3564print$cgi->a({-href => href(project=>undef, action=>"opml"),3565-class=>$feed_class},"OPML") ." ";3566print$cgi->a({-href => href(project=>undef, action=>"project_index"),3567-class=>$feed_class},"TXT") ."\n";3568}3569print"</div>\n";# class="page_footer"35703571if(defined$t0&& gitweb_check_feature('timed')) {3572print"<div id=\"generating_info\">\n";3573print'This page took '.3574'<span id="generating_time" class="time_span">'.3575 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).3576' seconds </span>'.3577' and '.3578'<span id="generating_cmd">'.3579$number_of_git_cmds.3580'</span> git commands '.3581" to generate.\n";3582print"</div>\n";# class="page_footer"3583}35843585if(defined$site_footer&& -f $site_footer) {3586 insert_file($site_footer);3587}35883589print qq!<script type="text/javascript" src="$javascript"></script>\n!;3590if(defined$action&&3591$actioneq'blame_incremental') {3592print qq!<script type="text/javascript">\n!.3593 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.3594 qq!"!. href() .qq!");\n!.3595 qq!</script>\n!;3596}elsif(gitweb_check_feature('javascript-actions')) {3597print qq!<script type="text/javascript">\n!.3598 qq!window.onload = fixLinks;\n!.3599 qq!</script>\n!;3600}36013602print"</body>\n".3603"</html>";3604}36053606# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])3607# Example: die_error(404, 'Hash not found')3608# By convention, use the following status codes (as defined in RFC 2616):3609# 400: Invalid or missing CGI parameters, or3610# requested object exists but has wrong type.3611# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3612# this server or project.3613# 404: Requested object/revision/project doesn't exist.3614# 500: The server isn't configured properly, or3615# an internal error occurred (e.g. failed assertions caused by bugs), or3616# an unknown error occurred (e.g. the git binary died unexpectedly).3617# 503: The server is currently unavailable (because it is overloaded,3618# or down for maintenance). Generally, this is a temporary state.3619sub die_error {3620my$status=shift||500;3621my$error= esc_html(shift) ||"Internal Server Error";3622my$extra=shift;3623my%opts=@_;36243625my%http_responses= (3626400=>'400 Bad Request',3627403=>'403 Forbidden',3628404=>'404 Not Found',3629500=>'500 Internal Server Error',3630503=>'503 Service Unavailable',3631);3632 git_header_html($http_responses{$status},undef,%opts);3633print<<EOF;3634<div class="page_body">3635<br /><br />3636$status-$error3637<br />3638EOF3639if(defined$extra) {3640print"<hr />\n".3641"$extra\n";3642}3643print"</div>\n";36443645 git_footer_html();3646goto DONE_GITWEB3647unless($opts{'-error_handler'});3648}36493650## ----------------------------------------------------------------------3651## functions printing or outputting HTML: navigation36523653sub git_print_page_nav {3654my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;3655$extra=''if!defined$extra;# pager or formats36563657my@navs=qw(summary shortlog log commit commitdiff tree);3658if($suppress) {3659@navs=grep{$_ne$suppress}@navs;3660}36613662my%arg=map{$_=> {action=>$_} }@navs;3663if(defined$head) {3664for(qw(commit commitdiff)) {3665$arg{$_}{'hash'} =$head;3666}3667if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {3668for(qw(shortlog log)) {3669$arg{$_}{'hash'} =$head;3670}3671}3672}36733674$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;3675$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;36763677my@actions= gitweb_get_feature('actions');3678my%repl= (3679'%'=>'%',3680'n'=>$project,# project name3681'f'=>$git_dir,# project path within filesystem3682'h'=>$treehead||'',# current hash ('h' parameter)3683'b'=>$treebase||'',# hash base ('hb' parameter)3684);3685while(@actions) {3686my($label,$link,$pos) =splice(@actions,0,3);3687# insert3688@navs=map{$_eq$pos? ($_,$label) :$_}@navs;3689# munch munch3690$link=~s/%([%nfhb])/$repl{$1}/g;3691$arg{$label}{'_href'} =$link;3692}36933694print"<div class=\"page_nav\">\n".3695(join" | ",3696map{$_eq$current?3697$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")3698}@navs);3699print"<br/>\n$extra<br/>\n".3700"</div>\n";3701}37023703sub format_paging_nav {3704my($action,$page,$has_next_link) =@_;3705my$paging_nav;370637073708if($page>0) {3709$paging_nav.=3710$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .3711" ⋅ ".3712$cgi->a({-href => href(-replay=>1, page=>$page-1),3713-accesskey =>"p", -title =>"Alt-p"},"prev");3714}else{3715$paging_nav.="first ⋅ prev";3716}37173718if($has_next_link) {3719$paging_nav.=" ⋅ ".3720$cgi->a({-href => href(-replay=>1, page=>$page+1),3721-accesskey =>"n", -title =>"Alt-n"},"next");3722}else{3723$paging_nav.=" ⋅ next";3724}37253726return$paging_nav;3727}37283729## ......................................................................3730## functions printing or outputting HTML: div37313732sub git_print_header_div {3733my($action,$title,$hash,$hash_base) =@_;3734my%args= ();37353736$args{'action'} =$action;3737$args{'hash'} =$hashif$hash;3738$args{'hash_base'} =$hash_baseif$hash_base;37393740print"<div class=\"header\">\n".3741$cgi->a({-href => href(%args), -class=>"title"},3742$title?$title:$action) .3743"\n</div>\n";3744}37453746sub print_local_time {3747print format_local_time(@_);3748}37493750sub format_local_time {3751my$localtime='';3752my%date=@_;3753if($date{'hour_local'} <6) {3754$localtime.=sprintf(" (<span class=\"atnight\">%02d:%02d</span>%s)",3755$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});3756}else{3757$localtime.=sprintf(" (%02d:%02d%s)",3758$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});3759}37603761return$localtime;3762}37633764# Outputs the author name and date in long form3765sub git_print_authorship {3766my$co=shift;3767my%opts=@_;3768my$tag=$opts{-tag} ||'div';3769my$author=$co->{'author_name'};37703771my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});3772print"<$tagclass=\"author_date\">".3773 format_search_author($author,"author", esc_html($author)) .3774" [$ad{'rfc2822'}";3775 print_local_time(%ad)if($opts{-localtime});3776print"]". git_get_avatar($co->{'author_email'}, -pad_before =>1)3777."</$tag>\n";3778}37793780# Outputs table rows containing the full author or committer information,3781# in the format expected for 'commit' view (& similia).3782# Parameters are a commit hash reference, followed by the list of people3783# to output information for. If the list is empty it defalts to both3784# author and committer.3785sub git_print_authorship_rows {3786my$co=shift;3787# too bad we can't use @people = @_ || ('author', 'committer')3788my@people=@_;3789@people= ('author','committer')unless@people;3790foreachmy$who(@people) {3791my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});3792print"<tr><td>$who</td><td>".3793 format_search_author($co->{"${who}_name"},$who,3794 esc_html($co->{"${who}_name"})) ." ".3795 format_search_author($co->{"${who}_email"},$who,3796 esc_html("<".$co->{"${who}_email"} .">")) .3797"</td><td rowspan=\"2\">".3798 git_get_avatar($co->{"${who}_email"}, -size =>'double') .3799"</td></tr>\n".3800"<tr>".3801"<td></td><td>$wd{'rfc2822'}";3802 print_local_time(%wd);3803print"</td>".3804"</tr>\n";3805}3806}38073808sub git_print_page_path {3809my$name=shift;3810my$type=shift;3811my$hb=shift;381238133814print"<div class=\"page_path\">";3815print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),3816-title =>'tree root'}, to_utf8("[$project]"));3817print" / ";3818if(defined$name) {3819my@dirname=split'/',$name;3820my$basename=pop@dirname;3821my$fullname='';38223823foreachmy$dir(@dirname) {3824$fullname.= ($fullname?'/':'') .$dir;3825print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,3826 hash_base=>$hb),3827-title =>$fullname}, esc_path($dir));3828print" / ";3829}3830if(defined$type&&$typeeq'blob') {3831print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,3832 hash_base=>$hb),3833-title =>$name}, esc_path($basename));3834}elsif(defined$type&&$typeeq'tree') {3835print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,3836 hash_base=>$hb),3837-title =>$name}, esc_path($basename));3838print" / ";3839}else{3840print esc_path($basename);3841}3842}3843print"<br/></div>\n";3844}38453846sub git_print_log {3847my$log=shift;3848my%opts=@_;38493850if($opts{'-remove_title'}) {3851# remove title, i.e. first line of log3852shift@$log;3853}3854# remove leading empty lines3855while(defined$log->[0] &&$log->[0]eq"") {3856shift@$log;3857}38583859# print log3860my$signoff=0;3861my$empty=0;3862foreachmy$line(@$log) {3863if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {3864$signoff=1;3865$empty=0;3866if(!$opts{'-remove_signoff'}) {3867print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";3868next;3869}else{3870# remove signoff lines3871next;3872}3873}else{3874$signoff=0;3875}38763877# print only one empty line3878# do not print empty line after signoff3879if($lineeq"") {3880next if($empty||$signoff);3881$empty=1;3882}else{3883$empty=0;3884}38853886print format_log_line_html($line) ."<br/>\n";3887}38883889if($opts{'-final_empty_line'}) {3890# end with single empty line3891print"<br/>\n"unless$empty;3892}3893}38943895# return link target (what link points to)3896sub git_get_link_target {3897my$hash=shift;3898my$link_target;38993900# read link3901open my$fd,"-|", git_cmd(),"cat-file","blob",$hash3902orreturn;3903{3904local$/=undef;3905$link_target= <$fd>;3906}3907close$fd3908orreturn;39093910return$link_target;3911}39123913# given link target, and the directory (basedir) the link is in,3914# return target of link relative to top directory (top tree);3915# return undef if it is not possible (including absolute links).3916sub normalize_link_target {3917my($link_target,$basedir) =@_;39183919# absolute symlinks (beginning with '/') cannot be normalized3920return if(substr($link_target,0,1)eq'/');39213922# normalize link target to path from top (root) tree (dir)3923my$path;3924if($basedir) {3925$path=$basedir.'/'.$link_target;3926}else{3927# we are in top (root) tree (dir)3928$path=$link_target;3929}39303931# remove //, /./, and /../3932my@path_parts;3933foreachmy$part(split('/',$path)) {3934# discard '.' and ''3935next if(!$part||$parteq'.');3936# handle '..'3937if($parteq'..') {3938if(@path_parts) {3939pop@path_parts;3940}else{3941# link leads outside repository (outside top dir)3942return;3943}3944}else{3945push@path_parts,$part;3946}3947}3948$path=join('/',@path_parts);39493950return$path;3951}39523953# print tree entry (row of git_tree), but without encompassing <tr> element3954sub git_print_tree_entry {3955my($t,$basedir,$hash_base,$have_blame) =@_;39563957my%base_key= ();3958$base_key{'hash_base'} =$hash_baseifdefined$hash_base;39593960# The format of a table row is: mode list link. Where mode is3961# the mode of the entry, list is the name of the entry, an href,3962# and link is the action links of the entry.39633964print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";3965if(exists$t->{'size'}) {3966print"<td class=\"size\">$t->{'size'}</td>\n";3967}3968if($t->{'type'}eq"blob") {3969print"<td class=\"list\">".3970$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},3971 file_name=>"$basedir$t->{'name'}",%base_key),3972-class=>"list"}, esc_path($t->{'name'}));3973if(S_ISLNK(oct$t->{'mode'})) {3974my$link_target= git_get_link_target($t->{'hash'});3975if($link_target) {3976my$norm_target= normalize_link_target($link_target,$basedir);3977if(defined$norm_target) {3978print" -> ".3979$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,3980 file_name=>$norm_target),3981-title =>$norm_target}, esc_path($link_target));3982}else{3983print" -> ". esc_path($link_target);3984}3985}3986}3987print"</td>\n";3988print"<td class=\"link\">";3989print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},3990 file_name=>"$basedir$t->{'name'}",%base_key)},3991"blob");3992if($have_blame) {3993print" | ".3994$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},3995 file_name=>"$basedir$t->{'name'}",%base_key)},3996"blame");3997}3998if(defined$hash_base) {3999print" | ".4000$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4001 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4002"history");4003}4004print" | ".4005$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4006 file_name=>"$basedir$t->{'name'}")},4007"raw");4008print"</td>\n";40094010}elsif($t->{'type'}eq"tree") {4011print"<td class=\"list\">";4012print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4013 file_name=>"$basedir$t->{'name'}",4014%base_key)},4015 esc_path($t->{'name'}));4016print"</td>\n";4017print"<td class=\"link\">";4018print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4019 file_name=>"$basedir$t->{'name'}",4020%base_key)},4021"tree");4022if(defined$hash_base) {4023print" | ".4024$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4025 file_name=>"$basedir$t->{'name'}")},4026"history");4027}4028print"</td>\n";4029}else{4030# unknown object: we can only present history for it4031# (this includes 'commit' object, i.e. submodule support)4032print"<td class=\"list\">".4033 esc_path($t->{'name'}) .4034"</td>\n";4035print"<td class=\"link\">";4036if(defined$hash_base) {4037print$cgi->a({-href => href(action=>"history",4038 hash_base=>$hash_base,4039 file_name=>"$basedir$t->{'name'}")},4040"history");4041}4042print"</td>\n";4043}4044}40454046## ......................................................................4047## functions printing large fragments of HTML40484049# get pre-image filenames for merge (combined) diff4050sub fill_from_file_info {4051my($diff,@parents) =@_;40524053$diff->{'from_file'} = [ ];4054$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4055for(my$i=0;$i<$diff->{'nparents'};$i++) {4056if($diff->{'status'}[$i]eq'R'||4057$diff->{'status'}[$i]eq'C') {4058$diff->{'from_file'}[$i] =4059 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4060}4061}40624063return$diff;4064}40654066# is current raw difftree line of file deletion4067sub is_deleted {4068my$diffinfo=shift;40694070return$diffinfo->{'to_id'}eq('0' x 40);4071}40724073# does patch correspond to [previous] difftree raw line4074# $diffinfo - hashref of parsed raw diff format4075# $patchinfo - hashref of parsed patch diff format4076# (the same keys as in $diffinfo)4077sub is_patch_split {4078my($diffinfo,$patchinfo) =@_;40794080returndefined$diffinfo&&defined$patchinfo4081&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4082}408340844085sub git_difftree_body {4086my($difftree,$hash,@parents) =@_;4087my($parent) =$parents[0];4088my$have_blame= gitweb_check_feature('blame');4089print"<div class=\"list_head\">\n";4090if($#{$difftree} >10) {4091print(($#{$difftree} +1) ." files changed:\n");4092}4093print"</div>\n";40944095print"<table class=\"".4096(@parents>1?"combined ":"") .4097"diff_tree\">\n";40984099# header only for combined diff in 'commitdiff' view4100my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4101if($has_header) {4102# table header4103print"<thead><tr>\n".4104"<th></th><th></th>\n";# filename, patchN link4105for(my$i=0;$i<@parents;$i++) {4106my$par=$parents[$i];4107print"<th>".4108$cgi->a({-href => href(action=>"commitdiff",4109 hash=>$hash, hash_parent=>$par),4110-title =>'commitdiff to parent number '.4111($i+1) .': '.substr($par,0,7)},4112$i+1) .4113" </th>\n";4114}4115print"</tr></thead>\n<tbody>\n";4116}41174118my$alternate=1;4119my$patchno=0;4120foreachmy$line(@{$difftree}) {4121my$diff= parsed_difftree_line($line);41224123if($alternate) {4124print"<tr class=\"dark\">\n";4125}else{4126print"<tr class=\"light\">\n";4127}4128$alternate^=1;41294130if(exists$diff->{'nparents'}) {# combined diff41314132 fill_from_file_info($diff,@parents)4133unlessexists$diff->{'from_file'};41344135if(!is_deleted($diff)) {4136# file exists in the result (child) commit4137print"<td>".4138$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4139 file_name=>$diff->{'to_file'},4140 hash_base=>$hash),4141-class=>"list"}, esc_path($diff->{'to_file'})) .4142"</td>\n";4143}else{4144print"<td>".4145 esc_path($diff->{'to_file'}) .4146"</td>\n";4147}41484149if($actioneq'commitdiff') {4150# link to patch4151$patchno++;4152print"<td class=\"link\">".4153$cgi->a({-href =>"#patch$patchno"},"patch") .4154" | ".4155"</td>\n";4156}41574158my$has_history=0;4159my$not_deleted=0;4160for(my$i=0;$i<$diff->{'nparents'};$i++) {4161my$hash_parent=$parents[$i];4162my$from_hash=$diff->{'from_id'}[$i];4163my$from_path=$diff->{'from_file'}[$i];4164my$status=$diff->{'status'}[$i];41654166$has_history||= ($statusne'A');4167$not_deleted||= ($statusne'D');41684169if($statuseq'A') {4170print"<td class=\"link\"align=\"right\"> | </td>\n";4171}elsif($statuseq'D') {4172print"<td class=\"link\">".4173$cgi->a({-href => href(action=>"blob",4174 hash_base=>$hash,4175 hash=>$from_hash,4176 file_name=>$from_path)},4177"blob". ($i+1)) .4178" | </td>\n";4179}else{4180if($diff->{'to_id'}eq$from_hash) {4181print"<td class=\"link nochange\">";4182}else{4183print"<td class=\"link\">";4184}4185print$cgi->a({-href => href(action=>"blobdiff",4186 hash=>$diff->{'to_id'},4187 hash_parent=>$from_hash,4188 hash_base=>$hash,4189 hash_parent_base=>$hash_parent,4190 file_name=>$diff->{'to_file'},4191 file_parent=>$from_path)},4192"diff". ($i+1)) .4193" | </td>\n";4194}4195}41964197print"<td class=\"link\">";4198if($not_deleted) {4199print$cgi->a({-href => href(action=>"blob",4200 hash=>$diff->{'to_id'},4201 file_name=>$diff->{'to_file'},4202 hash_base=>$hash)},4203"blob");4204print" | "if($has_history);4205}4206if($has_history) {4207print$cgi->a({-href => href(action=>"history",4208 file_name=>$diff->{'to_file'},4209 hash_base=>$hash)},4210"history");4211}4212print"</td>\n";42134214print"</tr>\n";4215next;# instead of 'else' clause, to avoid extra indent4216}4217# else ordinary diff42184219my($to_mode_oct,$to_mode_str,$to_file_type);4220my($from_mode_oct,$from_mode_str,$from_file_type);4221if($diff->{'to_mode'}ne('0' x 6)) {4222$to_mode_oct=oct$diff->{'to_mode'};4223if(S_ISREG($to_mode_oct)) {# only for regular file4224$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4225}4226$to_file_type= file_type($diff->{'to_mode'});4227}4228if($diff->{'from_mode'}ne('0' x 6)) {4229$from_mode_oct=oct$diff->{'from_mode'};4230if(S_ISREG($to_mode_oct)) {# only for regular file4231$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4232}4233$from_file_type= file_type($diff->{'from_mode'});4234}42354236if($diff->{'status'}eq"A") {# created4237my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4238$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4239$mode_chng.="]</span>";4240print"<td>";4241print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4242 hash_base=>$hash, file_name=>$diff->{'file'}),4243-class=>"list"}, esc_path($diff->{'file'}));4244print"</td>\n";4245print"<td>$mode_chng</td>\n";4246print"<td class=\"link\">";4247if($actioneq'commitdiff') {4248# link to patch4249$patchno++;4250print$cgi->a({-href =>"#patch$patchno"},"patch");4251print" | ";4252}4253print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4254 hash_base=>$hash, file_name=>$diff->{'file'})},4255"blob");4256print"</td>\n";42574258}elsif($diff->{'status'}eq"D") {# deleted4259my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4260print"<td>";4261print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4262 hash_base=>$parent, file_name=>$diff->{'file'}),4263-class=>"list"}, esc_path($diff->{'file'}));4264print"</td>\n";4265print"<td>$mode_chng</td>\n";4266print"<td class=\"link\">";4267if($actioneq'commitdiff') {4268# link to patch4269$patchno++;4270print$cgi->a({-href =>"#patch$patchno"},"patch");4271print" | ";4272}4273print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4274 hash_base=>$parent, file_name=>$diff->{'file'})},4275"blob") ." | ";4276if($have_blame) {4277print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4278 file_name=>$diff->{'file'})},4279"blame") ." | ";4280}4281print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4282 file_name=>$diff->{'file'})},4283"history");4284print"</td>\n";42854286}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4287my$mode_chnge="";4288if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4289$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4290if($from_file_typene$to_file_type) {4291$mode_chnge.=" from$from_file_typeto$to_file_type";4292}4293if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4294if($from_mode_str&&$to_mode_str) {4295$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4296}elsif($to_mode_str) {4297$mode_chnge.=" mode:$to_mode_str";4298}4299}4300$mode_chnge.="]</span>\n";4301}4302print"<td>";4303print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4304 hash_base=>$hash, file_name=>$diff->{'file'}),4305-class=>"list"}, esc_path($diff->{'file'}));4306print"</td>\n";4307print"<td>$mode_chnge</td>\n";4308print"<td class=\"link\">";4309if($actioneq'commitdiff') {4310# link to patch4311$patchno++;4312print$cgi->a({-href =>"#patch$patchno"},"patch") .4313" | ";4314}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4315# "commit" view and modified file (not onlu mode changed)4316print$cgi->a({-href => href(action=>"blobdiff",4317 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4318 hash_base=>$hash, hash_parent_base=>$parent,4319 file_name=>$diff->{'file'})},4320"diff") .4321" | ";4322}4323print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4324 hash_base=>$hash, file_name=>$diff->{'file'})},4325"blob") ." | ";4326if($have_blame) {4327print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4328 file_name=>$diff->{'file'})},4329"blame") ." | ";4330}4331print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4332 file_name=>$diff->{'file'})},4333"history");4334print"</td>\n";43354336}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4337my%status_name= ('R'=>'moved','C'=>'copied');4338my$nstatus=$status_name{$diff->{'status'}};4339my$mode_chng="";4340if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4341# mode also for directories, so we cannot use $to_mode_str4342$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4343}4344print"<td>".4345$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4346 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4347-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4348"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4349$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4350 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4351-class=>"list"}, esc_path($diff->{'from_file'})) .4352" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4353"<td class=\"link\">";4354if($actioneq'commitdiff') {4355# link to patch4356$patchno++;4357print$cgi->a({-href =>"#patch$patchno"},"patch") .4358" | ";4359}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4360# "commit" view and modified file (not only pure rename or copy)4361print$cgi->a({-href => href(action=>"blobdiff",4362 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4363 hash_base=>$hash, hash_parent_base=>$parent,4364 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4365"diff") .4366" | ";4367}4368print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4369 hash_base=>$parent, file_name=>$diff->{'to_file'})},4370"blob") ." | ";4371if($have_blame) {4372print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4373 file_name=>$diff->{'to_file'})},4374"blame") ." | ";4375}4376print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4377 file_name=>$diff->{'to_file'})},4378"history");4379print"</td>\n";43804381}# we should not encounter Unmerged (U) or Unknown (X) status4382print"</tr>\n";4383}4384print"</tbody>"if$has_header;4385print"</table>\n";4386}43874388sub git_patchset_body {4389my($fd,$difftree,$hash,@hash_parents) =@_;4390my($hash_parent) =$hash_parents[0];43914392my$is_combined= (@hash_parents>1);4393my$patch_idx=0;4394my$patch_number=0;4395my$patch_line;4396my$diffinfo;4397my$to_name;4398my(%from,%to);43994400print"<div class=\"patchset\">\n";44014402# skip to first patch4403while($patch_line= <$fd>) {4404chomp$patch_line;44054406last if($patch_line=~m/^diff /);4407}44084409 PATCH:4410while($patch_line) {44114412# parse "git diff" header line4413if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4414# $1 is from_name, which we do not use4415$to_name= unquote($2);4416$to_name=~s!^b/!!;4417}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4418# $1 is 'cc' or 'combined', which we do not use4419$to_name= unquote($2);4420}else{4421$to_name=undef;4422}44234424# check if current patch belong to current raw line4425# and parse raw git-diff line if needed4426if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4427# this is continuation of a split patch4428print"<div class=\"patch cont\">\n";4429}else{4430# advance raw git-diff output if needed4431$patch_idx++ifdefined$diffinfo;44324433# read and prepare patch information4434$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);44354436# compact combined diff output can have some patches skipped4437# find which patch (using pathname of result) we are at now;4438if($is_combined) {4439while($to_namene$diffinfo->{'to_file'}) {4440print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4441 format_diff_cc_simplified($diffinfo,@hash_parents) .4442"</div>\n";# class="patch"44434444$patch_idx++;4445$patch_number++;44464447last if$patch_idx>$#$difftree;4448$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4449}4450}44514452# modifies %from, %to hashes4453 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);44544455# this is first patch for raw difftree line with $patch_idx index4456# we index @$difftree array from 0, but number patches from 14457print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4458}44594460# git diff header4461#assert($patch_line =~ m/^diff /) if DEBUG;4462#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4463$patch_number++;4464# print "git diff" header4465print format_git_diff_header_line($patch_line,$diffinfo,4466 \%from, \%to);44674468# print extended diff header4469print"<div class=\"diff extended_header\">\n";4470 EXTENDED_HEADER:4471while($patch_line= <$fd>) {4472chomp$patch_line;44734474last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);44754476print format_extended_diff_header_line($patch_line,$diffinfo,4477 \%from, \%to);4478}4479print"</div>\n";# class="diff extended_header"44804481# from-file/to-file diff header4482if(!$patch_line) {4483print"</div>\n";# class="patch"4484last PATCH;4485}4486next PATCH if($patch_line=~m/^diff /);4487#assert($patch_line =~ m/^---/) if DEBUG;44884489my$last_patch_line=$patch_line;4490$patch_line= <$fd>;4491chomp$patch_line;4492#assert($patch_line =~ m/^\+\+\+/) if DEBUG;44934494print format_diff_from_to_header($last_patch_line,$patch_line,4495$diffinfo, \%from, \%to,4496@hash_parents);44974498# the patch itself4499 LINE:4500while($patch_line= <$fd>) {4501chomp$patch_line;45024503next PATCH if($patch_line=~m/^diff /);45044505print format_diff_line($patch_line, \%from, \%to);4506}45074508}continue{4509print"</div>\n";# class="patch"4510}45114512# for compact combined (--cc) format, with chunk and patch simpliciaction4513# patchset might be empty, but there might be unprocessed raw lines4514for(++$patch_idxif$patch_number>0;4515$patch_idx<@$difftree;4516++$patch_idx) {4517# read and prepare patch information4518$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);45194520# generate anchor for "patch" links in difftree / whatchanged part4521print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4522 format_diff_cc_simplified($diffinfo,@hash_parents) .4523"</div>\n";# class="patch"45244525$patch_number++;4526}45274528if($patch_number==0) {4529if(@hash_parents>1) {4530print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4531}else{4532print"<div class=\"diff nodifferences\">No differences found</div>\n";4533}4534}45354536print"</div>\n";# class="patchset"4537}45384539# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .45404541# fills project list info (age, description, owner, forks) for each4542# project in the list, removing invalid projects from returned list4543# NOTE: modifies $projlist, but does not remove entries from it4544sub fill_project_list_info {4545my($projlist,$check_forks) =@_;4546my@projects;45474548my$show_ctags= gitweb_check_feature('ctags');4549 PROJECT:4550foreachmy$pr(@$projlist) {4551my(@activity) = git_get_last_activity($pr->{'path'});4552unless(@activity) {4553next PROJECT;4554}4555($pr->{'age'},$pr->{'age_string'}) =@activity;4556if(!defined$pr->{'descr'}) {4557my$descr= git_get_project_description($pr->{'path'}) ||"";4558$descr= to_utf8($descr);4559$pr->{'descr_long'} =$descr;4560$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);4561}4562if(!defined$pr->{'owner'}) {4563$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";4564}4565if($check_forks) {4566my$pname=$pr->{'path'};4567if(($pname=~s/\.git$//) &&4568($pname!~/\/$/) &&4569(-d "$projectroot/$pname")) {4570$pr->{'forks'} ="-d$projectroot/$pname";4571}else{4572$pr->{'forks'} =0;4573}4574}4575$show_ctagsand$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});4576push@projects,$pr;4577}45784579return@projects;4580}45814582# print 'sort by' <th> element, generating 'sort by $name' replay link4583# if that order is not selected4584sub print_sort_th {4585print format_sort_th(@_);4586}45874588sub format_sort_th {4589my($name,$order,$header) =@_;4590my$sort_th="";4591$header||=ucfirst($name);45924593if($ordereq$name) {4594$sort_th.="<th>$header</th>\n";4595}else{4596$sort_th.="<th>".4597$cgi->a({-href => href(-replay=>1, order=>$name),4598-class=>"header"},$header) .4599"</th>\n";4600}46014602return$sort_th;4603}46044605sub git_project_list_body {4606# actually uses global variable $project4607my($projlist,$order,$from,$to,$extra,$no_header) =@_;46084609my$check_forks= gitweb_check_feature('forks');4610my@projects= fill_project_list_info($projlist,$check_forks);46114612$order||=$default_projects_order;4613$from=0unlessdefined$from;4614$to=$#projectsif(!defined$to||$#projects<$to);46154616my%order_info= (4617 project => { key =>'path', type =>'str'},4618 descr => { key =>'descr_long', type =>'str'},4619 owner => { key =>'owner', type =>'str'},4620 age => { key =>'age', type =>'num'}4621);4622my$oi=$order_info{$order};4623if($oi->{'type'}eq'str') {4624@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@projects;4625}else{4626@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@projects;4627}46284629my$show_ctags= gitweb_check_feature('ctags');4630if($show_ctags) {4631my%ctags;4632foreachmy$p(@projects) {4633foreachmy$ct(keys%{$p->{'ctags'}}) {4634$ctags{$ct} +=$p->{'ctags'}->{$ct};4635}4636}4637my$cloud= git_populate_project_tagcloud(\%ctags);4638print git_show_project_tagcloud($cloud,64);4639}46404641print"<table class=\"project_list\">\n";4642unless($no_header) {4643print"<tr>\n";4644if($check_forks) {4645print"<th></th>\n";4646}4647 print_sort_th('project',$order,'Project');4648 print_sort_th('descr',$order,'Description');4649 print_sort_th('owner',$order,'Owner');4650 print_sort_th('age',$order,'Last Change');4651print"<th></th>\n".# for links4652"</tr>\n";4653}4654my$alternate=1;4655my$tagfilter=$cgi->param('by_tag');4656for(my$i=$from;$i<=$to;$i++) {4657my$pr=$projects[$i];46584659next if$tagfilterand$show_ctagsand not grep{lc$_eq lc$tagfilter}keys%{$pr->{'ctags'}};4660next if$searchtextand not$pr->{'path'} =~/$searchtext/4661and not$pr->{'descr_long'} =~/$searchtext/;4662# Weed out forks or non-matching entries of search4663if($check_forks) {4664my$forkbase=$project;$forkbase||='';$forkbase=~ s#\.git$#/#;4665$forkbase="^$forkbase"if$forkbase;4666next ifnot$searchtextand not$tagfilterand$show_ctags4667and$pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe4668}46694670if($alternate) {4671print"<tr class=\"dark\">\n";4672}else{4673print"<tr class=\"light\">\n";4674}4675$alternate^=1;4676if($check_forks) {4677print"<td>";4678if($pr->{'forks'}) {4679print"<!--$pr->{'forks'} -->\n";4680print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"+");4681}4682print"</td>\n";4683}4684print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),4685-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".4686"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),4687-class=>"list", -title =>$pr->{'descr_long'}},4688 esc_html($pr->{'descr'})) ."</td>\n".4689"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";4690print"<td class=\"". age_class($pr->{'age'}) ."\">".4691(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".4692"<td class=\"link\">".4693$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".4694$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".4695$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".4696$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .4697($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .4698"</td>\n".4699"</tr>\n";4700}4701if(defined$extra) {4702print"<tr>\n";4703if($check_forks) {4704print"<td></td>\n";4705}4706print"<td colspan=\"5\">$extra</td>\n".4707"</tr>\n";4708}4709print"</table>\n";4710}47114712sub git_log_body {4713# uses global variable $project4714my($commitlist,$from,$to,$refs,$extra) =@_;47154716$from=0unlessdefined$from;4717$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);47184719for(my$i=0;$i<=$to;$i++) {4720my%co= %{$commitlist->[$i]};4721next if!%co;4722my$commit=$co{'id'};4723my$ref= format_ref_marker($refs,$commit);4724my%ad= parse_date($co{'author_epoch'});4725 git_print_header_div('commit',4726"<span class=\"age\">$co{'age_string'}</span>".4727 esc_html($co{'title'}) .$ref,4728$commit);4729print"<div class=\"title_text\">\n".4730"<div class=\"log_link\">\n".4731$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .4732" | ".4733$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .4734" | ".4735$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .4736"<br/>\n".4737"</div>\n";4738 git_print_authorship(\%co, -tag =>'span');4739print"<br/>\n</div>\n";47404741print"<div class=\"log_body\">\n";4742 git_print_log($co{'comment'}, -final_empty_line=>1);4743print"</div>\n";4744}4745if($extra) {4746print"<div class=\"page_nav\">\n";4747print"$extra\n";4748print"</div>\n";4749}4750}47514752sub git_shortlog_body {4753# uses global variable $project4754my($commitlist,$from,$to,$refs,$extra) =@_;47554756$from=0unlessdefined$from;4757$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);47584759print"<table class=\"shortlog\">\n";4760my$alternate=1;4761for(my$i=$from;$i<=$to;$i++) {4762my%co= %{$commitlist->[$i]};4763my$commit=$co{'id'};4764my$ref= format_ref_marker($refs,$commit);4765if($alternate) {4766print"<tr class=\"dark\">\n";4767}else{4768print"<tr class=\"light\">\n";4769}4770$alternate^=1;4771# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .4772print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4773 format_author_html('td', \%co,10) ."<td>";4774print format_subject_html($co{'title'},$co{'title_short'},4775 href(action=>"commit", hash=>$commit),$ref);4776print"</td>\n".4777"<td class=\"link\">".4778$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".4779$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".4780$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");4781my$snapshot_links= format_snapshot_links($commit);4782if(defined$snapshot_links) {4783print" | ".$snapshot_links;4784}4785print"</td>\n".4786"</tr>\n";4787}4788if(defined$extra) {4789print"<tr>\n".4790"<td colspan=\"4\">$extra</td>\n".4791"</tr>\n";4792}4793print"</table>\n";4794}47954796sub git_history_body {4797# Warning: assumes constant type (blob or tree) during history4798my($commitlist,$from,$to,$refs,$extra,4799$file_name,$file_hash,$ftype) =@_;48004801$from=0unlessdefined$from;4802$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});48034804print"<table class=\"history\">\n";4805my$alternate=1;4806for(my$i=$from;$i<=$to;$i++) {4807my%co= %{$commitlist->[$i]};4808if(!%co) {4809next;4810}4811my$commit=$co{'id'};48124813my$ref= format_ref_marker($refs,$commit);48144815if($alternate) {4816print"<tr class=\"dark\">\n";4817}else{4818print"<tr class=\"light\">\n";4819}4820$alternate^=1;4821print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4822# shortlog: format_author_html('td', \%co, 10)4823 format_author_html('td', \%co,15,3) ."<td>";4824# originally git_history used chop_str($co{'title'}, 50)4825print format_subject_html($co{'title'},$co{'title_short'},4826 href(action=>"commit", hash=>$commit),$ref);4827print"</td>\n".4828"<td class=\"link\">".4829$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".4830$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");48314832if($ftypeeq'blob') {4833my$blob_current=$file_hash;4834my$blob_parent= git_get_hash_by_path($commit,$file_name);4835if(defined$blob_current&&defined$blob_parent&&4836$blob_currentne$blob_parent) {4837print" | ".4838$cgi->a({-href => href(action=>"blobdiff",4839 hash=>$blob_current, hash_parent=>$blob_parent,4840 hash_base=>$hash_base, hash_parent_base=>$commit,4841 file_name=>$file_name)},4842"diff to current");4843}4844}4845print"</td>\n".4846"</tr>\n";4847}4848if(defined$extra) {4849print"<tr>\n".4850"<td colspan=\"4\">$extra</td>\n".4851"</tr>\n";4852}4853print"</table>\n";4854}48554856sub git_tags_body {4857# uses global variable $project4858my($taglist,$from,$to,$extra) =@_;4859$from=0unlessdefined$from;4860$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);48614862print"<table class=\"tags\">\n";4863my$alternate=1;4864for(my$i=$from;$i<=$to;$i++) {4865my$entry=$taglist->[$i];4866my%tag=%$entry;4867my$comment=$tag{'subject'};4868my$comment_short;4869if(defined$comment) {4870$comment_short= chop_str($comment,30,5);4871}4872if($alternate) {4873print"<tr class=\"dark\">\n";4874}else{4875print"<tr class=\"light\">\n";4876}4877$alternate^=1;4878if(defined$tag{'age'}) {4879print"<td><i>$tag{'age'}</i></td>\n";4880}else{4881print"<td></td>\n";4882}4883print"<td>".4884$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),4885-class=>"list name"}, esc_html($tag{'name'})) .4886"</td>\n".4887"<td>";4888if(defined$comment) {4889print format_subject_html($comment,$comment_short,4890 href(action=>"tag", hash=>$tag{'id'}));4891}4892print"</td>\n".4893"<td class=\"selflink\">";4894if($tag{'type'}eq"tag") {4895print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");4896}else{4897print" ";4898}4899print"</td>\n".4900"<td class=\"link\">"." | ".4901$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});4902if($tag{'reftype'}eq"commit") {4903print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .4904" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");4905}elsif($tag{'reftype'}eq"blob") {4906print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");4907}4908print"</td>\n".4909"</tr>";4910}4911if(defined$extra) {4912print"<tr>\n".4913"<td colspan=\"5\">$extra</td>\n".4914"</tr>\n";4915}4916print"</table>\n";4917}49184919sub git_heads_body {4920# uses global variable $project4921my($headlist,$head,$from,$to,$extra) =@_;4922$from=0unlessdefined$from;4923$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);49244925print"<table class=\"heads\">\n";4926my$alternate=1;4927for(my$i=$from;$i<=$to;$i++) {4928my$entry=$headlist->[$i];4929my%ref=%$entry;4930my$curr=$ref{'id'}eq$head;4931if($alternate) {4932print"<tr class=\"dark\">\n";4933}else{4934print"<tr class=\"light\">\n";4935}4936$alternate^=1;4937print"<td><i>$ref{'age'}</i></td>\n".4938($curr?"<td class=\"current_head\">":"<td>") .4939$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),4940-class=>"list name"},esc_html($ref{'name'})) .4941"</td>\n".4942"<td class=\"link\">".4943$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".4944$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".4945$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})},"tree") .4946"</td>\n".4947"</tr>";4948}4949if(defined$extra) {4950print"<tr>\n".4951"<td colspan=\"3\">$extra</td>\n".4952"</tr>\n";4953}4954print"</table>\n";4955}49564957sub git_search_grep_body {4958my($commitlist,$from,$to,$extra) =@_;4959$from=0unlessdefined$from;4960$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);49614962print"<table class=\"commit_search\">\n";4963my$alternate=1;4964for(my$i=$from;$i<=$to;$i++) {4965my%co= %{$commitlist->[$i]};4966if(!%co) {4967next;4968}4969my$commit=$co{'id'};4970if($alternate) {4971print"<tr class=\"dark\">\n";4972}else{4973print"<tr class=\"light\">\n";4974}4975$alternate^=1;4976print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4977 format_author_html('td', \%co,15,5) .4978"<td>".4979$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),4980-class=>"list subject"},4981 chop_and_escape_str($co{'title'},50) ."<br/>");4982my$comment=$co{'comment'};4983foreachmy$line(@$comment) {4984if($line=~m/^(.*?)($search_regexp)(.*)$/i) {4985my($lead,$match,$trail) = ($1,$2,$3);4986$match= chop_str($match,70,5,'center');4987my$contextlen=int((80-length($match))/2);4988$contextlen=30if($contextlen>30);4989$lead= chop_str($lead,$contextlen,10,'left');4990$trail= chop_str($trail,$contextlen,10,'right');49914992$lead= esc_html($lead);4993$match= esc_html($match);4994$trail= esc_html($trail);49954996print"$lead<span class=\"match\">$match</span>$trail<br />";4997}4998}4999print"</td>\n".5000"<td class=\"link\">".5001$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .5002" | ".5003$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .5004" | ".5005$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");5006print"</td>\n".5007"</tr>\n";5008}5009if(defined$extra) {5010print"<tr>\n".5011"<td colspan=\"3\">$extra</td>\n".5012"</tr>\n";5013}5014print"</table>\n";5015}50165017## ======================================================================5018## ======================================================================5019## actions50205021sub git_project_list {5022my$order=$input_params{'order'};5023if(defined$order&&$order!~m/none|project|descr|owner|age/) {5024 die_error(400,"Unknown order parameter");5025}50265027my@list= git_get_projects_list();5028if(!@list) {5029 die_error(404,"No projects found");5030}50315032 git_header_html();5033if(defined$home_text&& -f $home_text) {5034print"<div class=\"index_include\">\n";5035 insert_file($home_text);5036print"</div>\n";5037}5038print$cgi->startform(-method=>"get") .5039"<p class=\"projsearch\">Search:\n".5040$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".5041"</p>".5042$cgi->end_form() ."\n";5043 git_project_list_body(\@list,$order);5044 git_footer_html();5045}50465047sub git_forks {5048my$order=$input_params{'order'};5049if(defined$order&&$order!~m/none|project|descr|owner|age/) {5050 die_error(400,"Unknown order parameter");5051}50525053my@list= git_get_projects_list($project);5054if(!@list) {5055 die_error(404,"No forks found");5056}50575058 git_header_html();5059 git_print_page_nav('','');5060 git_print_header_div('summary',"$projectforks");5061 git_project_list_body(\@list,$order);5062 git_footer_html();5063}50645065sub git_project_index {5066my@projects= git_get_projects_list($project);50675068print$cgi->header(5069-type =>'text/plain',5070-charset =>'utf-8',5071-content_disposition =>'inline; filename="index.aux"');50725073foreachmy$pr(@projects) {5074if(!exists$pr->{'owner'}) {5075$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");5076}50775078my($path,$owner) = ($pr->{'path'},$pr->{'owner'});5079# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '5080$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5081$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5082$path=~s/ /\+/g;5083$owner=~s/ /\+/g;50845085print"$path$owner\n";5086}5087}50885089sub git_summary {5090my$descr= git_get_project_description($project) ||"none";5091my%co= parse_commit("HEAD");5092my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();5093my$head=$co{'id'};50945095my$owner= git_get_project_owner($project);50965097my$refs= git_get_references();5098# These get_*_list functions return one more to allow us to see if5099# there are more ...5100my@taglist= git_get_tags_list(16);5101my@headlist= git_get_heads_list(16);5102my@forklist;5103my$check_forks= gitweb_check_feature('forks');51045105if($check_forks) {5106@forklist= git_get_projects_list($project);5107}51085109 git_header_html();5110 git_print_page_nav('summary','',$head);51115112print"<div class=\"title\"> </div>\n";5113print"<table class=\"projects_list\">\n".5114"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".5115"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";5116if(defined$cd{'rfc2822'}) {5117print"<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";5118}51195120# use per project git URL list in $projectroot/$project/cloneurl5121# or make project git URL from git base URL and project name5122my$url_tag="URL";5123my@url_list= git_get_project_url_list($project);5124@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;5125foreachmy$git_url(@url_list) {5126next unless$git_url;5127print"<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";5128$url_tag="";5129}51305131# Tag cloud5132my$show_ctags= gitweb_check_feature('ctags');5133if($show_ctags) {5134my$ctags= git_get_project_ctags($project);5135my$cloud= git_populate_project_tagcloud($ctags);5136print"<tr id=\"metadata_ctags\"><td>Content tags:<br />";5137print"</td>\n<td>"unless%$ctags;5138print"<form action=\"$show_ctags\"method=\"post\"><input type=\"hidden\"name=\"p\"value=\"$project\"/>Add: <input type=\"text\"name=\"t\"size=\"8\"/></form>";5139print"</td>\n<td>"if%$ctags;5140print git_show_project_tagcloud($cloud,48);5141print"</td></tr>";5142}51435144print"</table>\n";51455146# If XSS prevention is on, we don't include README.html.5147# TODO: Allow a readme in some safe format.5148if(!$prevent_xss&& -s "$projectroot/$project/README.html") {5149print"<div class=\"title\">readme</div>\n".5150"<div class=\"readme\">\n";5151 insert_file("$projectroot/$project/README.html");5152print"\n</div>\n";# class="readme"5153}51545155# we need to request one more than 16 (0..15) to check if5156# those 16 are all5157my@commitlist=$head? parse_commits($head,17) : ();5158if(@commitlist) {5159 git_print_header_div('shortlog');5160 git_shortlog_body(\@commitlist,0,15,$refs,5161$#commitlist<=15?undef:5162$cgi->a({-href => href(action=>"shortlog")},"..."));5163}51645165if(@taglist) {5166 git_print_header_div('tags');5167 git_tags_body(\@taglist,0,15,5168$#taglist<=15?undef:5169$cgi->a({-href => href(action=>"tags")},"..."));5170}51715172if(@headlist) {5173 git_print_header_div('heads');5174 git_heads_body(\@headlist,$head,0,15,5175$#headlist<=15?undef:5176$cgi->a({-href => href(action=>"heads")},"..."));5177}51785179if(@forklist) {5180 git_print_header_div('forks');5181 git_project_list_body(\@forklist,'age',0,15,5182$#forklist<=15?undef:5183$cgi->a({-href => href(action=>"forks")},"..."),5184'no_header');5185}51865187 git_footer_html();5188}51895190sub git_tag {5191my$head= git_get_head_hash($project);5192 git_header_html();5193 git_print_page_nav('','',$head,undef,$head);5194my%tag= parse_tag($hash);51955196if(!%tag) {5197 die_error(404,"Unknown tag object");5198}51995200 git_print_header_div('commit', esc_html($tag{'name'}),$hash);5201print"<div class=\"title_text\">\n".5202"<table class=\"object_header\">\n".5203"<tr>\n".5204"<td>object</td>\n".5205"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5206$tag{'object'}) ."</td>\n".5207"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5208$tag{'type'}) ."</td>\n".5209"</tr>\n";5210if(defined($tag{'author'})) {5211 git_print_authorship_rows(\%tag,'author');5212}5213print"</table>\n\n".5214"</div>\n";5215print"<div class=\"page_body\">";5216my$comment=$tag{'comment'};5217foreachmy$line(@$comment) {5218chomp$line;5219print esc_html($line, -nbsp=>1) ."<br/>\n";5220}5221print"</div>\n";5222 git_footer_html();5223}52245225sub git_blame_common {5226my$format=shift||'porcelain';5227if($formateq'porcelain'&&$cgi->param('js')) {5228$format='incremental';5229$action='blame_incremental';# for page title etc5230}52315232# permissions5233 gitweb_check_feature('blame')5234or die_error(403,"Blame view not allowed");52355236# error checking5237 die_error(400,"No file name given")unless$file_name;5238$hash_base||= git_get_head_hash($project);5239 die_error(404,"Couldn't find base commit")unless$hash_base;5240my%co= parse_commit($hash_base)5241or die_error(404,"Commit not found");5242my$ftype="blob";5243if(!defined$hash) {5244$hash= git_get_hash_by_path($hash_base,$file_name,"blob")5245or die_error(404,"Error looking up file");5246}else{5247$ftype= git_get_type($hash);5248if($ftype!~"blob") {5249 die_error(400,"Object is not a blob");5250}5251}52525253my$fd;5254if($formateq'incremental') {5255# get file contents (as base)5256open$fd,"-|", git_cmd(),'cat-file','blob',$hash5257or die_error(500,"Open git-cat-file failed");5258}elsif($formateq'data') {5259# run git-blame --incremental5260open$fd,"-|", git_cmd(),"blame","--incremental",5261$hash_base,"--",$file_name5262or die_error(500,"Open git-blame --incremental failed");5263}else{5264# run git-blame --porcelain5265open$fd,"-|", git_cmd(),"blame",'-p',5266$hash_base,'--',$file_name5267or die_error(500,"Open git-blame --porcelain failed");5268}52695270# incremental blame data returns early5271if($formateq'data') {5272print$cgi->header(5273-type=>"text/plain", -charset =>"utf-8",5274-status=>"200 OK");5275local$| =1;# output autoflush5276printwhile<$fd>;5277close$fd5278or print"ERROR$!\n";52795280print'END';5281if(defined$t0&& gitweb_check_feature('timed')) {5282print' '.5283 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).5284' '.$number_of_git_cmds;5285}5286print"\n";52875288return;5289}52905291# page header5292 git_header_html();5293my$formats_nav=5294$cgi->a({-href => href(action=>"blob", -replay=>1)},5295"blob") .5296" | ";5297if($formateq'incremental') {5298$formats_nav.=5299$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},5300"blame") ." (non-incremental)";5301}else{5302$formats_nav.=5303$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},5304"blame") ." (incremental)";5305}5306$formats_nav.=5307" | ".5308$cgi->a({-href => href(action=>"history", -replay=>1)},5309"history") .5310" | ".5311$cgi->a({-href => href(action=>$action, file_name=>$file_name)},5312"HEAD");5313 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5314 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5315 git_print_page_path($file_name,$ftype,$hash_base);53165317# page body5318if($formateq'incremental') {5319print"<noscript>\n<div class=\"error\"><center><b>\n".5320"This page requires JavaScript to run.\nUse ".5321$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},5322'this page').5323" instead.\n".5324"</b></center></div>\n</noscript>\n";53255326print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;5327}53285329print qq!<div class="page_body">\n!;5330print qq!<div id="progress_info">.../ ...</div>\n!5331if($formateq'incremental');5332print qq!<table id="blame_table"class="blame" width="100%">\n!.5333#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.5334 qq!<thead>\n!.5335 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.5336 qq!</thead>\n!.5337 qq!<tbody>\n!;53385339my@rev_color=qw(light dark);5340my$num_colors=scalar(@rev_color);5341my$current_color=0;53425343if($formateq'incremental') {5344my$color_class=$rev_color[$current_color];53455346#contents of a file5347my$linenr=0;5348 LINE:5349while(my$line= <$fd>) {5350chomp$line;5351$linenr++;53525353print qq!<tr id="l$linenr"class="$color_class">!.5354 qq!<td class="sha1"><a href=""> </a></td>!.5355 qq!<td class="linenr">!.5356 qq!<a class="linenr" href="">$linenr</a></td>!;5357print qq!<td class="pre">! . esc_html($line) ."</td>\n";5358print qq!</tr>\n!;5359}53605361}else{# porcelain, i.e. ordinary blame5362my%metainfo= ();# saves information about commits53635364# blame data5365 LINE:5366while(my$line= <$fd>) {5367chomp$line;5368# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]5369# no <lines in group> for subsequent lines in group of lines5370my($full_rev,$orig_lineno,$lineno,$group_size) =5371($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);5372if(!exists$metainfo{$full_rev}) {5373$metainfo{$full_rev} = {'nprevious'=>0};5374}5375my$meta=$metainfo{$full_rev};5376my$data;5377while($data= <$fd>) {5378chomp$data;5379last if($data=~s/^\t//);# contents of line5380if($data=~/^(\S+)(?: (.*))?$/) {5381$meta->{$1} =$2unlessexists$meta->{$1};5382}5383if($data=~/^previous /) {5384$meta->{'nprevious'}++;5385}5386}5387my$short_rev=substr($full_rev,0,8);5388my$author=$meta->{'author'};5389my%date=5390 parse_date($meta->{'author-time'},$meta->{'author-tz'});5391my$date=$date{'iso-tz'};5392if($group_size) {5393$current_color= ($current_color+1) %$num_colors;5394}5395my$tr_class=$rev_color[$current_color];5396$tr_class.=' boundary'if(exists$meta->{'boundary'});5397$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);5398$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);5399print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";5400if($group_size) {5401print"<td class=\"sha1\"";5402print" title=\"". esc_html($author) .",$date\"";5403print" rowspan=\"$group_size\""if($group_size>1);5404print">";5405print$cgi->a({-href => href(action=>"commit",5406 hash=>$full_rev,5407 file_name=>$file_name)},5408 esc_html($short_rev));5409if($group_size>=2) {5410my@author_initials= ($author=~/\b([[:upper:]])\B/g);5411if(@author_initials) {5412print"<br />".5413 esc_html(join('',@author_initials));5414# or join('.', ...)5415}5416}5417print"</td>\n";5418}5419# 'previous' <sha1 of parent commit> <filename at commit>5420if(exists$meta->{'previous'} &&5421$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {5422$meta->{'parent'} =$1;5423$meta->{'file_parent'} = unquote($2);5424}5425my$linenr_commit=5426exists($meta->{'parent'}) ?5427$meta->{'parent'} :$full_rev;5428my$linenr_filename=5429exists($meta->{'file_parent'}) ?5430$meta->{'file_parent'} : unquote($meta->{'filename'});5431my$blamed= href(action =>'blame',5432 file_name =>$linenr_filename,5433 hash_base =>$linenr_commit);5434print"<td class=\"linenr\">";5435print$cgi->a({ -href =>"$blamed#l$orig_lineno",5436-class=>"linenr"},5437 esc_html($lineno));5438print"</td>";5439print"<td class=\"pre\">". esc_html($data) ."</td>\n";5440print"</tr>\n";5441}# end while54425443}54445445# footer5446print"</tbody>\n".5447"</table>\n";# class="blame"5448print"</div>\n";# class="blame_body"5449close$fd5450or print"Reading blob failed\n";54515452 git_footer_html();5453}54545455sub git_blame {5456 git_blame_common();5457}54585459sub git_blame_incremental {5460 git_blame_common('incremental');5461}54625463sub git_blame_data {5464 git_blame_common('data');5465}54665467sub git_tags {5468my$head= git_get_head_hash($project);5469 git_header_html();5470 git_print_page_nav('','',$head,undef,$head);5471 git_print_header_div('summary',$project);54725473my@tagslist= git_get_tags_list();5474if(@tagslist) {5475 git_tags_body(\@tagslist);5476}5477 git_footer_html();5478}54795480sub git_heads {5481my$head= git_get_head_hash($project);5482 git_header_html();5483 git_print_page_nav('','',$head,undef,$head);5484 git_print_header_div('summary',$project);54855486my@headslist= git_get_heads_list();5487if(@headslist) {5488 git_heads_body(\@headslist,$head);5489}5490 git_footer_html();5491}54925493sub git_blob_plain {5494my$type=shift;5495my$expires;54965497if(!defined$hash) {5498if(defined$file_name) {5499my$base=$hash_base|| git_get_head_hash($project);5500$hash= git_get_hash_by_path($base,$file_name,"blob")5501or die_error(404,"Cannot find file");5502}else{5503 die_error(400,"No file name defined");5504}5505}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {5506# blobs defined by non-textual hash id's can be cached5507$expires="+1d";5508}55095510open my$fd,"-|", git_cmd(),"cat-file","blob",$hash5511or die_error(500,"Open git-cat-file blob '$hash' failed");55125513# content-type (can include charset)5514$type= blob_contenttype($fd,$file_name,$type);55155516# "save as" filename, even when no $file_name is given5517my$save_as="$hash";5518if(defined$file_name) {5519$save_as=$file_name;5520}elsif($type=~m/^text\//) {5521$save_as.='.txt';5522}55235524# With XSS prevention on, blobs of all types except a few known safe5525# ones are served with "Content-Disposition: attachment" to make sure5526# they don't run in our security domain. For certain image types,5527# blob view writes an <img> tag referring to blob_plain view, and we5528# want to be sure not to break that by serving the image as an5529# attachment (though Firefox 3 doesn't seem to care).5530my$sandbox=$prevent_xss&&5531$type!~m!^(?:text/plain|image/(?:gif|png|jpeg))$!;55325533print$cgi->header(5534-type =>$type,5535-expires =>$expires,5536-content_disposition =>5537($sandbox?'attachment':'inline')5538.'; filename="'.$save_as.'"');5539local$/=undef;5540binmode STDOUT,':raw';5541print<$fd>;5542binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi5543close$fd;5544}55455546sub git_blob {5547my$expires;55485549if(!defined$hash) {5550if(defined$file_name) {5551my$base=$hash_base|| git_get_head_hash($project);5552$hash= git_get_hash_by_path($base,$file_name,"blob")5553or die_error(404,"Cannot find file");5554}else{5555 die_error(400,"No file name defined");5556}5557}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {5558# blobs defined by non-textual hash id's can be cached5559$expires="+1d";5560}55615562my$have_blame= gitweb_check_feature('blame');5563open my$fd,"-|", git_cmd(),"cat-file","blob",$hash5564or die_error(500,"Couldn't cat$file_name,$hash");5565my$mimetype= blob_mimetype($fd,$file_name);5566# use 'blob_plain' (aka 'raw') view for files that cannot be displayed5567if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {5568close$fd;5569return git_blob_plain($mimetype);5570}5571# we can have blame only for text/* mimetype5572$have_blame&&= ($mimetype=~m!^text/!);55735574my$highlight= gitweb_check_feature('highlight');5575my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);5576$fd= run_highlighter($fd,$highlight,$syntax)5577if$syntax;55785579 git_header_html(undef,$expires);5580my$formats_nav='';5581if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5582if(defined$file_name) {5583if($have_blame) {5584$formats_nav.=5585$cgi->a({-href => href(action=>"blame", -replay=>1)},5586"blame") .5587" | ";5588}5589$formats_nav.=5590$cgi->a({-href => href(action=>"history", -replay=>1)},5591"history") .5592" | ".5593$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},5594"raw") .5595" | ".5596$cgi->a({-href => href(action=>"blob",5597 hash_base=>"HEAD", file_name=>$file_name)},5598"HEAD");5599}else{5600$formats_nav.=5601$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},5602"raw");5603}5604 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5605 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5606}else{5607print"<div class=\"page_nav\">\n".5608"<br/><br/></div>\n".5609"<div class=\"title\">$hash</div>\n";5610}5611 git_print_page_path($file_name,"blob",$hash_base);5612print"<div class=\"page_body\">\n";5613if($mimetype=~m!^image/!) {5614print qq!<img type="$mimetype"!;5615if($file_name) {5616print qq! alt="$file_name" title="$file_name"!;5617}5618print qq! src="! .5619 href(action=>"blob_plain", hash=>$hash,5620 hash_base=>$hash_base, file_name=>$file_name) .5621 qq!"/>\n!;5622}else{5623my$nr;5624while(my$line= <$fd>) {5625chomp$line;5626$nr++;5627$line= untabify($line);5628printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,5629$nr, href(-replay =>1),$nr,$nr,$syntax?$line: esc_html($line, -nbsp=>1);5630}5631}5632close$fd5633or print"Reading blob failed.\n";5634print"</div>";5635 git_footer_html();5636}56375638sub git_tree {5639if(!defined$hash_base) {5640$hash_base="HEAD";5641}5642if(!defined$hash) {5643if(defined$file_name) {5644$hash= git_get_hash_by_path($hash_base,$file_name,"tree");5645}else{5646$hash=$hash_base;5647}5648}5649 die_error(404,"No such tree")unlessdefined($hash);56505651my$show_sizes= gitweb_check_feature('show-sizes');5652my$have_blame= gitweb_check_feature('blame');56535654my@entries= ();5655{5656local$/="\0";5657open my$fd,"-|", git_cmd(),"ls-tree",'-z',5658($show_sizes?'-l': ()),@extra_options,$hash5659or die_error(500,"Open git-ls-tree failed");5660@entries=map{chomp;$_} <$fd>;5661close$fd5662or die_error(404,"Reading tree failed");5663}56645665my$refs= git_get_references();5666my$ref= format_ref_marker($refs,$hash_base);5667 git_header_html();5668my$basedir='';5669if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5670my@views_nav= ();5671if(defined$file_name) {5672push@views_nav,5673$cgi->a({-href => href(action=>"history", -replay=>1)},5674"history"),5675$cgi->a({-href => href(action=>"tree",5676 hash_base=>"HEAD", file_name=>$file_name)},5677"HEAD"),5678}5679my$snapshot_links= format_snapshot_links($hash);5680if(defined$snapshot_links) {5681# FIXME: Should be available when we have no hash base as well.5682push@views_nav,$snapshot_links;5683}5684 git_print_page_nav('tree','',$hash_base,undef,undef,5685join(' | ',@views_nav));5686 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);5687}else{5688undef$hash_base;5689print"<div class=\"page_nav\">\n";5690print"<br/><br/></div>\n";5691print"<div class=\"title\">$hash</div>\n";5692}5693if(defined$file_name) {5694$basedir=$file_name;5695if($basedirne''&&substr($basedir, -1)ne'/') {5696$basedir.='/';5697}5698 git_print_page_path($file_name,'tree',$hash_base);5699}5700print"<div class=\"page_body\">\n";5701print"<table class=\"tree\">\n";5702my$alternate=1;5703# '..' (top directory) link if possible5704if(defined$hash_base&&5705defined$file_name&&$file_name=~m![^/]+$!) {5706if($alternate) {5707print"<tr class=\"dark\">\n";5708}else{5709print"<tr class=\"light\">\n";5710}5711$alternate^=1;57125713my$up=$file_name;5714$up=~s!/?[^/]+$!!;5715undef$upunless$up;5716# based on git_print_tree_entry5717print'<td class="mode">'. mode_str('040000') ."</td>\n";5718print'<td class="size"> </td>'."\n"if$show_sizes;5719print'<td class="list">';5720print$cgi->a({-href => href(action=>"tree",5721 hash_base=>$hash_base,5722 file_name=>$up)},5723"..");5724print"</td>\n";5725print"<td class=\"link\"></td>\n";57265727print"</tr>\n";5728}5729foreachmy$line(@entries) {5730my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);57315732if($alternate) {5733print"<tr class=\"dark\">\n";5734}else{5735print"<tr class=\"light\">\n";5736}5737$alternate^=1;57385739 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);57405741print"</tr>\n";5742}5743print"</table>\n".5744"</div>";5745 git_footer_html();5746}57475748sub snapshot_name {5749my($project,$hash) =@_;57505751# path/to/project.git -> project5752# path/to/project/.git -> project5753my$name= to_utf8($project);5754$name=~ s,([^/])/*\.git$,$1,;5755$name= basename($name);5756# sanitize name5757$name=~s/[[:cntrl:]]/?/g;57585759my$ver=$hash;5760if($hash=~/^[0-9a-fA-F]+$/) {5761# shorten SHA-1 hash5762my$full_hash= git_get_full_hash($project,$hash);5763if($full_hash=~/^$hash/&&length($hash) >7) {5764$ver= git_get_short_hash($project,$hash);5765}5766}elsif($hash=~m!^refs/tags/(.*)$!) {5767# tags don't need shortened SHA-1 hash5768$ver=$1;5769}else{5770# branches and other need shortened SHA-1 hash5771if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {5772$ver=$1;5773}5774$ver.='-'. git_get_short_hash($project,$hash);5775}5776# in case of hierarchical branch names5777$ver=~s!/!.!g;57785779# name = project-version_string5780$name="$name-$ver";57815782returnwantarray? ($name,$name) :$name;5783}57845785sub git_snapshot {5786my$format=$input_params{'snapshot_format'};5787if(!@snapshot_fmts) {5788 die_error(403,"Snapshots not allowed");5789}5790# default to first supported snapshot format5791$format||=$snapshot_fmts[0];5792if($format!~m/^[a-z0-9]+$/) {5793 die_error(400,"Invalid snapshot format parameter");5794}elsif(!exists($known_snapshot_formats{$format})) {5795 die_error(400,"Unknown snapshot format");5796}elsif($known_snapshot_formats{$format}{'disabled'}) {5797 die_error(403,"Snapshot format not allowed");5798}elsif(!grep($_eq$format,@snapshot_fmts)) {5799 die_error(403,"Unsupported snapshot format");5800}58015802my$type= git_get_type("$hash^{}");5803if(!$type) {5804 die_error(404,'Object does not exist');5805}elsif($typeeq'blob') {5806 die_error(400,'Object is not a tree-ish');5807}58085809my($name,$prefix) = snapshot_name($project,$hash);5810my$filename="$name$known_snapshot_formats{$format}{'suffix'}";5811my$cmd= quote_command(5812 git_cmd(),'archive',5813"--format=$known_snapshot_formats{$format}{'format'}",5814"--prefix=$prefix/",$hash);5815if(exists$known_snapshot_formats{$format}{'compressor'}) {5816$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});5817}58185819$filename=~s/(["\\])/\\$1/g;5820print$cgi->header(5821-type =>$known_snapshot_formats{$format}{'type'},5822-content_disposition =>'inline; filename="'.$filename.'"',5823-status =>'200 OK');58245825open my$fd,"-|",$cmd5826or die_error(500,"Execute git-archive failed");5827binmode STDOUT,':raw';5828print<$fd>;5829binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi5830close$fd;5831}58325833sub git_log_generic {5834my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;58355836my$head= git_get_head_hash($project);5837if(!defined$base) {5838$base=$head;5839}5840if(!defined$page) {5841$page=0;5842}5843my$refs= git_get_references();58445845my$commit_hash=$base;5846if(defined$parent) {5847$commit_hash="$parent..$base";5848}5849my@commitlist=5850 parse_commits($commit_hash,101, (100*$page),5851defined$file_name? ($file_name,"--full-history") : ());58525853my$ftype;5854if(!defined$file_hash&&defined$file_name) {5855# some commits could have deleted file in question,5856# and not have it in tree, but one of them has to have it5857for(my$i=0;$i<@commitlist;$i++) {5858$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);5859last ifdefined$file_hash;5860}5861}5862if(defined$file_hash) {5863$ftype= git_get_type($file_hash);5864}5865if(defined$file_name&& !defined$ftype) {5866 die_error(500,"Unknown type of object");5867}5868my%co;5869if(defined$file_name) {5870%co= parse_commit($base)5871or die_error(404,"Unknown commit object");5872}587358745875my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);5876my$next_link='';5877if($#commitlist>=100) {5878$next_link=5879$cgi->a({-href => href(-replay=>1, page=>$page+1),5880-accesskey =>"n", -title =>"Alt-n"},"next");5881}5882my$patch_max= gitweb_get_feature('patches');5883if($patch_max&& !defined$file_name) {5884if($patch_max<0||@commitlist<=$patch_max) {5885$paging_nav.=" ⋅ ".5886$cgi->a({-href => href(action=>"patches", -replay=>1)},5887"patches");5888}5889}58905891 git_header_html();5892 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);5893if(defined$file_name) {5894 git_print_header_div('commit', esc_html($co{'title'}),$base);5895}else{5896 git_print_header_div('summary',$project)5897}5898 git_print_page_path($file_name,$ftype,$hash_base)5899if(defined$file_name);59005901$body_subr->(\@commitlist,0,99,$refs,$next_link,5902$file_name,$file_hash,$ftype);59035904 git_footer_html();5905}59065907sub git_log {5908 git_log_generic('log', \&git_log_body,5909$hash,$hash_parent);5910}59115912sub git_commit {5913$hash||=$hash_base||"HEAD";5914my%co= parse_commit($hash)5915or die_error(404,"Unknown commit object");59165917my$parent=$co{'parent'};5918my$parents=$co{'parents'};# listref59195920# we need to prepare $formats_nav before any parameter munging5921my$formats_nav;5922if(!defined$parent) {5923# --root commitdiff5924$formats_nav.='(initial)';5925}elsif(@$parents==1) {5926# single parent commit5927$formats_nav.=5928'(parent: '.5929$cgi->a({-href => href(action=>"commit",5930 hash=>$parent)},5931 esc_html(substr($parent,0,7))) .5932')';5933}else{5934# merge commit5935$formats_nav.=5936'(merge: '.5937join(' ',map{5938$cgi->a({-href => href(action=>"commit",5939 hash=>$_)},5940 esc_html(substr($_,0,7)));5941}@$parents) .5942')';5943}5944if(gitweb_check_feature('patches') &&@$parents<=1) {5945$formats_nav.=" | ".5946$cgi->a({-href => href(action=>"patch", -replay=>1)},5947"patch");5948}59495950if(!defined$parent) {5951$parent="--root";5952}5953my@difftree;5954open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",5955@diff_opts,5956(@$parents<=1?$parent:'-c'),5957$hash,"--"5958or die_error(500,"Open git-diff-tree failed");5959@difftree=map{chomp;$_} <$fd>;5960close$fdor die_error(404,"Reading git-diff-tree failed");59615962# non-textual hash id's can be cached5963my$expires;5964if($hash=~m/^[0-9a-fA-F]{40}$/) {5965$expires="+1d";5966}5967my$refs= git_get_references();5968my$ref= format_ref_marker($refs,$co{'id'});59695970 git_header_html(undef,$expires);5971 git_print_page_nav('commit','',5972$hash,$co{'tree'},$hash,5973$formats_nav);59745975if(defined$co{'parent'}) {5976 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);5977}else{5978 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);5979}5980print"<div class=\"title_text\">\n".5981"<table class=\"object_header\">\n";5982 git_print_authorship_rows(\%co);5983print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";5984print"<tr>".5985"<td>tree</td>".5986"<td class=\"sha1\">".5987$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),5988class=>"list"},$co{'tree'}) .5989"</td>".5990"<td class=\"link\">".5991$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},5992"tree");5993my$snapshot_links= format_snapshot_links($hash);5994if(defined$snapshot_links) {5995print" | ".$snapshot_links;5996}5997print"</td>".5998"</tr>\n";59996000foreachmy$par(@$parents) {6001print"<tr>".6002"<td>parent</td>".6003"<td class=\"sha1\">".6004$cgi->a({-href => href(action=>"commit", hash=>$par),6005class=>"list"},$par) .6006"</td>".6007"<td class=\"link\">".6008$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .6009" | ".6010$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .6011"</td>".6012"</tr>\n";6013}6014print"</table>".6015"</div>\n";60166017print"<div class=\"page_body\">\n";6018 git_print_log($co{'comment'});6019print"</div>\n";60206021 git_difftree_body(\@difftree,$hash,@$parents);60226023 git_footer_html();6024}60256026sub git_object {6027# object is defined by:6028# - hash or hash_base alone6029# - hash_base and file_name6030my$type;60316032# - hash or hash_base alone6033if($hash|| ($hash_base&& !defined$file_name)) {6034my$object_id=$hash||$hash_base;60356036open my$fd,"-|", quote_command(6037 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'6038or die_error(404,"Object does not exist");6039$type= <$fd>;6040chomp$type;6041close$fd6042or die_error(404,"Object does not exist");60436044# - hash_base and file_name6045}elsif($hash_base&&defined$file_name) {6046$file_name=~ s,/+$,,;60476048system(git_cmd(),"cat-file",'-e',$hash_base) ==06049or die_error(404,"Base object does not exist");60506051# here errors should not hapen6052open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name6053or die_error(500,"Open git-ls-tree failed");6054my$line= <$fd>;6055close$fd;60566057#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'6058unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {6059 die_error(404,"File or directory for given base does not exist");6060}6061$type=$2;6062$hash=$3;6063}else{6064 die_error(400,"Not enough information to find object");6065}60666067print$cgi->redirect(-uri => href(action=>$type, -full=>1,6068 hash=>$hash, hash_base=>$hash_base,6069 file_name=>$file_name),6070-status =>'302 Found');6071}60726073sub git_blobdiff {6074my$format=shift||'html';60756076my$fd;6077my@difftree;6078my%diffinfo;6079my$expires;60806081# preparing $fd and %diffinfo for git_patchset_body6082# new style URI6083if(defined$hash_base&&defined$hash_parent_base) {6084if(defined$file_name) {6085# read raw output6086open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6087$hash_parent_base,$hash_base,6088"--", (defined$file_parent?$file_parent: ()),$file_name6089or die_error(500,"Open git-diff-tree failed");6090@difftree=map{chomp;$_} <$fd>;6091close$fd6092or die_error(404,"Reading git-diff-tree failed");6093@difftree6094or die_error(404,"Blob diff not found");60956096}elsif(defined$hash&&6097$hash=~/[0-9a-fA-F]{40}/) {6098# try to find filename from $hash60996100# read filtered raw output6101open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6102$hash_parent_base,$hash_base,"--"6103or die_error(500,"Open git-diff-tree failed");6104@difftree=6105# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'6106# $hash == to_id6107grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}6108map{chomp;$_} <$fd>;6109close$fd6110or die_error(404,"Reading git-diff-tree failed");6111@difftree6112or die_error(404,"Blob diff not found");61136114}else{6115 die_error(400,"Missing one of the blob diff parameters");6116}61176118if(@difftree>1) {6119 die_error(400,"Ambiguous blob diff specification");6120}61216122%diffinfo= parse_difftree_raw_line($difftree[0]);6123$file_parent||=$diffinfo{'from_file'} ||$file_name;6124$file_name||=$diffinfo{'to_file'};61256126$hash_parent||=$diffinfo{'from_id'};6127$hash||=$diffinfo{'to_id'};61286129# non-textual hash id's can be cached6130if($hash_base=~m/^[0-9a-fA-F]{40}$/&&6131$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {6132$expires='+1d';6133}61346135# open patch output6136open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6137'-p', ($formateq'html'?"--full-index": ()),6138$hash_parent_base,$hash_base,6139"--", (defined$file_parent?$file_parent: ()),$file_name6140or die_error(500,"Open git-diff-tree failed");6141}61426143# old/legacy style URI -- not generated anymore since 1.4.3.6144if(!%diffinfo) {6145 die_error('404 Not Found',"Missing one of the blob diff parameters")6146}61476148# header6149if($formateq'html') {6150my$formats_nav=6151$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},6152"raw");6153 git_header_html(undef,$expires);6154if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6155 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6156 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6157}else{6158print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";6159print"<div class=\"title\">$hashvs$hash_parent</div>\n";6160}6161if(defined$file_name) {6162 git_print_page_path($file_name,"blob",$hash_base);6163}else{6164print"<div class=\"page_path\"></div>\n";6165}61666167}elsif($formateq'plain') {6168print$cgi->header(6169-type =>'text/plain',6170-charset =>'utf-8',6171-expires =>$expires,6172-content_disposition =>'inline; filename="'."$file_name".'.patch"');61736174print"X-Git-Url: ".$cgi->self_url() ."\n\n";61756176}else{6177 die_error(400,"Unknown blobdiff format");6178}61796180# patch6181if($formateq'html') {6182print"<div class=\"page_body\">\n";61836184 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);6185close$fd;61866187print"</div>\n";# class="page_body"6188 git_footer_html();61896190}else{6191while(my$line= <$fd>) {6192$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;6193$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;61946195print$line;61966197last if$line=~m!^\+\+\+!;6198}6199local$/=undef;6200print<$fd>;6201close$fd;6202}6203}62046205sub git_blobdiff_plain {6206 git_blobdiff('plain');6207}62086209sub git_commitdiff {6210my%params=@_;6211my$format=$params{-format} ||'html';62126213my($patch_max) = gitweb_get_feature('patches');6214if($formateq'patch') {6215 die_error(403,"Patch view not allowed")unless$patch_max;6216}62176218$hash||=$hash_base||"HEAD";6219my%co= parse_commit($hash)6220or die_error(404,"Unknown commit object");62216222# choose format for commitdiff for merge6223if(!defined$hash_parent&& @{$co{'parents'}} >1) {6224$hash_parent='--cc';6225}6226# we need to prepare $formats_nav before almost any parameter munging6227my$formats_nav;6228if($formateq'html') {6229$formats_nav=6230$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},6231"raw");6232if($patch_max&& @{$co{'parents'}} <=1) {6233$formats_nav.=" | ".6234$cgi->a({-href => href(action=>"patch", -replay=>1)},6235"patch");6236}62376238if(defined$hash_parent&&6239$hash_parentne'-c'&&$hash_parentne'--cc') {6240# commitdiff with two commits given6241my$hash_parent_short=$hash_parent;6242if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {6243$hash_parent_short=substr($hash_parent,0,7);6244}6245$formats_nav.=6246' (from';6247for(my$i=0;$i< @{$co{'parents'}};$i++) {6248if($co{'parents'}[$i]eq$hash_parent) {6249$formats_nav.=' parent '. ($i+1);6250last;6251}6252}6253$formats_nav.=': '.6254$cgi->a({-href => href(action=>"commitdiff",6255 hash=>$hash_parent)},6256 esc_html($hash_parent_short)) .6257')';6258}elsif(!$co{'parent'}) {6259# --root commitdiff6260$formats_nav.=' (initial)';6261}elsif(scalar@{$co{'parents'}} ==1) {6262# single parent commit6263$formats_nav.=6264' (parent: '.6265$cgi->a({-href => href(action=>"commitdiff",6266 hash=>$co{'parent'})},6267 esc_html(substr($co{'parent'},0,7))) .6268')';6269}else{6270# merge commit6271if($hash_parenteq'--cc') {6272$formats_nav.=' | '.6273$cgi->a({-href => href(action=>"commitdiff",6274 hash=>$hash, hash_parent=>'-c')},6275'combined');6276}else{# $hash_parent eq '-c'6277$formats_nav.=' | '.6278$cgi->a({-href => href(action=>"commitdiff",6279 hash=>$hash, hash_parent=>'--cc')},6280'compact');6281}6282$formats_nav.=6283' (merge: '.6284join(' ',map{6285$cgi->a({-href => href(action=>"commitdiff",6286 hash=>$_)},6287 esc_html(substr($_,0,7)));6288} @{$co{'parents'}} ) .6289')';6290}6291}62926293my$hash_parent_param=$hash_parent;6294if(!defined$hash_parent_param) {6295# --cc for multiple parents, --root for parentless6296$hash_parent_param=6297@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';6298}62996300# read commitdiff6301my$fd;6302my@difftree;6303if($formateq'html') {6304open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6305"--no-commit-id","--patch-with-raw","--full-index",6306$hash_parent_param,$hash,"--"6307or die_error(500,"Open git-diff-tree failed");63086309while(my$line= <$fd>) {6310chomp$line;6311# empty line ends raw part of diff-tree output6312last unless$line;6313push@difftree,scalar parse_difftree_raw_line($line);6314}63156316}elsif($formateq'plain') {6317open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6318'-p',$hash_parent_param,$hash,"--"6319or die_error(500,"Open git-diff-tree failed");6320}elsif($formateq'patch') {6321# For commit ranges, we limit the output to the number of6322# patches specified in the 'patches' feature.6323# For single commits, we limit the output to a single patch,6324# diverging from the git-format-patch default.6325my@commit_spec= ();6326if($hash_parent) {6327if($patch_max>0) {6328push@commit_spec,"-$patch_max";6329}6330push@commit_spec,'-n',"$hash_parent..$hash";6331}else{6332if($params{-single}) {6333push@commit_spec,'-1';6334}else{6335if($patch_max>0) {6336push@commit_spec,"-$patch_max";6337}6338push@commit_spec,"-n";6339}6340push@commit_spec,'--root',$hash;6341}6342open$fd,"-|", git_cmd(),"format-patch",@diff_opts,6343'--encoding=utf8','--stdout',@commit_spec6344or die_error(500,"Open git-format-patch failed");6345}else{6346 die_error(400,"Unknown commitdiff format");6347}63486349# non-textual hash id's can be cached6350my$expires;6351if($hash=~m/^[0-9a-fA-F]{40}$/) {6352$expires="+1d";6353}63546355# write commit message6356if($formateq'html') {6357my$refs= git_get_references();6358my$ref= format_ref_marker($refs,$co{'id'});63596360 git_header_html(undef,$expires);6361 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);6362 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);6363print"<div class=\"title_text\">\n".6364"<table class=\"object_header\">\n";6365 git_print_authorship_rows(\%co);6366print"</table>".6367"</div>\n";6368print"<div class=\"page_body\">\n";6369if(@{$co{'comment'}} >1) {6370print"<div class=\"log\">\n";6371 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);6372print"</div>\n";# class="log"6373}63746375}elsif($formateq'plain') {6376my$refs= git_get_references("tags");6377my$tagname= git_get_rev_name_tags($hash);6378my$filename= basename($project) ."-$hash.patch";63796380print$cgi->header(6381-type =>'text/plain',6382-charset =>'utf-8',6383-expires =>$expires,6384-content_disposition =>'inline; filename="'."$filename".'"');6385my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});6386print"From: ". to_utf8($co{'author'}) ."\n";6387print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";6388print"Subject: ". to_utf8($co{'title'}) ."\n";63896390print"X-Git-Tag:$tagname\n"if$tagname;6391print"X-Git-Url: ".$cgi->self_url() ."\n\n";63926393foreachmy$line(@{$co{'comment'}}) {6394print to_utf8($line) ."\n";6395}6396print"---\n\n";6397}elsif($formateq'patch') {6398my$filename= basename($project) ."-$hash.patch";63996400print$cgi->header(6401-type =>'text/plain',6402-charset =>'utf-8',6403-expires =>$expires,6404-content_disposition =>'inline; filename="'."$filename".'"');6405}64066407# write patch6408if($formateq'html') {6409my$use_parents= !defined$hash_parent||6410$hash_parenteq'-c'||$hash_parenteq'--cc';6411 git_difftree_body(\@difftree,$hash,6412$use_parents? @{$co{'parents'}} :$hash_parent);6413print"<br/>\n";64146415 git_patchset_body($fd, \@difftree,$hash,6416$use_parents? @{$co{'parents'}} :$hash_parent);6417close$fd;6418print"</div>\n";# class="page_body"6419 git_footer_html();64206421}elsif($formateq'plain') {6422local$/=undef;6423print<$fd>;6424close$fd6425or print"Reading git-diff-tree failed\n";6426}elsif($formateq'patch') {6427local$/=undef;6428print<$fd>;6429close$fd6430or print"Reading git-format-patch failed\n";6431}6432}64336434sub git_commitdiff_plain {6435 git_commitdiff(-format =>'plain');6436}64376438# format-patch-style patches6439sub git_patch {6440 git_commitdiff(-format =>'patch', -single =>1);6441}64426443sub git_patches {6444 git_commitdiff(-format =>'patch');6445}64466447sub git_history {6448 git_log_generic('history', \&git_history_body,6449$hash_base,$hash_parent_base,6450$file_name,$hash);6451}64526453sub git_search {6454 gitweb_check_feature('search')or die_error(403,"Search is disabled");6455if(!defined$searchtext) {6456 die_error(400,"Text field is empty");6457}6458if(!defined$hash) {6459$hash= git_get_head_hash($project);6460}6461my%co= parse_commit($hash);6462if(!%co) {6463 die_error(404,"Unknown commit object");6464}6465if(!defined$page) {6466$page=0;6467}64686469$searchtype||='commit';6470if($searchtypeeq'pickaxe') {6471# pickaxe may take all resources of your box and run for several minutes6472# with every query - so decide by yourself how public you make this feature6473 gitweb_check_feature('pickaxe')6474or die_error(403,"Pickaxe is disabled");6475}6476if($searchtypeeq'grep') {6477 gitweb_check_feature('grep')6478or die_error(403,"Grep is disabled");6479}64806481 git_header_html();64826483if($searchtypeeq'commit'or$searchtypeeq'author'or$searchtypeeq'committer') {6484my$greptype;6485if($searchtypeeq'commit') {6486$greptype="--grep=";6487}elsif($searchtypeeq'author') {6488$greptype="--author=";6489}elsif($searchtypeeq'committer') {6490$greptype="--committer=";6491}6492$greptype.=$searchtext;6493my@commitlist= parse_commits($hash,101, (100*$page),undef,6494$greptype,'--regexp-ignore-case',6495$search_use_regexp?'--extended-regexp':'--fixed-strings');64966497my$paging_nav='';6498if($page>0) {6499$paging_nav.=6500$cgi->a({-href => href(action=>"search", hash=>$hash,6501 searchtext=>$searchtext,6502 searchtype=>$searchtype)},6503"first");6504$paging_nav.=" ⋅ ".6505$cgi->a({-href => href(-replay=>1, page=>$page-1),6506-accesskey =>"p", -title =>"Alt-p"},"prev");6507}else{6508$paging_nav.="first";6509$paging_nav.=" ⋅ prev";6510}6511my$next_link='';6512if($#commitlist>=100) {6513$next_link=6514$cgi->a({-href => href(-replay=>1, page=>$page+1),6515-accesskey =>"n", -title =>"Alt-n"},"next");6516$paging_nav.=" ⋅$next_link";6517}else{6518$paging_nav.=" ⋅ next";6519}65206521if($#commitlist>=100) {6522}65236524 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);6525 git_print_header_div('commit', esc_html($co{'title'}),$hash);6526 git_search_grep_body(\@commitlist,0,99,$next_link);6527}65286529if($searchtypeeq'pickaxe') {6530 git_print_page_nav('','',$hash,$co{'tree'},$hash);6531 git_print_header_div('commit', esc_html($co{'title'}),$hash);65326533print"<table class=\"pickaxe search\">\n";6534my$alternate=1;6535local$/="\n";6536open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,6537'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",6538($search_use_regexp?'--pickaxe-regex': ());6539undef%co;6540my@files;6541while(my$line= <$fd>) {6542chomp$line;6543next unless$line;65446545my%set= parse_difftree_raw_line($line);6546if(defined$set{'commit'}) {6547# finish previous commit6548if(%co) {6549print"</td>\n".6550"<td class=\"link\">".6551$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6552" | ".6553$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6554print"</td>\n".6555"</tr>\n";6556}65576558if($alternate) {6559print"<tr class=\"dark\">\n";6560}else{6561print"<tr class=\"light\">\n";6562}6563$alternate^=1;6564%co= parse_commit($set{'commit'});6565my$author= chop_and_escape_str($co{'author_name'},15,5);6566print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6567"<td><i>$author</i></td>\n".6568"<td>".6569$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6570-class=>"list subject"},6571 chop_and_escape_str($co{'title'},50) ."<br/>");6572}elsif(defined$set{'to_id'}) {6573next if($set{'to_id'} =~m/^0{40}$/);65746575print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},6576 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),6577-class=>"list"},6578"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .6579"<br/>\n";6580}6581}6582close$fd;65836584# finish last commit (warning: repetition!)6585if(%co) {6586print"</td>\n".6587"<td class=\"link\">".6588$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6589" | ".6590$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6591print"</td>\n".6592"</tr>\n";6593}65946595print"</table>\n";6596}65976598if($searchtypeeq'grep') {6599 git_print_page_nav('','',$hash,$co{'tree'},$hash);6600 git_print_header_div('commit', esc_html($co{'title'}),$hash);66016602print"<table class=\"grep_search\">\n";6603my$alternate=1;6604my$matches=0;6605local$/="\n";6606open my$fd,"-|", git_cmd(),'grep','-n',6607$search_use_regexp? ('-E','-i') :'-F',6608$searchtext,$co{'tree'};6609my$lastfile='';6610while(my$line= <$fd>) {6611chomp$line;6612my($file,$lno,$ltext,$binary);6613last if($matches++>1000);6614if($line=~/^Binary file (.+) matches$/) {6615$file=$1;6616$binary=1;6617}else{6618(undef,$file,$lno,$ltext) =split(/:/,$line,4);6619}6620if($filene$lastfile) {6621$lastfileand print"</td></tr>\n";6622if($alternate++) {6623print"<tr class=\"dark\">\n";6624}else{6625print"<tr class=\"light\">\n";6626}6627print"<td class=\"list\">".6628$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},6629 file_name=>"$file"),6630-class=>"list"}, esc_path($file));6631print"</td><td>\n";6632$lastfile=$file;6633}6634if($binary) {6635print"<div class=\"binary\">Binary file</div>\n";6636}else{6637$ltext= untabify($ltext);6638if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6639$ltext= esc_html($1, -nbsp=>1);6640$ltext.='<span class="match">';6641$ltext.= esc_html($2, -nbsp=>1);6642$ltext.='</span>';6643$ltext.= esc_html($3, -nbsp=>1);6644}else{6645$ltext= esc_html($ltext, -nbsp=>1);6646}6647print"<div class=\"pre\">".6648$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},6649 file_name=>"$file").'#l'.$lno,6650-class=>"linenr"},sprintf('%4i',$lno))6651.' '.$ltext."</div>\n";6652}6653}6654if($lastfile) {6655print"</td></tr>\n";6656if($matches>1000) {6657print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6658}6659}else{6660print"<div class=\"diff nodifferences\">No matches found</div>\n";6661}6662close$fd;66636664print"</table>\n";6665}6666 git_footer_html();6667}66686669sub git_search_help {6670 git_header_html();6671 git_print_page_nav('','',$hash,$hash,$hash);6672print<<EOT;6673<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without6674regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,6675the pattern entered is recognized as the POSIX extended6676<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case6677insensitive).</p>6678<dl>6679<dt><b>commit</b></dt>6680<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>6681EOT6682my$have_grep= gitweb_check_feature('grep');6683if($have_grep) {6684print<<EOT;6685<dt><b>grep</b></dt>6686<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing6687 a different one) are searched for the given pattern. On large trees, this search can take6688a while and put some strain on the server, so please use it with some consideration. Note that6689due to git-grep peculiarity, currently if regexp mode is turned off, the matches are6690case-sensitive.</dd>6691EOT6692}6693print<<EOT;6694<dt><b>author</b></dt>6695<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>6696<dt><b>committer</b></dt>6697<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>6698EOT6699my$have_pickaxe= gitweb_check_feature('pickaxe');6700if($have_pickaxe) {6701print<<EOT;6702<dt><b>pickaxe</b></dt>6703<dd>All commits that caused the string to appear or disappear from any file (changes that6704added, removed or "modified" the string) will be listed. This search can take a while and6705takes a lot of strain on the server, so please use it wisely. Note that since you may be6706interested even in changes just changing the case as well, this search is case sensitive.</dd>6707EOT6708}6709print"</dl>\n";6710 git_footer_html();6711}67126713sub git_shortlog {6714 git_log_generic('shortlog', \&git_shortlog_body,6715$hash,$hash_parent);6716}67176718## ......................................................................6719## feeds (RSS, Atom; OPML)67206721sub git_feed {6722my$format=shift||'atom';6723my$have_blame= gitweb_check_feature('blame');67246725# Atom: http://www.atomenabled.org/developers/syndication/6726# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ6727if($formatne'rss'&&$formatne'atom') {6728 die_error(400,"Unknown web feed format");6729}67306731# log/feed of current (HEAD) branch, log of given branch, history of file/directory6732my$head=$hash||'HEAD';6733my@commitlist= parse_commits($head,150,0,$file_name);67346735my%latest_commit;6736my%latest_date;6737my$content_type="application/$format+xml";6738if(defined$cgi->http('HTTP_ACCEPT') &&6739$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {6740# browser (feed reader) prefers text/xml6741$content_type='text/xml';6742}6743if(defined($commitlist[0])) {6744%latest_commit= %{$commitlist[0]};6745my$latest_epoch=$latest_commit{'committer_epoch'};6746%latest_date= parse_date($latest_epoch);6747my$if_modified=$cgi->http('IF_MODIFIED_SINCE');6748if(defined$if_modified) {6749my$since;6750if(eval{require HTTP::Date;1; }) {6751$since= HTTP::Date::str2time($if_modified);6752}elsif(eval{require Time::ParseDate;1; }) {6753$since= Time::ParseDate::parsedate($if_modified, GMT =>1);6754}6755if(defined$since&&$latest_epoch<=$since) {6756print$cgi->header(6757-type =>$content_type,6758-charset =>'utf-8',6759-last_modified =>$latest_date{'rfc2822'},6760-status =>'304 Not Modified');6761return;6762}6763}6764print$cgi->header(6765-type =>$content_type,6766-charset =>'utf-8',6767-last_modified =>$latest_date{'rfc2822'});6768}else{6769print$cgi->header(6770-type =>$content_type,6771-charset =>'utf-8');6772}67736774# Optimization: skip generating the body if client asks only6775# for Last-Modified date.6776return if($cgi->request_method()eq'HEAD');67776778# header variables6779my$title="$site_name-$project/$action";6780my$feed_type='log';6781if(defined$hash) {6782$title.=" - '$hash'";6783$feed_type='branch log';6784if(defined$file_name) {6785$title.=" ::$file_name";6786$feed_type='history';6787}6788}elsif(defined$file_name) {6789$title.=" -$file_name";6790$feed_type='history';6791}6792$title.="$feed_type";6793my$descr= git_get_project_description($project);6794if(defined$descr) {6795$descr= esc_html($descr);6796}else{6797$descr="$project".6798($formateq'rss'?'RSS':'Atom') .6799" feed";6800}6801my$owner= git_get_project_owner($project);6802$owner= esc_html($owner);68036804#header6805my$alt_url;6806if(defined$file_name) {6807$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);6808}elsif(defined$hash) {6809$alt_url= href(-full=>1, action=>"log", hash=>$hash);6810}else{6811$alt_url= href(-full=>1, action=>"summary");6812}6813print qq!<?xml version="1.0" encoding="utf-8"?>\n!;6814if($formateq'rss') {6815print<<XML;6816<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">6817<channel>6818XML6819print"<title>$title</title>\n".6820"<link>$alt_url</link>\n".6821"<description>$descr</description>\n".6822"<language>en</language>\n".6823# project owner is responsible for 'editorial' content6824"<managingEditor>$owner</managingEditor>\n";6825if(defined$logo||defined$favicon) {6826# prefer the logo to the favicon, since RSS6827# doesn't allow both6828my$img= esc_url($logo||$favicon);6829print"<image>\n".6830"<url>$img</url>\n".6831"<title>$title</title>\n".6832"<link>$alt_url</link>\n".6833"</image>\n";6834}6835if(%latest_date) {6836print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";6837print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";6838}6839print"<generator>gitweb v.$version/$git_version</generator>\n";6840}elsif($formateq'atom') {6841print<<XML;6842<feed xmlns="http://www.w3.org/2005/Atom">6843XML6844print"<title>$title</title>\n".6845"<subtitle>$descr</subtitle>\n".6846'<link rel="alternate" type="text/html" href="'.6847$alt_url.'" />'."\n".6848'<link rel="self" type="'.$content_type.'" href="'.6849$cgi->self_url() .'" />'."\n".6850"<id>". href(-full=>1) ."</id>\n".6851# use project owner for feed author6852"<author><name>$owner</name></author>\n";6853if(defined$favicon) {6854print"<icon>". esc_url($favicon) ."</icon>\n";6855}6856if(defined$logo_url) {6857# not twice as wide as tall: 72 x 27 pixels6858print"<logo>". esc_url($logo) ."</logo>\n";6859}6860if(!%latest_date) {6861# dummy date to keep the feed valid until commits trickle in:6862print"<updated>1970-01-01T00:00:00Z</updated>\n";6863}else{6864print"<updated>$latest_date{'iso-8601'}</updated>\n";6865}6866print"<generator version='$version/$git_version'>gitweb</generator>\n";6867}68686869# contents6870for(my$i=0;$i<=$#commitlist;$i++) {6871my%co= %{$commitlist[$i]};6872my$commit=$co{'id'};6873# we read 150, we always show 30 and the ones more recent than 48 hours6874if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {6875last;6876}6877my%cd= parse_date($co{'author_epoch'});68786879# get list of changed files6880open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6881$co{'parent'} ||"--root",6882$co{'id'},"--", (defined$file_name?$file_name: ())6883ornext;6884my@difftree=map{chomp;$_} <$fd>;6885close$fd6886ornext;68876888# print element (entry, item)6889my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);6890if($formateq'rss') {6891print"<item>\n".6892"<title>". esc_html($co{'title'}) ."</title>\n".6893"<author>". esc_html($co{'author'}) ."</author>\n".6894"<pubDate>$cd{'rfc2822'}</pubDate>\n".6895"<guid isPermaLink=\"true\">$co_url</guid>\n".6896"<link>$co_url</link>\n".6897"<description>". esc_html($co{'title'}) ."</description>\n".6898"<content:encoded>".6899"<![CDATA[\n";6900}elsif($formateq'atom') {6901print"<entry>\n".6902"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".6903"<updated>$cd{'iso-8601'}</updated>\n".6904"<author>\n".6905" <name>". esc_html($co{'author_name'}) ."</name>\n";6906if($co{'author_email'}) {6907print" <email>". esc_html($co{'author_email'}) ."</email>\n";6908}6909print"</author>\n".6910# use committer for contributor6911"<contributor>\n".6912" <name>". esc_html($co{'committer_name'}) ."</name>\n";6913if($co{'committer_email'}) {6914print" <email>". esc_html($co{'committer_email'}) ."</email>\n";6915}6916print"</contributor>\n".6917"<published>$cd{'iso-8601'}</published>\n".6918"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".6919"<id>$co_url</id>\n".6920"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".6921"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";6922}6923my$comment=$co{'comment'};6924print"<pre>\n";6925foreachmy$line(@$comment) {6926$line= esc_html($line);6927print"$line\n";6928}6929print"</pre><ul>\n";6930foreachmy$difftree_line(@difftree) {6931my%difftree= parse_difftree_raw_line($difftree_line);6932next if!$difftree{'from_id'};69336934my$file=$difftree{'file'} ||$difftree{'to_file'};69356936print"<li>".6937"[".6938$cgi->a({-href => href(-full=>1, action=>"blobdiff",6939 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},6940 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},6941 file_name=>$file, file_parent=>$difftree{'from_file'}),6942-title =>"diff"},'D');6943if($have_blame) {6944print$cgi->a({-href => href(-full=>1, action=>"blame",6945 file_name=>$file, hash_base=>$commit),6946-title =>"blame"},'B');6947}6948# if this is not a feed of a file history6949if(!defined$file_name||$file_namene$file) {6950print$cgi->a({-href => href(-full=>1, action=>"history",6951 file_name=>$file, hash=>$commit),6952-title =>"history"},'H');6953}6954$file= esc_path($file);6955print"] ".6956"$file</li>\n";6957}6958if($formateq'rss') {6959print"</ul>]]>\n".6960"</content:encoded>\n".6961"</item>\n";6962}elsif($formateq'atom') {6963print"</ul>\n</div>\n".6964"</content>\n".6965"</entry>\n";6966}6967}69686969# end of feed6970if($formateq'rss') {6971print"</channel>\n</rss>\n";6972}elsif($formateq'atom') {6973print"</feed>\n";6974}6975}69766977sub git_rss {6978 git_feed('rss');6979}69806981sub git_atom {6982 git_feed('atom');6983}69846985sub git_opml {6986my@list= git_get_projects_list();69876988print$cgi->header(6989-type =>'text/xml',6990-charset =>'utf-8',6991-content_disposition =>'inline; filename="opml.xml"');69926993print<<XML;6994<?xml version="1.0" encoding="utf-8"?>6995<opml version="1.0">6996<head>6997 <title>$site_nameOPML Export</title>6998</head>6999<body>7000<outline text="git RSS feeds">7001XML70027003foreachmy$pr(@list) {7004my%proj=%$pr;7005my$head= git_get_head_hash($proj{'path'});7006if(!defined$head) {7007next;7008}7009$git_dir="$projectroot/$proj{'path'}";7010my%co= parse_commit($head);7011if(!%co) {7012next;7013}70147015my$path= esc_html(chop_str($proj{'path'},25,5));7016my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);7017my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);7018print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";7019}7020print<<XML;7021</outline>7022</body>7023</opml>7024XML7025}