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# configuration for 'highlight' (http://www.andre-simon.de/) 236# match by basename 237our%highlight_basename= ( 238#'Program' => 'py', 239#'Library' => 'py', 240'SConstruct'=>'py',# SCons equivalent of Makefile 241'Makefile'=>'make', 242); 243# match by extension 244our%highlight_ext= ( 245# main extensions, defining name of syntax; 246# see files in /usr/share/highlight/langDefs/ directory 247map{$_=>$_} 248qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl), 249# alternate extensions, see /etc/highlight/filetypes.conf 250'h'=>'c', 251map{$_=>'cpp'}qw(cxx c++ cc), 252map{$_=>'php'}qw(php3 php4), 253map{$_=>'pl'}qw(perl pm),# perhaps also 'cgi' 254'mak'=>'make', 255map{$_=>'xml'}qw(xhtml html htm), 256); 257 258# You define site-wide feature defaults here; override them with 259# $GITWEB_CONFIG as necessary. 260our%feature= ( 261# feature => { 262# 'sub' => feature-sub (subroutine), 263# 'override' => allow-override (boolean), 264# 'default' => [ default options...] (array reference)} 265# 266# if feature is overridable (it means that allow-override has true value), 267# then feature-sub will be called with default options as parameters; 268# return value of feature-sub indicates if to enable specified feature 269# 270# if there is no 'sub' key (no feature-sub), then feature cannot be 271# overridden 272# 273# use gitweb_get_feature(<feature>) to retrieve the <feature> value 274# (an array) or gitweb_check_feature(<feature>) to check if <feature> 275# is enabled 276 277# Enable the 'blame' blob view, showing the last commit that modified 278# each line in the file. This can be very CPU-intensive. 279 280# To enable system wide have in $GITWEB_CONFIG 281# $feature{'blame'}{'default'} = [1]; 282# To have project specific config enable override in $GITWEB_CONFIG 283# $feature{'blame'}{'override'} = 1; 284# and in project config gitweb.blame = 0|1; 285'blame'=> { 286'sub'=>sub{ feature_bool('blame',@_) }, 287'override'=>0, 288'default'=> [0]}, 289 290# Enable the 'snapshot' link, providing a compressed archive of any 291# tree. This can potentially generate high traffic if you have large 292# project. 293 294# Value is a list of formats defined in %known_snapshot_formats that 295# you wish to offer. 296# To disable system wide have in $GITWEB_CONFIG 297# $feature{'snapshot'}{'default'} = []; 298# To have project specific config enable override in $GITWEB_CONFIG 299# $feature{'snapshot'}{'override'} = 1; 300# and in project config, a comma-separated list of formats or "none" 301# to disable. Example: gitweb.snapshot = tbz2,zip; 302'snapshot'=> { 303'sub'=> \&feature_snapshot, 304'override'=>0, 305'default'=> ['tgz']}, 306 307# Enable text search, which will list the commits which match author, 308# committer or commit text to a given string. Enabled by default. 309# Project specific override is not supported. 310'search'=> { 311'override'=>0, 312'default'=> [1]}, 313 314# Enable grep search, which will list the files in currently selected 315# tree containing the given string. Enabled by default. This can be 316# potentially CPU-intensive, of course. 317 318# To enable system wide have in $GITWEB_CONFIG 319# $feature{'grep'}{'default'} = [1]; 320# To have project specific config enable override in $GITWEB_CONFIG 321# $feature{'grep'}{'override'} = 1; 322# and in project config gitweb.grep = 0|1; 323'grep'=> { 324'sub'=>sub{ feature_bool('grep',@_) }, 325'override'=>0, 326'default'=> [1]}, 327 328# Enable the pickaxe search, which will list the commits that modified 329# a given string in a file. This can be practical and quite faster 330# alternative to 'blame', but still potentially CPU-intensive. 331 332# To enable system wide have in $GITWEB_CONFIG 333# $feature{'pickaxe'}{'default'} = [1]; 334# To have project specific config enable override in $GITWEB_CONFIG 335# $feature{'pickaxe'}{'override'} = 1; 336# and in project config gitweb.pickaxe = 0|1; 337'pickaxe'=> { 338'sub'=>sub{ feature_bool('pickaxe',@_) }, 339'override'=>0, 340'default'=> [1]}, 341 342# Enable showing size of blobs in a 'tree' view, in a separate 343# column, similar to what 'ls -l' does. This cost a bit of IO. 344 345# To disable system wide have in $GITWEB_CONFIG 346# $feature{'show-sizes'}{'default'} = [0]; 347# To have project specific config enable override in $GITWEB_CONFIG 348# $feature{'show-sizes'}{'override'} = 1; 349# and in project config gitweb.showsizes = 0|1; 350'show-sizes'=> { 351'sub'=>sub{ feature_bool('showsizes',@_) }, 352'override'=>0, 353'default'=> [1]}, 354 355# Make gitweb use an alternative format of the URLs which can be 356# more readable and natural-looking: project name is embedded 357# directly in the path and the query string contains other 358# auxiliary information. All gitweb installations recognize 359# URL in either format; this configures in which formats gitweb 360# generates links. 361 362# To enable system wide have in $GITWEB_CONFIG 363# $feature{'pathinfo'}{'default'} = [1]; 364# Project specific override is not supported. 365 366# Note that you will need to change the default location of CSS, 367# favicon, logo and possibly other files to an absolute URL. Also, 368# if gitweb.cgi serves as your indexfile, you will need to force 369# $my_uri to contain the script name in your $GITWEB_CONFIG. 370'pathinfo'=> { 371'override'=>0, 372'default'=> [0]}, 373 374# Make gitweb consider projects in project root subdirectories 375# to be forks of existing projects. Given project $projname.git, 376# projects matching $projname/*.git will not be shown in the main 377# projects list, instead a '+' mark will be added to $projname 378# there and a 'forks' view will be enabled for the project, listing 379# all the forks. If project list is taken from a file, forks have 380# to be listed after the main project. 381 382# To enable system wide have in $GITWEB_CONFIG 383# $feature{'forks'}{'default'} = [1]; 384# Project specific override is not supported. 385'forks'=> { 386'override'=>0, 387'default'=> [0]}, 388 389# Insert custom links to the action bar of all project pages. 390# This enables you mainly to link to third-party scripts integrating 391# into gitweb; e.g. git-browser for graphical history representation 392# or custom web-based repository administration interface. 393 394# The 'default' value consists of a list of triplets in the form 395# (label, link, position) where position is the label after which 396# to insert the link and link is a format string where %n expands 397# to the project name, %f to the project path within the filesystem, 398# %h to the current hash (h gitweb parameter) and %b to the current 399# hash base (hb gitweb parameter); %% expands to %. 400 401# To enable system wide have in $GITWEB_CONFIG e.g. 402# $feature{'actions'}{'default'} = [('graphiclog', 403# '/git-browser/by-commit.html?r=%n', 'summary')]; 404# Project specific override is not supported. 405'actions'=> { 406'override'=>0, 407'default'=> []}, 408 409# Allow gitweb scan project content tags described in ctags/ 410# of project repository, and display the popular Web 2.0-ish 411# "tag cloud" near the project list. Note that this is something 412# COMPLETELY different from the normal Git tags. 413 414# gitweb by itself can show existing tags, but it does not handle 415# tagging itself; you need an external application for that. 416# For an example script, check Girocco's cgi/tagproj.cgi. 417# You may want to install the HTML::TagCloud Perl module to get 418# a pretty tag cloud instead of just a list of tags. 419 420# To enable system wide have in $GITWEB_CONFIG 421# $feature{'ctags'}{'default'} = ['path_to_tag_script']; 422# Project specific override is not supported. 423'ctags'=> { 424'override'=>0, 425'default'=> [0]}, 426 427# The maximum number of patches in a patchset generated in patch 428# view. Set this to 0 or undef to disable patch view, or to a 429# negative number to remove any limit. 430 431# To disable system wide have in $GITWEB_CONFIG 432# $feature{'patches'}{'default'} = [0]; 433# To have project specific config enable override in $GITWEB_CONFIG 434# $feature{'patches'}{'override'} = 1; 435# and in project config gitweb.patches = 0|n; 436# where n is the maximum number of patches allowed in a patchset. 437'patches'=> { 438'sub'=> \&feature_patches, 439'override'=>0, 440'default'=> [16]}, 441 442# Avatar support. When this feature is enabled, views such as 443# shortlog or commit will display an avatar associated with 444# the email of the committer(s) and/or author(s). 445 446# Currently available providers are gravatar and picon. 447# If an unknown provider is specified, the feature is disabled. 448 449# Gravatar depends on Digest::MD5. 450# Picon currently relies on the indiana.edu database. 451 452# To enable system wide have in $GITWEB_CONFIG 453# $feature{'avatar'}{'default'} = ['<provider>']; 454# where <provider> is either gravatar or picon. 455# To have project specific config enable override in $GITWEB_CONFIG 456# $feature{'avatar'}{'override'} = 1; 457# and in project config gitweb.avatar = <provider>; 458'avatar'=> { 459'sub'=> \&feature_avatar, 460'override'=>0, 461'default'=> ['']}, 462 463# Enable displaying how much time and how many git commands 464# it took to generate and display page. Disabled by default. 465# Project specific override is not supported. 466'timed'=> { 467'override'=>0, 468'default'=> [0]}, 469 470# Enable turning some links into links to actions which require 471# JavaScript to run (like 'blame_incremental'). Not enabled by 472# default. Project specific override is currently not supported. 473'javascript-actions'=> { 474'override'=>0, 475'default'=> [0]}, 476 477# Syntax highlighting support. This is based on Daniel Svensson's 478# and Sham Chukoury's work in gitweb-xmms2.git. 479# It requires the 'highlight' program present in $PATH, 480# and therefore is disabled by default. 481 482# To enable system wide have in $GITWEB_CONFIG 483# $feature{'highlight'}{'default'} = [1]; 484 485'highlight'=> { 486'sub'=>sub{ feature_bool('highlight',@_) }, 487'override'=>0, 488'default'=> [0]}, 489); 490 491sub gitweb_get_feature { 492my($name) =@_; 493return unlessexists$feature{$name}; 494my($sub,$override,@defaults) = ( 495$feature{$name}{'sub'}, 496$feature{$name}{'override'}, 497@{$feature{$name}{'default'}}); 498# project specific override is possible only if we have project 499our$git_dir;# global variable, declared later 500if(!$override|| !defined$git_dir) { 501return@defaults; 502} 503if(!defined$sub) { 504warn"feature$nameis not overridable"; 505return@defaults; 506} 507return$sub->(@defaults); 508} 509 510# A wrapper to check if a given feature is enabled. 511# With this, you can say 512# 513# my $bool_feat = gitweb_check_feature('bool_feat'); 514# gitweb_check_feature('bool_feat') or somecode; 515# 516# instead of 517# 518# my ($bool_feat) = gitweb_get_feature('bool_feat'); 519# (gitweb_get_feature('bool_feat'))[0] or somecode; 520# 521sub gitweb_check_feature { 522return(gitweb_get_feature(@_))[0]; 523} 524 525 526sub feature_bool { 527my$key=shift; 528my($val) = git_get_project_config($key,'--bool'); 529 530if(!defined$val) { 531return($_[0]); 532}elsif($valeq'true') { 533return(1); 534}elsif($valeq'false') { 535return(0); 536} 537} 538 539sub feature_snapshot { 540my(@fmts) =@_; 541 542my($val) = git_get_project_config('snapshot'); 543 544if($val) { 545@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 546} 547 548return@fmts; 549} 550 551sub feature_patches { 552my@val= (git_get_project_config('patches','--int')); 553 554if(@val) { 555return@val; 556} 557 558return($_[0]); 559} 560 561sub feature_avatar { 562my@val= (git_get_project_config('avatar')); 563 564return@val?@val:@_; 565} 566 567# checking HEAD file with -e is fragile if the repository was 568# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 569# and then pruned. 570sub check_head_link { 571my($dir) =@_; 572my$headfile="$dir/HEAD"; 573return((-e $headfile) || 574(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 575} 576 577sub check_export_ok { 578my($dir) =@_; 579return(check_head_link($dir) && 580(!$export_ok|| -e "$dir/$export_ok") && 581(!$export_auth_hook||$export_auth_hook->($dir))); 582} 583 584# process alternate names for backward compatibility 585# filter out unsupported (unknown) snapshot formats 586sub filter_snapshot_fmts { 587my@fmts=@_; 588 589@fmts=map{ 590exists$known_snapshot_format_aliases{$_} ? 591$known_snapshot_format_aliases{$_} :$_}@fmts; 592@fmts=grep{ 593exists$known_snapshot_formats{$_} && 594!$known_snapshot_formats{$_}{'disabled'}}@fmts; 595} 596 597our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM); 598sub evaluate_gitweb_config { 599our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 600our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 601# die if there are errors parsing config file 602if(-e $GITWEB_CONFIG) { 603do$GITWEB_CONFIG; 604die$@if$@; 605}elsif(-e $GITWEB_CONFIG_SYSTEM) { 606do$GITWEB_CONFIG_SYSTEM; 607die$@if$@; 608} 609} 610 611# Get loadavg of system, to compare against $maxload. 612# Currently it requires '/proc/loadavg' present to get loadavg; 613# if it is not present it returns 0, which means no load checking. 614sub get_loadavg { 615if( -e '/proc/loadavg'){ 616open my$fd,'<','/proc/loadavg' 617orreturn0; 618my@load=split(/\s+/,scalar<$fd>); 619close$fd; 620 621# The first three columns measure CPU and IO utilization of the last one, 622# five, and 10 minute periods. The fourth column shows the number of 623# currently running processes and the total number of processes in the m/n 624# format. The last column displays the last process ID used. 625return$load[0] ||0; 626} 627# additional checks for load average should go here for things that don't export 628# /proc/loadavg 629 630return0; 631} 632 633# version of the core git binary 634our$git_version; 635sub evaluate_git_version { 636our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 637$number_of_git_cmds++; 638} 639 640sub check_loadavg { 641if(defined$maxload&& get_loadavg() >$maxload) { 642 die_error(503,"The load average on the server is too high"); 643} 644} 645 646# ====================================================================== 647# input validation and dispatch 648 649# input parameters can be collected from a variety of sources (presently, CGI 650# and PATH_INFO), so we define an %input_params hash that collects them all 651# together during validation: this allows subsequent uses (e.g. href()) to be 652# agnostic of the parameter origin 653 654our%input_params= (); 655 656# input parameters are stored with the long parameter name as key. This will 657# also be used in the href subroutine to convert parameters to their CGI 658# equivalent, and since the href() usage is the most frequent one, we store 659# the name -> CGI key mapping here, instead of the reverse. 660# 661# XXX: Warning: If you touch this, check the search form for updating, 662# too. 663 664our@cgi_param_mapping= ( 665 project =>"p", 666 action =>"a", 667 file_name =>"f", 668 file_parent =>"fp", 669 hash =>"h", 670 hash_parent =>"hp", 671 hash_base =>"hb", 672 hash_parent_base =>"hpb", 673 page =>"pg", 674 order =>"o", 675 searchtext =>"s", 676 searchtype =>"st", 677 snapshot_format =>"sf", 678 extra_options =>"opt", 679 search_use_regexp =>"sr", 680# this must be last entry (for manipulation from JavaScript) 681 javascript =>"js" 682); 683our%cgi_param_mapping=@cgi_param_mapping; 684 685# we will also need to know the possible actions, for validation 686our%actions= ( 687"blame"=> \&git_blame, 688"blame_incremental"=> \&git_blame_incremental, 689"blame_data"=> \&git_blame_data, 690"blobdiff"=> \&git_blobdiff, 691"blobdiff_plain"=> \&git_blobdiff_plain, 692"blob"=> \&git_blob, 693"blob_plain"=> \&git_blob_plain, 694"commitdiff"=> \&git_commitdiff, 695"commitdiff_plain"=> \&git_commitdiff_plain, 696"commit"=> \&git_commit, 697"forks"=> \&git_forks, 698"heads"=> \&git_heads, 699"history"=> \&git_history, 700"log"=> \&git_log, 701"patch"=> \&git_patch, 702"patches"=> \&git_patches, 703"rss"=> \&git_rss, 704"atom"=> \&git_atom, 705"search"=> \&git_search, 706"search_help"=> \&git_search_help, 707"shortlog"=> \&git_shortlog, 708"summary"=> \&git_summary, 709"tag"=> \&git_tag, 710"tags"=> \&git_tags, 711"tree"=> \&git_tree, 712"snapshot"=> \&git_snapshot, 713"object"=> \&git_object, 714# those below don't need $project 715"opml"=> \&git_opml, 716"project_list"=> \&git_project_list, 717"project_index"=> \&git_project_index, 718); 719 720# finally, we have the hash of allowed extra_options for the commands that 721# allow them 722our%allowed_options= ( 723"--no-merges"=> [qw(rss atom log shortlog history)], 724); 725 726# fill %input_params with the CGI parameters. All values except for 'opt' 727# should be single values, but opt can be an array. We should probably 728# build an array of parameters that can be multi-valued, but since for the time 729# being it's only this one, we just single it out 730sub evaluate_query_params { 731our$cgi; 732 733while(my($name,$symbol) =each%cgi_param_mapping) { 734if($symboleq'opt') { 735$input_params{$name} = [$cgi->param($symbol) ]; 736}else{ 737$input_params{$name} =$cgi->param($symbol); 738} 739} 740} 741 742# now read PATH_INFO and update the parameter list for missing parameters 743sub evaluate_path_info { 744return ifdefined$input_params{'project'}; 745return if!$path_info; 746$path_info=~ s,^/+,,; 747return if!$path_info; 748 749# find which part of PATH_INFO is project 750my$project=$path_info; 751$project=~ s,/+$,,; 752while($project&& !check_head_link("$projectroot/$project")) { 753$project=~ s,/*[^/]*$,,; 754} 755return unless$project; 756$input_params{'project'} =$project; 757 758# do not change any parameters if an action is given using the query string 759return if$input_params{'action'}; 760$path_info=~ s,^\Q$project\E/*,,; 761 762# next, check if we have an action 763my$action=$path_info; 764$action=~ s,/.*$,,; 765if(exists$actions{$action}) { 766$path_info=~ s,^$action/*,,; 767$input_params{'action'} =$action; 768} 769 770# list of actions that want hash_base instead of hash, but can have no 771# pathname (f) parameter 772my@wants_base= ( 773'tree', 774'history', 775); 776 777# we want to catch 778# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 779my($parentrefname,$parentpathname,$refname,$pathname) = 780($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/); 781 782# first, analyze the 'current' part 783if(defined$pathname) { 784# we got "branch:filename" or "branch:dir/" 785# we could use git_get_type(branch:pathname), but: 786# - it needs $git_dir 787# - it does a git() call 788# - the convention of terminating directories with a slash 789# makes it superfluous 790# - embedding the action in the PATH_INFO would make it even 791# more superfluous 792$pathname=~ s,^/+,,; 793if(!$pathname||substr($pathname, -1)eq"/") { 794$input_params{'action'} ||="tree"; 795$pathname=~ s,/$,,; 796}else{ 797# the default action depends on whether we had parent info 798# or not 799if($parentrefname) { 800$input_params{'action'} ||="blobdiff_plain"; 801}else{ 802$input_params{'action'} ||="blob_plain"; 803} 804} 805$input_params{'hash_base'} ||=$refname; 806$input_params{'file_name'} ||=$pathname; 807}elsif(defined$refname) { 808# we got "branch". In this case we have to choose if we have to 809# set hash or hash_base. 810# 811# Most of the actions without a pathname only want hash to be 812# set, except for the ones specified in @wants_base that want 813# hash_base instead. It should also be noted that hand-crafted 814# links having 'history' as an action and no pathname or hash 815# set will fail, but that happens regardless of PATH_INFO. 816$input_params{'action'} ||="shortlog"; 817if(grep{$_eq$input_params{'action'} }@wants_base) { 818$input_params{'hash_base'} ||=$refname; 819}else{ 820$input_params{'hash'} ||=$refname; 821} 822} 823 824# next, handle the 'parent' part, if present 825if(defined$parentrefname) { 826# a missing pathspec defaults to the 'current' filename, allowing e.g. 827# someproject/blobdiff/oldrev..newrev:/filename 828if($parentpathname) { 829$parentpathname=~ s,^/+,,; 830$parentpathname=~ s,/$,,; 831$input_params{'file_parent'} ||=$parentpathname; 832}else{ 833$input_params{'file_parent'} ||=$input_params{'file_name'}; 834} 835# we assume that hash_parent_base is wanted if a path was specified, 836# or if the action wants hash_base instead of hash 837if(defined$input_params{'file_parent'} || 838grep{$_eq$input_params{'action'} }@wants_base) { 839$input_params{'hash_parent_base'} ||=$parentrefname; 840}else{ 841$input_params{'hash_parent'} ||=$parentrefname; 842} 843} 844 845# for the snapshot action, we allow URLs in the form 846# $project/snapshot/$hash.ext 847# where .ext determines the snapshot and gets removed from the 848# passed $refname to provide the $hash. 849# 850# To be able to tell that $refname includes the format extension, we 851# require the following two conditions to be satisfied: 852# - the hash input parameter MUST have been set from the $refname part 853# of the URL (i.e. they must be equal) 854# - the snapshot format MUST NOT have been defined already (e.g. from 855# CGI parameter sf) 856# It's also useless to try any matching unless $refname has a dot, 857# so we check for that too 858if(defined$input_params{'action'} && 859$input_params{'action'}eq'snapshot'&& 860defined$refname&&index($refname,'.') != -1&& 861$refnameeq$input_params{'hash'} && 862!defined$input_params{'snapshot_format'}) { 863# We loop over the known snapshot formats, checking for 864# extensions. Allowed extensions are both the defined suffix 865# (which includes the initial dot already) and the snapshot 866# format key itself, with a prepended dot 867while(my($fmt,$opt) =each%known_snapshot_formats) { 868my$hash=$refname; 869unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 870next; 871} 872my$sfx=$1; 873# a valid suffix was found, so set the snapshot format 874# and reset the hash parameter 875$input_params{'snapshot_format'} =$fmt; 876$input_params{'hash'} =$hash; 877# we also set the format suffix to the one requested 878# in the URL: this way a request for e.g. .tgz returns 879# a .tgz instead of a .tar.gz 880$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 881last; 882} 883} 884} 885 886our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 887$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 888$searchtext,$search_regexp); 889sub evaluate_and_validate_params { 890our$action=$input_params{'action'}; 891if(defined$action) { 892if(!validate_action($action)) { 893 die_error(400,"Invalid action parameter"); 894} 895} 896 897# parameters which are pathnames 898our$project=$input_params{'project'}; 899if(defined$project) { 900if(!validate_project($project)) { 901undef$project; 902 die_error(404,"No such project"); 903} 904} 905 906our$file_name=$input_params{'file_name'}; 907if(defined$file_name) { 908if(!validate_pathname($file_name)) { 909 die_error(400,"Invalid file parameter"); 910} 911} 912 913our$file_parent=$input_params{'file_parent'}; 914if(defined$file_parent) { 915if(!validate_pathname($file_parent)) { 916 die_error(400,"Invalid file parent parameter"); 917} 918} 919 920# parameters which are refnames 921our$hash=$input_params{'hash'}; 922if(defined$hash) { 923if(!validate_refname($hash)) { 924 die_error(400,"Invalid hash parameter"); 925} 926} 927 928our$hash_parent=$input_params{'hash_parent'}; 929if(defined$hash_parent) { 930if(!validate_refname($hash_parent)) { 931 die_error(400,"Invalid hash parent parameter"); 932} 933} 934 935our$hash_base=$input_params{'hash_base'}; 936if(defined$hash_base) { 937if(!validate_refname($hash_base)) { 938 die_error(400,"Invalid hash base parameter"); 939} 940} 941 942our@extra_options= @{$input_params{'extra_options'}}; 943# @extra_options is always defined, since it can only be (currently) set from 944# CGI, and $cgi->param() returns the empty array in array context if the param 945# is not set 946foreachmy$opt(@extra_options) { 947if(not exists$allowed_options{$opt}) { 948 die_error(400,"Invalid option parameter"); 949} 950if(not grep(/^$action$/, @{$allowed_options{$opt}})) { 951 die_error(400,"Invalid option parameter for this action"); 952} 953} 954 955our$hash_parent_base=$input_params{'hash_parent_base'}; 956if(defined$hash_parent_base) { 957if(!validate_refname($hash_parent_base)) { 958 die_error(400,"Invalid hash parent base parameter"); 959} 960} 961 962# other parameters 963our$page=$input_params{'page'}; 964if(defined$page) { 965if($page=~m/[^0-9]/) { 966 die_error(400,"Invalid page parameter"); 967} 968} 969 970our$searchtype=$input_params{'searchtype'}; 971if(defined$searchtype) { 972if($searchtype=~m/[^a-z]/) { 973 die_error(400,"Invalid searchtype parameter"); 974} 975} 976 977our$search_use_regexp=$input_params{'search_use_regexp'}; 978 979our$searchtext=$input_params{'searchtext'}; 980our$search_regexp; 981if(defined$searchtext) { 982if(length($searchtext) <2) { 983 die_error(403,"At least two characters are required for search parameter"); 984} 985$search_regexp=$search_use_regexp?$searchtext:quotemeta$searchtext; 986} 987} 988 989# path to the current git repository 990our$git_dir; 991sub evaluate_git_dir { 992our$git_dir="$projectroot/$project"if$project; 993} 994 995our(@snapshot_fmts,$git_avatar); 996sub configure_gitweb_features { 997# list of supported snapshot formats 998our@snapshot_fmts= gitweb_get_feature('snapshot'); 999@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);10001001# check that the avatar feature is set to a known provider name,1002# and for each provider check if the dependencies are satisfied.1003# if the provider name is invalid or the dependencies are not met,1004# reset $git_avatar to the empty string.1005our($git_avatar) = gitweb_get_feature('avatar');1006if($git_avatareq'gravatar') {1007$git_avatar=''unless(eval{require Digest::MD5;1; });1008}elsif($git_avatareq'picon') {1009# no dependencies1010}else{1011$git_avatar='';1012}1013}10141015# custom error handler: 'die <message>' is Internal Server Error1016sub handle_errors_html {1017my$msg=shift;# it is already HTML escaped10181019# to avoid infinite loop where error occurs in die_error,1020# change handler to default handler, disabling handle_errors_html1021 set_message("Error occured when inside die_error:\n$msg");10221023# you cannot jump out of die_error when called as error handler;1024# the subroutine set via CGI::Carp::set_message is called _after_1025# HTTP headers are already written, so it cannot write them itself1026 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1027}1028set_message(\&handle_errors_html);10291030# dispatch1031sub dispatch {1032if(!defined$action) {1033if(defined$hash) {1034$action= git_get_type($hash);1035}elsif(defined$hash_base&&defined$file_name) {1036$action= git_get_type("$hash_base:$file_name");1037}elsif(defined$project) {1038$action='summary';1039}else{1040$action='project_list';1041}1042}1043if(!defined($actions{$action})) {1044 die_error(400,"Unknown action");1045}1046if($action!~m/^(?:opml|project_list|project_index)$/&&1047!$project) {1048 die_error(400,"Project needed");1049}1050$actions{$action}->();1051}10521053sub reset_timer {1054our$t0= [Time::HiRes::gettimeofday()]1055ifdefined$t0;1056our$number_of_git_cmds=0;1057}10581059sub run_request {1060 reset_timer();10611062 evaluate_uri();1063 evaluate_gitweb_config();1064 check_loadavg();10651066# $projectroot and $projects_list might be set in gitweb config file1067$projects_list||=$projectroot;10681069 evaluate_query_params();1070 evaluate_path_info();1071 evaluate_and_validate_params();1072 evaluate_git_dir();10731074 configure_gitweb_features();10751076 dispatch();1077}10781079our$is_last_request=sub{1};1080our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1081our$CGI='CGI';1082our$cgi;1083sub configure_as_fcgi {1084require CGI::Fast;1085our$CGI='CGI::Fast';10861087my$request_number=0;1088# let each child service 100 requests1089our$is_last_request=sub{ ++$request_number>100};1090}1091sub evaluate_argv {1092my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1093 configure_as_fcgi()1094if$script_name=~/\.fcgi$/;10951096return unless(@ARGV);10971098require Getopt::Long;1099 Getopt::Long::GetOptions(1100'fastcgi|fcgi|f'=> \&configure_as_fcgi,1101'nproc|n=i'=>sub{1102my($arg,$val) =@_;1103return unlesseval{require FCGI::ProcManager;1; };1104my$proc_manager= FCGI::ProcManager->new({1105 n_processes =>$val,1106});1107our$pre_listen_hook=sub{$proc_manager->pm_manage() };1108our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1109our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1110},1111);1112}11131114sub run {1115 evaluate_argv();1116 evaluate_git_version();11171118$pre_listen_hook->()1119if$pre_listen_hook;11201121 REQUEST:1122while($cgi=$CGI->new()) {1123$pre_dispatch_hook->()1124if$pre_dispatch_hook;11251126 run_request();11271128$post_dispatch_hook->()1129if$post_dispatch_hook;11301131last REQUEST if($is_last_request->());1132}11331134 DONE_GITWEB:11351;1136}11371138run();11391140if(defined caller) {1141# wrapped in a subroutine processing requests,1142# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1143return;1144}else{1145# pure CGI script, serving single request1146exit;1147}11481149## ======================================================================1150## action links11511152# possible values of extra options1153# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1154# -replay => 1 - start from a current view (replay with modifications)1155# -path_info => 0|1 - don't use/use path_info URL (if possible)1156sub href {1157my%params=@_;1158# default is to use -absolute url() i.e. $my_uri1159my$href=$params{-full} ?$my_url:$my_uri;11601161$params{'project'} =$projectunlessexists$params{'project'};11621163if($params{-replay}) {1164while(my($name,$symbol) =each%cgi_param_mapping) {1165if(!exists$params{$name}) {1166$params{$name} =$input_params{$name};1167}1168}1169}11701171my$use_pathinfo= gitweb_check_feature('pathinfo');1172if(defined$params{'project'} &&1173(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1174# try to put as many parameters as possible in PATH_INFO:1175# - project name1176# - action1177# - hash_parent or hash_parent_base:/file_parent1178# - hash or hash_base:/filename1179# - the snapshot_format as an appropriate suffix11801181# When the script is the root DirectoryIndex for the domain,1182# $href here would be something like http://gitweb.example.com/1183# Thus, we strip any trailing / from $href, to spare us double1184# slashes in the final URL1185$href=~ s,/$,,;11861187# Then add the project name, if present1188$href.="/".esc_url($params{'project'});1189delete$params{'project'};11901191# since we destructively absorb parameters, we keep this1192# boolean that remembers if we're handling a snapshot1193my$is_snapshot=$params{'action'}eq'snapshot';11941195# Summary just uses the project path URL, any other action is1196# added to the URL1197if(defined$params{'action'}) {1198$href.="/".esc_url($params{'action'})unless$params{'action'}eq'summary';1199delete$params{'action'};1200}12011202# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1203# stripping nonexistent or useless pieces1204$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1205||$params{'hash_parent'} ||$params{'hash'});1206if(defined$params{'hash_base'}) {1207if(defined$params{'hash_parent_base'}) {1208$href.= esc_url($params{'hash_parent_base'});1209# skip the file_parent if it's the same as the file_name1210if(defined$params{'file_parent'}) {1211if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1212delete$params{'file_parent'};1213}elsif($params{'file_parent'} !~/\.\./) {1214$href.=":/".esc_url($params{'file_parent'});1215delete$params{'file_parent'};1216}1217}1218$href.="..";1219delete$params{'hash_parent'};1220delete$params{'hash_parent_base'};1221}elsif(defined$params{'hash_parent'}) {1222$href.= esc_url($params{'hash_parent'})."..";1223delete$params{'hash_parent'};1224}12251226$href.= esc_url($params{'hash_base'});1227if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1228$href.=":/".esc_url($params{'file_name'});1229delete$params{'file_name'};1230}1231delete$params{'hash'};1232delete$params{'hash_base'};1233}elsif(defined$params{'hash'}) {1234$href.= esc_url($params{'hash'});1235delete$params{'hash'};1236}12371238# If the action was a snapshot, we can absorb the1239# snapshot_format parameter too1240if($is_snapshot) {1241my$fmt=$params{'snapshot_format'};1242# snapshot_format should always be defined when href()1243# is called, but just in case some code forgets, we1244# fall back to the default1245$fmt||=$snapshot_fmts[0];1246$href.=$known_snapshot_formats{$fmt}{'suffix'};1247delete$params{'snapshot_format'};1248}1249}12501251# now encode the parameters explicitly1252my@result= ();1253for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1254my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1255if(defined$params{$name}) {1256if(ref($params{$name})eq"ARRAY") {1257foreachmy$par(@{$params{$name}}) {1258push@result,$symbol."=". esc_param($par);1259}1260}else{1261push@result,$symbol."=". esc_param($params{$name});1262}1263}1264}1265$href.="?".join(';',@result)ifscalar@result;12661267return$href;1268}126912701271## ======================================================================1272## validation, quoting/unquoting and escaping12731274sub validate_action {1275my$input=shift||returnundef;1276returnundefunlessexists$actions{$input};1277return$input;1278}12791280sub validate_project {1281my$input=shift||returnundef;1282if(!validate_pathname($input) ||1283!(-d "$projectroot/$input") ||1284!check_export_ok("$projectroot/$input") ||1285($strict_export&& !project_in_list($input))) {1286returnundef;1287}else{1288return$input;1289}1290}12911292sub validate_pathname {1293my$input=shift||returnundef;12941295# no '.' or '..' as elements of path, i.e. no '.' nor '..'1296# at the beginning, at the end, and between slashes.1297# also this catches doubled slashes1298if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1299returnundef;1300}1301# no null characters1302if($input=~m!\0!) {1303returnundef;1304}1305return$input;1306}13071308sub validate_refname {1309my$input=shift||returnundef;13101311# textual hashes are O.K.1312if($input=~m/^[0-9a-fA-F]{40}$/) {1313return$input;1314}1315# it must be correct pathname1316$input= validate_pathname($input)1317orreturnundef;1318# restrictions on ref name according to git-check-ref-format1319if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1320returnundef;1321}1322return$input;1323}13241325# decode sequences of octets in utf8 into Perl's internal form,1326# which is utf-8 with utf8 flag set if needed. gitweb writes out1327# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1328sub to_utf8 {1329my$str=shift;1330returnundefunlessdefined$str;1331if(utf8::valid($str)) {1332 utf8::decode($str);1333return$str;1334}else{1335return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1336}1337}13381339# quote unsafe chars, but keep the slash, even when it's not1340# correct, but quoted slashes look too horrible in bookmarks1341sub esc_param {1342my$str=shift;1343returnundefunlessdefined$str;1344$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1345$str=~s/ /\+/g;1346return$str;1347}13481349# quote unsafe chars in whole URL, so some characters cannot be quoted1350sub esc_url {1351my$str=shift;1352returnundefunlessdefined$str;1353$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1354$str=~s/ /\+/g;1355return$str;1356}13571358# replace invalid utf8 character with SUBSTITUTION sequence1359sub esc_html {1360my$str=shift;1361my%opts=@_;13621363returnundefunlessdefined$str;13641365$str= to_utf8($str);1366$str=$cgi->escapeHTML($str);1367if($opts{'-nbsp'}) {1368$str=~s/ / /g;1369}1370$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1371return$str;1372}13731374# quote control characters and escape filename to HTML1375sub esc_path {1376my$str=shift;1377my%opts=@_;13781379returnundefunlessdefined$str;13801381$str= to_utf8($str);1382$str=$cgi->escapeHTML($str);1383if($opts{'-nbsp'}) {1384$str=~s/ / /g;1385}1386$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1387return$str;1388}13891390# Make control characters "printable", using character escape codes (CEC)1391sub quot_cec {1392my$cntrl=shift;1393my%opts=@_;1394my%es= (# character escape codes, aka escape sequences1395"\t"=>'\t',# tab (HT)1396"\n"=>'\n',# line feed (LF)1397"\r"=>'\r',# carrige return (CR)1398"\f"=>'\f',# form feed (FF)1399"\b"=>'\b',# backspace (BS)1400"\a"=>'\a',# alarm (bell) (BEL)1401"\e"=>'\e',# escape (ESC)1402"\013"=>'\v',# vertical tab (VT)1403"\000"=>'\0',# nul character (NUL)1404);1405my$chr= ( (exists$es{$cntrl})1406?$es{$cntrl}1407:sprintf('\%2x',ord($cntrl)) );1408if($opts{-nohtml}) {1409return$chr;1410}else{1411return"<span class=\"cntrl\">$chr</span>";1412}1413}14141415# Alternatively use unicode control pictures codepoints,1416# Unicode "printable representation" (PR)1417sub quot_upr {1418my$cntrl=shift;1419my%opts=@_;14201421my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1422if($opts{-nohtml}) {1423return$chr;1424}else{1425return"<span class=\"cntrl\">$chr</span>";1426}1427}14281429# git may return quoted and escaped filenames1430sub unquote {1431my$str=shift;14321433sub unq {1434my$seq=shift;1435my%es= (# character escape codes, aka escape sequences1436't'=>"\t",# tab (HT, TAB)1437'n'=>"\n",# newline (NL)1438'r'=>"\r",# return (CR)1439'f'=>"\f",# form feed (FF)1440'b'=>"\b",# backspace (BS)1441'a'=>"\a",# alarm (bell) (BEL)1442'e'=>"\e",# escape (ESC)1443'v'=>"\013",# vertical tab (VT)1444);14451446if($seq=~m/^[0-7]{1,3}$/) {1447# octal char sequence1448returnchr(oct($seq));1449}elsif(exists$es{$seq}) {1450# C escape sequence, aka character escape code1451return$es{$seq};1452}1453# quoted ordinary character1454return$seq;1455}14561457if($str=~m/^"(.*)"$/) {1458# needs unquoting1459$str=$1;1460$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1461}1462return$str;1463}14641465# escape tabs (convert tabs to spaces)1466sub untabify {1467my$line=shift;14681469while((my$pos=index($line,"\t")) != -1) {1470if(my$count= (8- ($pos%8))) {1471my$spaces=' ' x $count;1472$line=~s/\t/$spaces/;1473}1474}14751476return$line;1477}14781479sub project_in_list {1480my$project=shift;1481my@list= git_get_projects_list();1482return@list&&scalar(grep{$_->{'path'}eq$project}@list);1483}14841485## ----------------------------------------------------------------------1486## HTML aware string manipulation14871488# Try to chop given string on a word boundary between position1489# $len and $len+$add_len. If there is no word boundary there,1490# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1491# (marking chopped part) would be longer than given string.1492sub chop_str {1493my$str=shift;1494my$len=shift;1495my$add_len=shift||10;1496my$where=shift||'right';# 'left' | 'center' | 'right'14971498# Make sure perl knows it is utf8 encoded so we don't1499# cut in the middle of a utf8 multibyte char.1500$str= to_utf8($str);15011502# allow only $len chars, but don't cut a word if it would fit in $add_len1503# if it doesn't fit, cut it if it's still longer than the dots we would add1504# remove chopped character entities entirely15051506# when chopping in the middle, distribute $len into left and right part1507# return early if chopping wouldn't make string shorter1508if($whereeq'center') {1509return$strif($len+5>=length($str));# filler is length 51510$len=int($len/2);1511}else{1512return$strif($len+4>=length($str));# filler is length 41513}15141515# regexps: ending and beginning with word part up to $add_len1516my$endre=qr/.{$len}\w{0,$add_len}/;1517my$begre=qr/\w{0,$add_len}.{$len}/;15181519if($whereeq'left') {1520$str=~m/^(.*?)($begre)$/;1521my($lead,$body) = ($1,$2);1522if(length($lead) >4) {1523$lead=" ...";1524}1525return"$lead$body";15261527}elsif($whereeq'center') {1528$str=~m/^($endre)(.*)$/;1529my($left,$str) = ($1,$2);1530$str=~m/^(.*?)($begre)$/;1531my($mid,$right) = ($1,$2);1532if(length($mid) >5) {1533$mid=" ... ";1534}1535return"$left$mid$right";15361537}else{1538$str=~m/^($endre)(.*)$/;1539my$body=$1;1540my$tail=$2;1541if(length($tail) >4) {1542$tail="... ";1543}1544return"$body$tail";1545}1546}15471548# takes the same arguments as chop_str, but also wraps a <span> around the1549# result with a title attribute if it does get chopped. Additionally, the1550# string is HTML-escaped.1551sub chop_and_escape_str {1552my($str) =@_;15531554my$chopped= chop_str(@_);1555if($choppedeq$str) {1556return esc_html($chopped);1557}else{1558$str=~s/[[:cntrl:]]/?/g;1559return$cgi->span({-title=>$str}, esc_html($chopped));1560}1561}15621563## ----------------------------------------------------------------------1564## functions returning short strings15651566# CSS class for given age value (in seconds)1567sub age_class {1568my$age=shift;15691570if(!defined$age) {1571return"noage";1572}elsif($age<60*60*2) {1573return"age0";1574}elsif($age<60*60*24*2) {1575return"age1";1576}else{1577return"age2";1578}1579}15801581# convert age in seconds to "nn units ago" string1582sub age_string {1583my$age=shift;1584my$age_str;15851586if($age>60*60*24*365*2) {1587$age_str= (int$age/60/60/24/365);1588$age_str.=" years ago";1589}elsif($age>60*60*24*(365/12)*2) {1590$age_str=int$age/60/60/24/(365/12);1591$age_str.=" months ago";1592}elsif($age>60*60*24*7*2) {1593$age_str=int$age/60/60/24/7;1594$age_str.=" weeks ago";1595}elsif($age>60*60*24*2) {1596$age_str=int$age/60/60/24;1597$age_str.=" days ago";1598}elsif($age>60*60*2) {1599$age_str=int$age/60/60;1600$age_str.=" hours ago";1601}elsif($age>60*2) {1602$age_str=int$age/60;1603$age_str.=" min ago";1604}elsif($age>2) {1605$age_str=int$age;1606$age_str.=" sec ago";1607}else{1608$age_str.=" right now";1609}1610return$age_str;1611}16121613useconstant{1614 S_IFINVALID =>0030000,1615 S_IFGITLINK =>0160000,1616};16171618# submodule/subproject, a commit object reference1619sub S_ISGITLINK {1620my$mode=shift;16211622return(($mode& S_IFMT) == S_IFGITLINK)1623}16241625# convert file mode in octal to symbolic file mode string1626sub mode_str {1627my$mode=oct shift;16281629if(S_ISGITLINK($mode)) {1630return'm---------';1631}elsif(S_ISDIR($mode& S_IFMT)) {1632return'drwxr-xr-x';1633}elsif(S_ISLNK($mode)) {1634return'lrwxrwxrwx';1635}elsif(S_ISREG($mode)) {1636# git cares only about the executable bit1637if($mode& S_IXUSR) {1638return'-rwxr-xr-x';1639}else{1640return'-rw-r--r--';1641};1642}else{1643return'----------';1644}1645}16461647# convert file mode in octal to file type string1648sub file_type {1649my$mode=shift;16501651if($mode!~m/^[0-7]+$/) {1652return$mode;1653}else{1654$mode=oct$mode;1655}16561657if(S_ISGITLINK($mode)) {1658return"submodule";1659}elsif(S_ISDIR($mode& S_IFMT)) {1660return"directory";1661}elsif(S_ISLNK($mode)) {1662return"symlink";1663}elsif(S_ISREG($mode)) {1664return"file";1665}else{1666return"unknown";1667}1668}16691670# convert file mode in octal to file type description string1671sub file_type_long {1672my$mode=shift;16731674if($mode!~m/^[0-7]+$/) {1675return$mode;1676}else{1677$mode=oct$mode;1678}16791680if(S_ISGITLINK($mode)) {1681return"submodule";1682}elsif(S_ISDIR($mode& S_IFMT)) {1683return"directory";1684}elsif(S_ISLNK($mode)) {1685return"symlink";1686}elsif(S_ISREG($mode)) {1687if($mode& S_IXUSR) {1688return"executable";1689}else{1690return"file";1691};1692}else{1693return"unknown";1694}1695}169616971698## ----------------------------------------------------------------------1699## functions returning short HTML fragments, or transforming HTML fragments1700## which don't belong to other sections17011702# format line of commit message.1703sub format_log_line_html {1704my$line=shift;17051706$line= esc_html($line, -nbsp=>1);1707$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1708$cgi->a({-href => href(action=>"object", hash=>$1),1709-class=>"text"},$1);1710}eg;17111712return$line;1713}17141715# format marker of refs pointing to given object17161717# the destination action is chosen based on object type and current context:1718# - for annotated tags, we choose the tag view unless it's the current view1719# already, in which case we go to shortlog view1720# - for other refs, we keep the current view if we're in history, shortlog or1721# log view, and select shortlog otherwise1722sub format_ref_marker {1723my($refs,$id) =@_;1724my$markers='';17251726if(defined$refs->{$id}) {1727foreachmy$ref(@{$refs->{$id}}) {1728# this code exploits the fact that non-lightweight tags are the1729# only indirect objects, and that they are the only objects for which1730# we want to use tag instead of shortlog as action1731my($type,$name) =qw();1732my$indirect= ($ref=~s/\^\{\}$//);1733# e.g. tags/v2.6.11 or heads/next1734if($ref=~m!^(.*?)s?/(.*)$!) {1735$type=$1;1736$name=$2;1737}else{1738$type="ref";1739$name=$ref;1740}17411742my$class=$type;1743$class.=" indirect"if$indirect;17441745my$dest_action="shortlog";17461747if($indirect) {1748$dest_action="tag"unless$actioneq"tag";1749}elsif($action=~/^(history|(short)?log)$/) {1750$dest_action=$action;1751}17521753my$dest="";1754$dest.="refs/"unless$ref=~ m!^refs/!;1755$dest.=$ref;17561757my$link=$cgi->a({1758-href => href(1759 action=>$dest_action,1760 hash=>$dest1761)},$name);17621763$markers.=" <span class=\"$class\"title=\"$ref\">".1764$link."</span>";1765}1766}17671768if($markers) {1769return' <span class="refs">'.$markers.'</span>';1770}else{1771return"";1772}1773}17741775# format, perhaps shortened and with markers, title line1776sub format_subject_html {1777my($long,$short,$href,$extra) =@_;1778$extra=''unlessdefined($extra);17791780if(length($short) <length($long)) {1781$long=~s/[[:cntrl:]]/?/g;1782return$cgi->a({-href =>$href, -class=>"list subject",1783-title => to_utf8($long)},1784 esc_html($short)) .$extra;1785}else{1786return$cgi->a({-href =>$href, -class=>"list subject"},1787 esc_html($long)) .$extra;1788}1789}17901791# Rather than recomputing the url for an email multiple times, we cache it1792# after the first hit. This gives a visible benefit in views where the avatar1793# for the same email is used repeatedly (e.g. shortlog).1794# The cache is shared by all avatar engines (currently gravatar only), which1795# are free to use it as preferred. Since only one avatar engine is used for any1796# given page, there's no risk for cache conflicts.1797our%avatar_cache= ();17981799# Compute the picon url for a given email, by using the picon search service over at1800# http://www.cs.indiana.edu/picons/search.html1801sub picon_url {1802my$email=lc shift;1803if(!$avatar_cache{$email}) {1804my($user,$domain) =split('@',$email);1805$avatar_cache{$email} =1806"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1807"$domain/$user/".1808"users+domains+unknown/up/single";1809}1810return$avatar_cache{$email};1811}18121813# Compute the gravatar url for a given email, if it's not in the cache already.1814# Gravatar stores only the part of the URL before the size, since that's the1815# one computationally more expensive. This also allows reuse of the cache for1816# different sizes (for this particular engine).1817sub gravatar_url {1818my$email=lc shift;1819my$size=shift;1820$avatar_cache{$email} ||=1821"http://www.gravatar.com/avatar/".1822 Digest::MD5::md5_hex($email) ."?s=";1823return$avatar_cache{$email} .$size;1824}18251826# Insert an avatar for the given $email at the given $size if the feature1827# is enabled.1828sub git_get_avatar {1829my($email,%opts) =@_;1830my$pre_white= ($opts{-pad_before} ?" ":"");1831my$post_white= ($opts{-pad_after} ?" ":"");1832$opts{-size} ||='default';1833my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1834my$url="";1835if($git_avatareq'gravatar') {1836$url= gravatar_url($email,$size);1837}elsif($git_avatareq'picon') {1838$url= picon_url($email);1839}1840# Other providers can be added by extending the if chain, defining $url1841# as needed. If no variant puts something in $url, we assume avatars1842# are completely disabled/unavailable.1843if($url) {1844return$pre_white.1845"<img width=\"$size\"".1846"class=\"avatar\"".1847"src=\"$url\"".1848"alt=\"\"".1849"/>".$post_white;1850}else{1851return"";1852}1853}18541855sub format_search_author {1856my($author,$searchtype,$displaytext) =@_;1857my$have_search= gitweb_check_feature('search');18581859if($have_search) {1860my$performed="";1861if($searchtypeeq'author') {1862$performed="authored";1863}elsif($searchtypeeq'committer') {1864$performed="committed";1865}18661867return$cgi->a({-href => href(action=>"search", hash=>$hash,1868 searchtext=>$author,1869 searchtype=>$searchtype),class=>"list",1870 title=>"Search for commits$performedby$author"},1871$displaytext);18721873}else{1874return$displaytext;1875}1876}18771878# format the author name of the given commit with the given tag1879# the author name is chopped and escaped according to the other1880# optional parameters (see chop_str).1881sub format_author_html {1882my$tag=shift;1883my$co=shift;1884my$author= chop_and_escape_str($co->{'author_name'},@_);1885return"<$tagclass=\"author\">".1886 format_search_author($co->{'author_name'},"author",1887 git_get_avatar($co->{'author_email'}, -pad_after =>1) .1888$author) .1889"</$tag>";1890}18911892# format git diff header line, i.e. "diff --(git|combined|cc) ..."1893sub format_git_diff_header_line {1894my$line=shift;1895my$diffinfo=shift;1896my($from,$to) =@_;18971898if($diffinfo->{'nparents'}) {1899# combined diff1900$line=~s!^(diff (.*?) )"?.*$!$1!;1901if($to->{'href'}) {1902$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1903 esc_path($to->{'file'}));1904}else{# file was deleted (no href)1905$line.= esc_path($to->{'file'});1906}1907}else{1908# "ordinary" diff1909$line=~s!^(diff (.*?) )"?a/.*$!$1!;1910if($from->{'href'}) {1911$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},1912'a/'. esc_path($from->{'file'}));1913}else{# file was added (no href)1914$line.='a/'. esc_path($from->{'file'});1915}1916$line.=' ';1917if($to->{'href'}) {1918$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1919'b/'. esc_path($to->{'file'}));1920}else{# file was deleted1921$line.='b/'. esc_path($to->{'file'});1922}1923}19241925return"<div class=\"diff header\">$line</div>\n";1926}19271928# format extended diff header line, before patch itself1929sub format_extended_diff_header_line {1930my$line=shift;1931my$diffinfo=shift;1932my($from,$to) =@_;19331934# match <path>1935if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {1936$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},1937 esc_path($from->{'file'}));1938}1939if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {1940$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},1941 esc_path($to->{'file'}));1942}1943# match single <mode>1944if($line=~m/\s(\d{6})$/) {1945$line.='<span class="info"> ('.1946 file_type_long($1) .1947')</span>';1948}1949# match <hash>1950if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {1951# can match only for combined diff1952$line='index ';1953for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {1954if($from->{'href'}[$i]) {1955$line.=$cgi->a({-href=>$from->{'href'}[$i],1956-class=>"hash"},1957substr($diffinfo->{'from_id'}[$i],0,7));1958}else{1959$line.='0' x 7;1960}1961# separator1962$line.=','if($i<$diffinfo->{'nparents'} -1);1963}1964$line.='..';1965if($to->{'href'}) {1966$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},1967substr($diffinfo->{'to_id'},0,7));1968}else{1969$line.='0' x 7;1970}19711972}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {1973# can match only for ordinary diff1974my($from_link,$to_link);1975if($from->{'href'}) {1976$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},1977substr($diffinfo->{'from_id'},0,7));1978}else{1979$from_link='0' x 7;1980}1981if($to->{'href'}) {1982$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},1983substr($diffinfo->{'to_id'},0,7));1984}else{1985$to_link='0' x 7;1986}1987my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});1988$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;1989}19901991return$line."<br/>\n";1992}19931994# format from-file/to-file diff header1995sub format_diff_from_to_header {1996my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;1997my$line;1998my$result='';19992000$line=$from_line;2001#assert($line =~ m/^---/) if DEBUG;2002# no extra formatting for "^--- /dev/null"2003if(!$diffinfo->{'nparents'}) {2004# ordinary (single parent) diff2005if($line=~m!^--- "?a/!) {2006if($from->{'href'}) {2007$line='--- a/'.2008$cgi->a({-href=>$from->{'href'}, -class=>"path"},2009 esc_path($from->{'file'}));2010}else{2011$line='--- a/'.2012 esc_path($from->{'file'});2013}2014}2015$result.= qq!<div class="diff from_file">$line</div>\n!;20162017}else{2018# combined diff (merge commit)2019for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2020if($from->{'href'}[$i]) {2021$line='--- '.2022$cgi->a({-href=>href(action=>"blobdiff",2023 hash_parent=>$diffinfo->{'from_id'}[$i],2024 hash_parent_base=>$parents[$i],2025 file_parent=>$from->{'file'}[$i],2026 hash=>$diffinfo->{'to_id'},2027 hash_base=>$hash,2028 file_name=>$to->{'file'}),2029-class=>"path",2030-title=>"diff". ($i+1)},2031$i+1) .2032'/'.2033$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2034 esc_path($from->{'file'}[$i]));2035}else{2036$line='--- /dev/null';2037}2038$result.= qq!<div class="diff from_file">$line</div>\n!;2039}2040}20412042$line=$to_line;2043#assert($line =~ m/^\+\+\+/) if DEBUG;2044# no extra formatting for "^+++ /dev/null"2045if($line=~m!^\+\+\+ "?b/!) {2046if($to->{'href'}) {2047$line='+++ b/'.2048$cgi->a({-href=>$to->{'href'}, -class=>"path"},2049 esc_path($to->{'file'}));2050}else{2051$line='+++ b/'.2052 esc_path($to->{'file'});2053}2054}2055$result.= qq!<div class="diff to_file">$line</div>\n!;20562057return$result;2058}20592060# create note for patch simplified by combined diff2061sub format_diff_cc_simplified {2062my($diffinfo,@parents) =@_;2063my$result='';20642065$result.="<div class=\"diff header\">".2066"diff --cc ";2067if(!is_deleted($diffinfo)) {2068$result.=$cgi->a({-href => href(action=>"blob",2069 hash_base=>$hash,2070 hash=>$diffinfo->{'to_id'},2071 file_name=>$diffinfo->{'to_file'}),2072-class=>"path"},2073 esc_path($diffinfo->{'to_file'}));2074}else{2075$result.= esc_path($diffinfo->{'to_file'});2076}2077$result.="</div>\n".# class="diff header"2078"<div class=\"diff nodifferences\">".2079"Simple merge".2080"</div>\n";# class="diff nodifferences"20812082return$result;2083}20842085# format patch (diff) line (not to be used for diff headers)2086sub format_diff_line {2087my$line=shift;2088my($from,$to) =@_;2089my$diff_class="";20902091chomp$line;20922093if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2094# combined diff2095my$prefix=substr($line,0,scalar@{$from->{'href'}});2096if($line=~m/^\@{3}/) {2097$diff_class=" chunk_header";2098}elsif($line=~m/^\\/) {2099$diff_class=" incomplete";2100}elsif($prefix=~tr/+/+/) {2101$diff_class=" add";2102}elsif($prefix=~tr/-/-/) {2103$diff_class=" rem";2104}2105}else{2106# assume ordinary diff2107my$char=substr($line,0,1);2108if($chareq'+') {2109$diff_class=" add";2110}elsif($chareq'-') {2111$diff_class=" rem";2112}elsif($chareq'@') {2113$diff_class=" chunk_header";2114}elsif($chareq"\\") {2115$diff_class=" incomplete";2116}2117}2118$line= untabify($line);2119if($from&&$to&&$line=~m/^\@{2} /) {2120my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2121$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;21222123$from_lines=0unlessdefined$from_lines;2124$to_lines=0unlessdefined$to_lines;21252126if($from->{'href'}) {2127$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2128-class=>"list"},$from_text);2129}2130if($to->{'href'}) {2131$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2132-class=>"list"},$to_text);2133}2134$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2135"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2136return"<div class=\"diff$diff_class\">$line</div>\n";2137}elsif($from&&$to&&$line=~m/^\@{3}/) {2138my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2139my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);21402141@from_text=split(' ',$ranges);2142for(my$i=0;$i<@from_text; ++$i) {2143($from_start[$i],$from_nlines[$i]) =2144(split(',',substr($from_text[$i],1)),0);2145}21462147$to_text=pop@from_text;2148$to_start=pop@from_start;2149$to_nlines=pop@from_nlines;21502151$line="<span class=\"chunk_info\">$prefix";2152for(my$i=0;$i<@from_text; ++$i) {2153if($from->{'href'}[$i]) {2154$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2155-class=>"list"},$from_text[$i]);2156}else{2157$line.=$from_text[$i];2158}2159$line.=" ";2160}2161if($to->{'href'}) {2162$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2163-class=>"list"},$to_text);2164}else{2165$line.=$to_text;2166}2167$line.="$prefix</span>".2168"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2169return"<div class=\"diff$diff_class\">$line</div>\n";2170}2171return"<div class=\"diff$diff_class\">". esc_html($line, -nbsp=>1) ."</div>\n";2172}21732174# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2175# linked. Pass the hash of the tree/commit to snapshot.2176sub format_snapshot_links {2177my($hash) =@_;2178my$num_fmts=@snapshot_fmts;2179if($num_fmts>1) {2180# A parenthesized list of links bearing format names.2181# e.g. "snapshot (_tar.gz_ _zip_)"2182return"snapshot (".join(' ',map2183$cgi->a({2184-href => href(2185 action=>"snapshot",2186 hash=>$hash,2187 snapshot_format=>$_2188)2189},$known_snapshot_formats{$_}{'display'})2190,@snapshot_fmts) .")";2191}elsif($num_fmts==1) {2192# A single "snapshot" link whose tooltip bears the format name.2193# i.e. "_snapshot_"2194my($fmt) =@snapshot_fmts;2195return2196$cgi->a({2197-href => href(2198 action=>"snapshot",2199 hash=>$hash,2200 snapshot_format=>$fmt2201),2202-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2203},"snapshot");2204}else{# $num_fmts == 02205returnundef;2206}2207}22082209## ......................................................................2210## functions returning values to be passed, perhaps after some2211## transformation, to other functions; e.g. returning arguments to href()22122213# returns hash to be passed to href to generate gitweb URL2214# in -title key it returns description of link2215sub get_feed_info {2216my$format=shift||'Atom';2217my%res= (action =>lc($format));22182219# feed links are possible only for project views2220return unless(defined$project);2221# some views should link to OPML, or to generic project feed,2222# or don't have specific feed yet (so they should use generic)2223return if($action=~/^(?:tags|heads|forks|tag|search)$/x);22242225my$branch;2226# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2227# from tag links; this also makes possible to detect branch links2228if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2229(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2230$branch=$1;2231}2232# find log type for feed description (title)2233my$type='log';2234if(defined$file_name) {2235$type="history of$file_name";2236$type.="/"if($actioneq'tree');2237$type.=" on '$branch'"if(defined$branch);2238}else{2239$type="log of$branch"if(defined$branch);2240}22412242$res{-title} =$type;2243$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2244$res{'file_name'} =$file_name;22452246return%res;2247}22482249## ----------------------------------------------------------------------2250## git utility subroutines, invoking git commands22512252# returns path to the core git executable and the --git-dir parameter as list2253sub git_cmd {2254$number_of_git_cmds++;2255return$GIT,'--git-dir='.$git_dir;2256}22572258# quote the given arguments for passing them to the shell2259# quote_command("command", "arg 1", "arg with ' and ! characters")2260# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2261# Try to avoid using this function wherever possible.2262sub quote_command {2263returnjoin(' ',2264map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2265}22662267# get HEAD ref of given project as hash2268sub git_get_head_hash {2269return git_get_full_hash(shift,'HEAD');2270}22712272sub git_get_full_hash {2273return git_get_hash(@_);2274}22752276sub git_get_short_hash {2277return git_get_hash(@_,'--short=7');2278}22792280sub git_get_hash {2281my($project,$hash,@options) =@_;2282my$o_git_dir=$git_dir;2283my$retval=undef;2284$git_dir="$projectroot/$project";2285if(open my$fd,'-|', git_cmd(),'rev-parse',2286'--verify','-q',@options,$hash) {2287$retval= <$fd>;2288chomp$retvalifdefined$retval;2289close$fd;2290}2291if(defined$o_git_dir) {2292$git_dir=$o_git_dir;2293}2294return$retval;2295}22962297# get type of given object2298sub git_get_type {2299my$hash=shift;23002301open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2302my$type= <$fd>;2303close$fdorreturn;2304chomp$type;2305return$type;2306}23072308# repository configuration2309our$config_file='';2310our%config;23112312# store multiple values for single key as anonymous array reference2313# single values stored directly in the hash, not as [ <value> ]2314sub hash_set_multi {2315my($hash,$key,$value) =@_;23162317if(!exists$hash->{$key}) {2318$hash->{$key} =$value;2319}elsif(!ref$hash->{$key}) {2320$hash->{$key} = [$hash->{$key},$value];2321}else{2322push@{$hash->{$key}},$value;2323}2324}23252326# return hash of git project configuration2327# optionally limited to some section, e.g. 'gitweb'2328sub git_parse_project_config {2329my$section_regexp=shift;2330my%config;23312332local$/="\0";23332334open my$fh,"-|", git_cmd(),"config",'-z','-l',2335orreturn;23362337while(my$keyval= <$fh>) {2338chomp$keyval;2339my($key,$value) =split(/\n/,$keyval,2);23402341 hash_set_multi(\%config,$key,$value)2342if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2343}2344close$fh;23452346return%config;2347}23482349# convert config value to boolean: 'true' or 'false'2350# no value, number > 0, 'true' and 'yes' values are true2351# rest of values are treated as false (never as error)2352sub config_to_bool {2353my$val=shift;23542355return1if!defined$val;# section.key23562357# strip leading and trailing whitespace2358$val=~s/^\s+//;2359$val=~s/\s+$//;23602361return(($val=~/^\d+$/&&$val) ||# section.key = 12362($val=~/^(?:true|yes)$/i));# section.key = true2363}23642365# convert config value to simple decimal number2366# an optional value suffix of 'k', 'm', or 'g' will cause the value2367# to be multiplied by 1024, 1048576, or 10737418242368sub config_to_int {2369my$val=shift;23702371# strip leading and trailing whitespace2372$val=~s/^\s+//;2373$val=~s/\s+$//;23742375if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2376$unit=lc($unit);2377# unknown unit is treated as 12378return$num* ($uniteq'g'?1073741824:2379$uniteq'm'?1048576:2380$uniteq'k'?1024:1);2381}2382return$val;2383}23842385# convert config value to array reference, if needed2386sub config_to_multi {2387my$val=shift;23882389returnref($val) ?$val: (defined($val) ? [$val] : []);2390}23912392sub git_get_project_config {2393my($key,$type) =@_;23942395return unlessdefined$git_dir;23962397# key sanity check2398return unless($key);2399$key=~s/^gitweb\.//;2400return if($key=~m/\W/);24012402# type sanity check2403if(defined$type) {2404$type=~s/^--//;2405$type=undef2406unless($typeeq'bool'||$typeeq'int');2407}24082409# get config2410if(!defined$config_file||2411$config_filene"$git_dir/config") {2412%config= git_parse_project_config('gitweb');2413$config_file="$git_dir/config";2414}24152416# check if config variable (key) exists2417return unlessexists$config{"gitweb.$key"};24182419# ensure given type2420if(!defined$type) {2421return$config{"gitweb.$key"};2422}elsif($typeeq'bool') {2423# backward compatibility: 'git config --bool' returns true/false2424return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2425}elsif($typeeq'int') {2426return config_to_int($config{"gitweb.$key"});2427}2428return$config{"gitweb.$key"};2429}24302431# get hash of given path at given ref2432sub git_get_hash_by_path {2433my$base=shift;2434my$path=shift||returnundef;2435my$type=shift;24362437$path=~ s,/+$,,;24382439open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2440or die_error(500,"Open git-ls-tree failed");2441my$line= <$fd>;2442close$fdorreturnundef;24432444if(!defined$line) {2445# there is no tree or hash given by $path at $base2446returnundef;2447}24482449#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2450$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2451if(defined$type&&$typene$2) {2452# type doesn't match2453returnundef;2454}2455return$3;2456}24572458# get path of entry with given hash at given tree-ish (ref)2459# used to get 'from' filename for combined diff (merge commit) for renames2460sub git_get_path_by_hash {2461my$base=shift||return;2462my$hash=shift||return;24632464local$/="\0";24652466open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2467orreturnundef;2468while(my$line= <$fd>) {2469chomp$line;24702471#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2472#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2473if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2474close$fd;2475return$1;2476}2477}2478close$fd;2479returnundef;2480}24812482## ......................................................................2483## git utility functions, directly accessing git repository24842485sub git_get_project_description {2486my$path=shift;24872488$git_dir="$projectroot/$path";2489open my$fd,'<',"$git_dir/description"2490orreturn git_get_project_config('description');2491my$descr= <$fd>;2492close$fd;2493if(defined$descr) {2494chomp$descr;2495}2496return$descr;2497}24982499sub git_get_project_ctags {2500my$path=shift;2501my$ctags= {};25022503$git_dir="$projectroot/$path";2504opendir my$dh,"$git_dir/ctags"2505orreturn$ctags;2506foreach(grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh)) {2507open my$ct,'<',$_ornext;2508my$val= <$ct>;2509chomp$val;2510close$ct;2511my$ctag=$_;$ctag=~ s#.*/##;2512$ctags->{$ctag} =$val;2513}2514closedir$dh;2515$ctags;2516}25172518sub git_populate_project_tagcloud {2519my$ctags=shift;25202521# First, merge different-cased tags; tags vote on casing2522my%ctags_lc;2523foreach(keys%$ctags) {2524$ctags_lc{lc$_}->{count} +=$ctags->{$_};2525if(not$ctags_lc{lc$_}->{topcount}2526or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2527$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2528$ctags_lc{lc$_}->{topname} =$_;2529}2530}25312532my$cloud;2533if(eval{require HTML::TagCloud;1; }) {2534$cloud= HTML::TagCloud->new;2535foreach(sort keys%ctags_lc) {2536# Pad the title with spaces so that the cloud looks2537# less crammed.2538my$title=$ctags_lc{$_}->{topname};2539$title=~s/ / /g;2540$title=~s/^/ /g;2541$title=~s/$/ /g;2542$cloud->add($title,$home_link."?by_tag=".$_,$ctags_lc{$_}->{count});2543}2544}else{2545$cloud= \%ctags_lc;2546}2547$cloud;2548}25492550sub git_show_project_tagcloud {2551my($cloud,$count) =@_;2552print STDERR ref($cloud)."..\n";2553if(ref$cloudeq'HTML::TagCloud') {2554return$cloud->html_and_css($count);2555}else{2556my@tags=sort{$cloud->{$a}->{count} <=>$cloud->{$b}->{count} }keys%$cloud;2557return'<p align="center">'.join(', ',map{2558"<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"2559}splice(@tags,0,$count)) .'</p>';2560}2561}25622563sub git_get_project_url_list {2564my$path=shift;25652566$git_dir="$projectroot/$path";2567open my$fd,'<',"$git_dir/cloneurl"2568orreturnwantarray?2569@{ config_to_multi(git_get_project_config('url')) } :2570 config_to_multi(git_get_project_config('url'));2571my@git_project_url_list=map{chomp;$_} <$fd>;2572close$fd;25732574returnwantarray?@git_project_url_list: \@git_project_url_list;2575}25762577sub git_get_projects_list {2578my($filter) =@_;2579my@list;25802581$filter||='';2582$filter=~s/\.git$//;25832584my$check_forks= gitweb_check_feature('forks');25852586if(-d $projects_list) {2587# search in directory2588my$dir=$projects_list. ($filter?"/$filter":'');2589# remove the trailing "/"2590$dir=~s!/+$!!;2591my$pfxlen=length("$dir");2592my$pfxdepth= ($dir=~tr!/!!);25932594 File::Find::find({2595 follow_fast =>1,# follow symbolic links2596 follow_skip =>2,# ignore duplicates2597 dangling_symlinks =>0,# ignore dangling symlinks, silently2598 wanted =>sub{2599# global variables2600our$project_maxdepth;2601our$projectroot;2602# skip project-list toplevel, if we get it.2603return if(m!^[/.]$!);2604# only directories can be git repositories2605return unless(-d $_);2606# don't traverse too deep (Find is super slow on os x)2607if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2608$File::Find::prune =1;2609return;2610}26112612my$subdir=substr($File::Find::name,$pfxlen+1);2613# we check related file in $projectroot2614my$path= ($filter?"$filter/":'') .$subdir;2615if(check_export_ok("$projectroot/$path")) {2616push@list, { path =>$path};2617$File::Find::prune =1;2618}2619},2620},"$dir");26212622}elsif(-f $projects_list) {2623# read from file(url-encoded):2624# 'git%2Fgit.git Linus+Torvalds'2625# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2626# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2627my%paths;2628open my$fd,'<',$projects_listorreturn;2629 PROJECT:2630while(my$line= <$fd>) {2631chomp$line;2632my($path,$owner) =split' ',$line;2633$path= unescape($path);2634$owner= unescape($owner);2635if(!defined$path) {2636next;2637}2638if($filterne'') {2639# looking for forks;2640my$pfx=substr($path,0,length($filter));2641if($pfxne$filter) {2642next PROJECT;2643}2644my$sfx=substr($path,length($filter));2645if($sfx!~/^\/.*\.git$/) {2646next PROJECT;2647}2648}elsif($check_forks) {2649 PATH:2650foreachmy$filter(keys%paths) {2651# looking for forks;2652my$pfx=substr($path,0,length($filter));2653if($pfxne$filter) {2654next PATH;2655}2656my$sfx=substr($path,length($filter));2657if($sfx!~/^\/.*\.git$/) {2658next PATH;2659}2660# is a fork, don't include it in2661# the list2662next PROJECT;2663}2664}2665if(check_export_ok("$projectroot/$path")) {2666my$pr= {2667 path =>$path,2668 owner => to_utf8($owner),2669};2670push@list,$pr;2671(my$forks_path=$path) =~s/\.git$//;2672$paths{$forks_path}++;2673}2674}2675close$fd;2676}2677return@list;2678}26792680our$gitweb_project_owner=undef;2681sub git_get_project_list_from_file {26822683return if(defined$gitweb_project_owner);26842685$gitweb_project_owner= {};2686# read from file (url-encoded):2687# 'git%2Fgit.git Linus+Torvalds'2688# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2689# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2690if(-f $projects_list) {2691open(my$fd,'<',$projects_list);2692while(my$line= <$fd>) {2693chomp$line;2694my($pr,$ow) =split' ',$line;2695$pr= unescape($pr);2696$ow= unescape($ow);2697$gitweb_project_owner->{$pr} = to_utf8($ow);2698}2699close$fd;2700}2701}27022703sub git_get_project_owner {2704my$project=shift;2705my$owner;27062707returnundefunless$project;2708$git_dir="$projectroot/$project";27092710if(!defined$gitweb_project_owner) {2711 git_get_project_list_from_file();2712}27132714if(exists$gitweb_project_owner->{$project}) {2715$owner=$gitweb_project_owner->{$project};2716}2717if(!defined$owner){2718$owner= git_get_project_config('owner');2719}2720if(!defined$owner) {2721$owner= get_file_owner("$git_dir");2722}27232724return$owner;2725}27262727sub git_get_last_activity {2728my($path) =@_;2729my$fd;27302731$git_dir="$projectroot/$path";2732open($fd,"-|", git_cmd(),'for-each-ref',2733'--format=%(committer)',2734'--sort=-committerdate',2735'--count=1',2736'refs/heads')orreturn;2737my$most_recent= <$fd>;2738close$fdorreturn;2739if(defined$most_recent&&2740$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {2741my$timestamp=$1;2742my$age=time-$timestamp;2743return($age, age_string($age));2744}2745return(undef,undef);2746}27472748sub git_get_references {2749my$type=shift||"";2750my%refs;2751# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.112752# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}2753open my$fd,"-|", git_cmd(),"show-ref","--dereference",2754($type? ("--","refs/$type") : ())# use -- <pattern> if $type2755orreturn;27562757while(my$line= <$fd>) {2758chomp$line;2759if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {2760if(defined$refs{$1}) {2761push@{$refs{$1}},$2;2762}else{2763$refs{$1} = [$2];2764}2765}2766}2767close$fdorreturn;2768return \%refs;2769}27702771sub git_get_rev_name_tags {2772my$hash=shift||returnundef;27732774open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash2775orreturn;2776my$name_rev= <$fd>;2777close$fd;27782779if($name_rev=~ m|^$hash tags/(.*)$|) {2780return$1;2781}else{2782# catches also '$hash undefined' output2783returnundef;2784}2785}27862787## ----------------------------------------------------------------------2788## parse to hash functions27892790sub parse_date {2791my$epoch=shift;2792my$tz=shift||"-0000";27932794my%date;2795my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");2796my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");2797my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);2798$date{'hour'} =$hour;2799$date{'minute'} =$min;2800$date{'mday'} =$mday;2801$date{'day'} =$days[$wday];2802$date{'month'} =$months[$mon];2803$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",2804$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;2805$date{'mday-time'} =sprintf"%d%s%02d:%02d",2806$mday,$months[$mon],$hour,$min;2807$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",28081900+$year,1+$mon,$mday,$hour,$min,$sec;28092810$tz=~m/^([+\-][0-9][0-9])([0-9][0-9])$/;2811my$local=$epoch+ ((int$1+ ($2/60)) *3600);2812($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);2813$date{'hour_local'} =$hour;2814$date{'minute_local'} =$min;2815$date{'tz_local'} =$tz;2816$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",28171900+$year,$mon+1,$mday,2818$hour,$min,$sec,$tz);2819return%date;2820}28212822sub parse_tag {2823my$tag_id=shift;2824my%tag;2825my@comment;28262827open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;2828$tag{'id'} =$tag_id;2829while(my$line= <$fd>) {2830chomp$line;2831if($line=~m/^object ([0-9a-fA-F]{40})$/) {2832$tag{'object'} =$1;2833}elsif($line=~m/^type (.+)$/) {2834$tag{'type'} =$1;2835}elsif($line=~m/^tag (.+)$/) {2836$tag{'name'} =$1;2837}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {2838$tag{'author'} =$1;2839$tag{'author_epoch'} =$2;2840$tag{'author_tz'} =$3;2841if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {2842$tag{'author_name'} =$1;2843$tag{'author_email'} =$2;2844}else{2845$tag{'author_name'} =$tag{'author'};2846}2847}elsif($line=~m/--BEGIN/) {2848push@comment,$line;2849last;2850}elsif($lineeq"") {2851last;2852}2853}2854push@comment, <$fd>;2855$tag{'comment'} = \@comment;2856close$fdorreturn;2857if(!defined$tag{'name'}) {2858return2859};2860return%tag2861}28622863sub parse_commit_text {2864my($commit_text,$withparents) =@_;2865my@commit_lines=split'\n',$commit_text;2866my%co;28672868pop@commit_lines;# Remove '\0'28692870if(!@commit_lines) {2871return;2872}28732874my$header=shift@commit_lines;2875if($header!~m/^[0-9a-fA-F]{40}/) {2876return;2877}2878($co{'id'},my@parents) =split' ',$header;2879while(my$line=shift@commit_lines) {2880last if$lineeq"\n";2881if($line=~m/^tree ([0-9a-fA-F]{40})$/) {2882$co{'tree'} =$1;2883}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {2884push@parents,$1;2885}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {2886$co{'author'} = to_utf8($1);2887$co{'author_epoch'} =$2;2888$co{'author_tz'} =$3;2889if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {2890$co{'author_name'} =$1;2891$co{'author_email'} =$2;2892}else{2893$co{'author_name'} =$co{'author'};2894}2895}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {2896$co{'committer'} = to_utf8($1);2897$co{'committer_epoch'} =$2;2898$co{'committer_tz'} =$3;2899if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {2900$co{'committer_name'} =$1;2901$co{'committer_email'} =$2;2902}else{2903$co{'committer_name'} =$co{'committer'};2904}2905}2906}2907if(!defined$co{'tree'}) {2908return;2909};2910$co{'parents'} = \@parents;2911$co{'parent'} =$parents[0];29122913foreachmy$title(@commit_lines) {2914$title=~s/^ //;2915if($titlene"") {2916$co{'title'} = chop_str($title,80,5);2917# remove leading stuff of merges to make the interesting part visible2918if(length($title) >50) {2919$title=~s/^Automatic //;2920$title=~s/^merge (of|with) /Merge ... /i;2921if(length($title) >50) {2922$title=~s/(http|rsync):\/\///;2923}2924if(length($title) >50) {2925$title=~s/(master|www|rsync)\.//;2926}2927if(length($title) >50) {2928$title=~s/kernel.org:?//;2929}2930if(length($title) >50) {2931$title=~s/\/pub\/scm//;2932}2933}2934$co{'title_short'} = chop_str($title,50,5);2935last;2936}2937}2938if(!defined$co{'title'} ||$co{'title'}eq"") {2939$co{'title'} =$co{'title_short'} ='(no commit message)';2940}2941# remove added spaces2942foreachmy$line(@commit_lines) {2943$line=~s/^ //;2944}2945$co{'comment'} = \@commit_lines;29462947my$age=time-$co{'committer_epoch'};2948$co{'age'} =$age;2949$co{'age_string'} = age_string($age);2950my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});2951if($age>60*60*24*7*2) {2952$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;2953$co{'age_string_age'} =$co{'age_string'};2954}else{2955$co{'age_string_date'} =$co{'age_string'};2956$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;2957}2958return%co;2959}29602961sub parse_commit {2962my($commit_id) =@_;2963my%co;29642965local$/="\0";29662967open my$fd,"-|", git_cmd(),"rev-list",2968"--parents",2969"--header",2970"--max-count=1",2971$commit_id,2972"--",2973or die_error(500,"Open git-rev-list failed");2974%co= parse_commit_text(<$fd>,1);2975close$fd;29762977return%co;2978}29792980sub parse_commits {2981my($commit_id,$maxcount,$skip,$filename,@args) =@_;2982my@cos;29832984$maxcount||=1;2985$skip||=0;29862987local$/="\0";29882989open my$fd,"-|", git_cmd(),"rev-list",2990"--header",2991@args,2992("--max-count=".$maxcount),2993("--skip=".$skip),2994@extra_options,2995$commit_id,2996"--",2997($filename? ($filename) : ())2998or die_error(500,"Open git-rev-list failed");2999while(my$line= <$fd>) {3000my%co= parse_commit_text($line);3001push@cos, \%co;3002}3003close$fd;30043005returnwantarray?@cos: \@cos;3006}30073008# parse line of git-diff-tree "raw" output3009sub parse_difftree_raw_line {3010my$line=shift;3011my%res;30123013# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3014# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3015if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3016$res{'from_mode'} =$1;3017$res{'to_mode'} =$2;3018$res{'from_id'} =$3;3019$res{'to_id'} =$4;3020$res{'status'} =$5;3021$res{'similarity'} =$6;3022if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3023($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3024}else{3025$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3026}3027}3028# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3029# combined diff (for merge commit)3030elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3031$res{'nparents'} =length($1);3032$res{'from_mode'} = [split(' ',$2) ];3033$res{'to_mode'} =pop@{$res{'from_mode'}};3034$res{'from_id'} = [split(' ',$3) ];3035$res{'to_id'} =pop@{$res{'from_id'}};3036$res{'status'} = [split('',$4) ];3037$res{'to_file'} = unquote($5);3038}3039# 'c512b523472485aef4fff9e57b229d9d243c967f'3040elsif($line=~m/^([0-9a-fA-F]{40})$/) {3041$res{'commit'} =$1;3042}30433044returnwantarray?%res: \%res;3045}30463047# wrapper: return parsed line of git-diff-tree "raw" output3048# (the argument might be raw line, or parsed info)3049sub parsed_difftree_line {3050my$line_or_ref=shift;30513052if(ref($line_or_ref)eq"HASH") {3053# pre-parsed (or generated by hand)3054return$line_or_ref;3055}else{3056return parse_difftree_raw_line($line_or_ref);3057}3058}30593060# parse line of git-ls-tree output3061sub parse_ls_tree_line {3062my$line=shift;3063my%opts=@_;3064my%res;30653066if($opts{'-l'}) {3067#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3068$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;30693070$res{'mode'} =$1;3071$res{'type'} =$2;3072$res{'hash'} =$3;3073$res{'size'} =$4;3074if($opts{'-z'}) {3075$res{'name'} =$5;3076}else{3077$res{'name'} = unquote($5);3078}3079}else{3080#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3081$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;30823083$res{'mode'} =$1;3084$res{'type'} =$2;3085$res{'hash'} =$3;3086if($opts{'-z'}) {3087$res{'name'} =$4;3088}else{3089$res{'name'} = unquote($4);3090}3091}30923093returnwantarray?%res: \%res;3094}30953096# generates _two_ hashes, references to which are passed as 2 and 3 argument3097sub parse_from_to_diffinfo {3098my($diffinfo,$from,$to,@parents) =@_;30993100if($diffinfo->{'nparents'}) {3101# combined diff3102$from->{'file'} = [];3103$from->{'href'} = [];3104 fill_from_file_info($diffinfo,@parents)3105unlessexists$diffinfo->{'from_file'};3106for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3107$from->{'file'}[$i] =3108defined$diffinfo->{'from_file'}[$i] ?3109$diffinfo->{'from_file'}[$i] :3110$diffinfo->{'to_file'};3111if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3112$from->{'href'}[$i] = href(action=>"blob",3113 hash_base=>$parents[$i],3114 hash=>$diffinfo->{'from_id'}[$i],3115 file_name=>$from->{'file'}[$i]);3116}else{3117$from->{'href'}[$i] =undef;3118}3119}3120}else{3121# ordinary (not combined) diff3122$from->{'file'} =$diffinfo->{'from_file'};3123if($diffinfo->{'status'}ne"A") {# not new (added) file3124$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3125 hash=>$diffinfo->{'from_id'},3126 file_name=>$from->{'file'});3127}else{3128delete$from->{'href'};3129}3130}31313132$to->{'file'} =$diffinfo->{'to_file'};3133if(!is_deleted($diffinfo)) {# file exists in result3134$to->{'href'} = href(action=>"blob", hash_base=>$hash,3135 hash=>$diffinfo->{'to_id'},3136 file_name=>$to->{'file'});3137}else{3138delete$to->{'href'};3139}3140}31413142## ......................................................................3143## parse to array of hashes functions31443145sub git_get_heads_list {3146my$limit=shift;3147my@headslist;31483149open my$fd,'-|', git_cmd(),'for-each-ref',3150($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3151'--format=%(objectname) %(refname) %(subject)%00%(committer)',3152'refs/heads'3153orreturn;3154while(my$line= <$fd>) {3155my%ref_item;31563157chomp$line;3158my($refinfo,$committerinfo) =split(/\0/,$line);3159my($hash,$name,$title) =split(' ',$refinfo,3);3160my($committer,$epoch,$tz) =3161($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3162$ref_item{'fullname'} =$name;3163$name=~s!^refs/heads/!!;31643165$ref_item{'name'} =$name;3166$ref_item{'id'} =$hash;3167$ref_item{'title'} =$title||'(no commit message)';3168$ref_item{'epoch'} =$epoch;3169if($epoch) {3170$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3171}else{3172$ref_item{'age'} ="unknown";3173}31743175push@headslist, \%ref_item;3176}3177close$fd;31783179returnwantarray?@headslist: \@headslist;3180}31813182sub git_get_tags_list {3183my$limit=shift;3184my@tagslist;31853186open my$fd,'-|', git_cmd(),'for-each-ref',3187($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3188'--format=%(objectname) %(objecttype) %(refname) '.3189'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3190'refs/tags'3191orreturn;3192while(my$line= <$fd>) {3193my%ref_item;31943195chomp$line;3196my($refinfo,$creatorinfo) =split(/\0/,$line);3197my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3198my($creator,$epoch,$tz) =3199($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3200$ref_item{'fullname'} =$name;3201$name=~s!^refs/tags/!!;32023203$ref_item{'type'} =$type;3204$ref_item{'id'} =$id;3205$ref_item{'name'} =$name;3206if($typeeq"tag") {3207$ref_item{'subject'} =$title;3208$ref_item{'reftype'} =$reftype;3209$ref_item{'refid'} =$refid;3210}else{3211$ref_item{'reftype'} =$type;3212$ref_item{'refid'} =$id;3213}32143215if($typeeq"tag"||$typeeq"commit") {3216$ref_item{'epoch'} =$epoch;3217if($epoch) {3218$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3219}else{3220$ref_item{'age'} ="unknown";3221}3222}32233224push@tagslist, \%ref_item;3225}3226close$fd;32273228returnwantarray?@tagslist: \@tagslist;3229}32303231## ----------------------------------------------------------------------3232## filesystem-related functions32333234sub get_file_owner {3235my$path=shift;32363237my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3238my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3239if(!defined$gcos) {3240returnundef;3241}3242my$owner=$gcos;3243$owner=~s/[,;].*$//;3244return to_utf8($owner);3245}32463247# assume that file exists3248sub insert_file {3249my$filename=shift;32503251open my$fd,'<',$filename;3252print map{ to_utf8($_) } <$fd>;3253close$fd;3254}32553256## ......................................................................3257## mimetype related functions32583259sub mimetype_guess_file {3260my$filename=shift;3261my$mimemap=shift;3262-r $mimemaporreturnundef;32633264my%mimemap;3265open(my$mh,'<',$mimemap)orreturnundef;3266while(<$mh>) {3267next ifm/^#/;# skip comments3268my($mimetype,$exts) =split(/\t+/);3269if(defined$exts) {3270my@exts=split(/\s+/,$exts);3271foreachmy$ext(@exts) {3272$mimemap{$ext} =$mimetype;3273}3274}3275}3276close($mh);32773278$filename=~/\.([^.]*)$/;3279return$mimemap{$1};3280}32813282sub mimetype_guess {3283my$filename=shift;3284my$mime;3285$filename=~/\./orreturnundef;32863287if($mimetypes_file) {3288my$file=$mimetypes_file;3289if($file!~m!^/!) {# if it is relative path3290# it is relative to project3291$file="$projectroot/$project/$file";3292}3293$mime= mimetype_guess_file($filename,$file);3294}3295$mime||= mimetype_guess_file($filename,'/etc/mime.types');3296return$mime;3297}32983299sub blob_mimetype {3300my$fd=shift;3301my$filename=shift;33023303if($filename) {3304my$mime= mimetype_guess($filename);3305$mimeandreturn$mime;3306}33073308# just in case3309return$default_blob_plain_mimetypeunless$fd;33103311if(-T $fd) {3312return'text/plain';3313}elsif(!$filename) {3314return'application/octet-stream';3315}elsif($filename=~m/\.png$/i) {3316return'image/png';3317}elsif($filename=~m/\.gif$/i) {3318return'image/gif';3319}elsif($filename=~m/\.jpe?g$/i) {3320return'image/jpeg';3321}else{3322return'application/octet-stream';3323}3324}33253326sub blob_contenttype {3327my($fd,$file_name,$type) =@_;33283329$type||= blob_mimetype($fd,$file_name);3330if($typeeq'text/plain'&&defined$default_text_plain_charset) {3331$type.="; charset=$default_text_plain_charset";3332}33333334return$type;3335}33363337# guess file syntax for syntax highlighting; return undef if no highlighting3338# the name of syntax can (in the future) depend on syntax highlighter used3339sub guess_file_syntax {3340my($highlight,$mimetype,$file_name) =@_;3341returnundefunless($highlight&&defined$file_name);3342my$basename= basename($file_name,'.in');3343return$highlight_basename{$basename}3344ifexists$highlight_basename{$basename};33453346$basename=~/\.([^.]*)$/;3347my$ext=$1orreturnundef;3348return$highlight_ext{$ext}3349ifexists$highlight_ext{$ext};33503351returnundef;3352}33533354# run highlighter and return FD of its output,3355# or return original FD if no highlighting3356sub run_highlighter {3357my($fd,$highlight,$syntax) =@_;3358return$fdunless($highlight&&defined$syntax);33593360close$fd3361or die_error(404,"Reading blob failed");3362open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3363"highlight --xhtml --fragment --syntax$syntax|"3364or die_error(500,"Couldn't open file or run syntax highlighter");3365return$fd;3366}33673368## ======================================================================3369## functions printing HTML: header, footer, error page33703371sub get_page_title {3372my$title= to_utf8($site_name);33733374return$titleunless(defined$project);3375$title.=" - ". to_utf8($project);33763377return$titleunless(defined$action);3378$title.="/$action";# $action is US-ASCII (7bit ASCII)33793380return$titleunless(defined$file_name);3381$title.=" - ". esc_path($file_name);3382if($actioneq"tree"&&$file_name!~ m|/$|) {3383$title.="/";3384}33853386return$title;3387}33883389sub git_header_html {3390my$status=shift||"200 OK";3391my$expires=shift;3392my%opts=@_;33933394my$title= get_page_title();3395my$content_type;3396# require explicit support from the UA if we are to send the page as3397# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3398# we have to do this because MSIE sometimes globs '*/*', pretending to3399# support xhtml+xml but choking when it gets what it asked for.3400if(defined$cgi->http('HTTP_ACCEPT') &&3401$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3402$cgi->Accept('application/xhtml+xml') !=0) {3403$content_type='application/xhtml+xml';3404}else{3405$content_type='text/html';3406}3407print$cgi->header(-type=>$content_type, -charset =>'utf-8',3408-status=>$status, -expires =>$expires)3409unless($opts{'-no_http_header'});3410my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3411print<<EOF;3412<?xml version="1.0" encoding="utf-8"?>3413<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3414<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3415<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3416<!-- git core binaries version$git_version-->3417<head>3418<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3419<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3420<meta name="robots" content="index, nofollow"/>3421<title>$title</title>3422EOF3423# the stylesheet, favicon etc urls won't work correctly with path_info3424# unless we set the appropriate base URL3425if($ENV{'PATH_INFO'}) {3426print"<base href=\"".esc_url($base_url)."\"/>\n";3427}3428# print out each stylesheet that exist, providing backwards capability3429# for those people who defined $stylesheet in a config file3430if(defined$stylesheet) {3431print'<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";3432}else{3433foreachmy$stylesheet(@stylesheets) {3434next unless$stylesheet;3435print'<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";3436}3437}3438if(defined$project) {3439my%href_params= get_feed_info();3440if(!exists$href_params{'-title'}) {3441$href_params{'-title'} ='log';3442}34433444foreachmy$formatqw(RSS Atom){3445my$type=lc($format);3446my%link_attr= (3447'-rel'=>'alternate',3448'-title'=>"$project-$href_params{'-title'} -$formatfeed",3449'-type'=>"application/$type+xml"3450);34513452$href_params{'action'} =$type;3453$link_attr{'-href'} = href(%href_params);3454print"<link ".3455"rel=\"$link_attr{'-rel'}\"".3456"title=\"$link_attr{'-title'}\"".3457"href=\"$link_attr{'-href'}\"".3458"type=\"$link_attr{'-type'}\"".3459"/>\n";34603461$href_params{'extra_options'} ='--no-merges';3462$link_attr{'-href'} = href(%href_params);3463$link_attr{'-title'} .=' (no merges)';3464print"<link ".3465"rel=\"$link_attr{'-rel'}\"".3466"title=\"$link_attr{'-title'}\"".3467"href=\"$link_attr{'-href'}\"".3468"type=\"$link_attr{'-type'}\"".3469"/>\n";3470}34713472}else{3473printf('<link rel="alternate" title="%sprojects list" '.3474'href="%s" type="text/plain; charset=utf-8" />'."\n",3475$site_name, href(project=>undef, action=>"project_index"));3476printf('<link rel="alternate" title="%sprojects feeds" '.3477'href="%s" type="text/x-opml" />'."\n",3478$site_name, href(project=>undef, action=>"opml"));3479}3480if(defined$favicon) {3481printqq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);3482}34833484print"</head>\n".3485"<body>\n";34863487if(defined$site_header&& -f $site_header) {3488 insert_file($site_header);3489}34903491print"<div class=\"page_header\">\n".3492$cgi->a({-href => esc_url($logo_url),3493-title =>$logo_label},3494qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));3495print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3496if(defined$project) {3497print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3498if(defined$action) {3499print" /$action";3500}3501print"\n";3502}3503print"</div>\n";35043505my$have_search= gitweb_check_feature('search');3506if(defined$project&&$have_search) {3507if(!defined$searchtext) {3508$searchtext="";3509}3510my$search_hash;3511if(defined$hash_base) {3512$search_hash=$hash_base;3513}elsif(defined$hash) {3514$search_hash=$hash;3515}else{3516$search_hash="HEAD";3517}3518my$action=$my_uri;3519my$use_pathinfo= gitweb_check_feature('pathinfo');3520if($use_pathinfo) {3521$action.="/".esc_url($project);3522}3523print$cgi->startform(-method=>"get", -action =>$action) .3524"<div class=\"search\">\n".3525(!$use_pathinfo&&3526$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3527$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3528$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3529$cgi->popup_menu(-name =>'st', -default=>'commit',3530-values=> ['commit','grep','author','committer','pickaxe']) .3531$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3532" search:\n",3533$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3534"<span title=\"Extended regular expression\">".3535$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3536-checked =>$search_use_regexp) .3537"</span>".3538"</div>".3539$cgi->end_form() ."\n";3540}3541}35423543sub git_footer_html {3544my$feed_class='rss_logo';35453546print"<div class=\"page_footer\">\n";3547if(defined$project) {3548my$descr= git_get_project_description($project);3549if(defined$descr) {3550print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3551}35523553my%href_params= get_feed_info();3554if(!%href_params) {3555$feed_class.=' generic';3556}3557$href_params{'-title'} ||='log';35583559foreachmy$formatqw(RSS Atom){3560$href_params{'action'} =lc($format);3561print$cgi->a({-href => href(%href_params),3562-title =>"$href_params{'-title'}$formatfeed",3563-class=>$feed_class},$format)."\n";3564}35653566}else{3567print$cgi->a({-href => href(project=>undef, action=>"opml"),3568-class=>$feed_class},"OPML") ." ";3569print$cgi->a({-href => href(project=>undef, action=>"project_index"),3570-class=>$feed_class},"TXT") ."\n";3571}3572print"</div>\n";# class="page_footer"35733574if(defined$t0&& gitweb_check_feature('timed')) {3575print"<div id=\"generating_info\">\n";3576print'This page took '.3577'<span id="generating_time" class="time_span">'.3578 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).3579' seconds </span>'.3580' and '.3581'<span id="generating_cmd">'.3582$number_of_git_cmds.3583'</span> git commands '.3584" to generate.\n";3585print"</div>\n";# class="page_footer"3586}35873588if(defined$site_footer&& -f $site_footer) {3589 insert_file($site_footer);3590}35913592print qq!<script type="text/javascript" src="$javascript"></script>\n!;3593if(defined$action&&3594$actioneq'blame_incremental') {3595print qq!<script type="text/javascript">\n!.3596 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.3597 qq!"!. href() .qq!");\n!.3598 qq!</script>\n!;3599}elsif(gitweb_check_feature('javascript-actions')) {3600print qq!<script type="text/javascript">\n!.3601 qq!window.onload = fixLinks;\n!.3602 qq!</script>\n!;3603}36043605print"</body>\n".3606"</html>";3607}36083609# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])3610# Example: die_error(404, 'Hash not found')3611# By convention, use the following status codes (as defined in RFC 2616):3612# 400: Invalid or missing CGI parameters, or3613# requested object exists but has wrong type.3614# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3615# this server or project.3616# 404: Requested object/revision/project doesn't exist.3617# 500: The server isn't configured properly, or3618# an internal error occurred (e.g. failed assertions caused by bugs), or3619# an unknown error occurred (e.g. the git binary died unexpectedly).3620# 503: The server is currently unavailable (because it is overloaded,3621# or down for maintenance). Generally, this is a temporary state.3622sub die_error {3623my$status=shift||500;3624my$error= esc_html(shift) ||"Internal Server Error";3625my$extra=shift;3626my%opts=@_;36273628my%http_responses= (3629400=>'400 Bad Request',3630403=>'403 Forbidden',3631404=>'404 Not Found',3632500=>'500 Internal Server Error',3633503=>'503 Service Unavailable',3634);3635 git_header_html($http_responses{$status},undef,%opts);3636print<<EOF;3637<div class="page_body">3638<br /><br />3639$status-$error3640<br />3641EOF3642if(defined$extra) {3643print"<hr />\n".3644"$extra\n";3645}3646print"</div>\n";36473648 git_footer_html();3649goto DONE_GITWEB3650unless($opts{'-error_handler'});3651}36523653## ----------------------------------------------------------------------3654## functions printing or outputting HTML: navigation36553656sub git_print_page_nav {3657my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;3658$extra=''if!defined$extra;# pager or formats36593660my@navs=qw(summary shortlog log commit commitdiff tree);3661if($suppress) {3662@navs=grep{$_ne$suppress}@navs;3663}36643665my%arg=map{$_=> {action=>$_} }@navs;3666if(defined$head) {3667for(qw(commit commitdiff)) {3668$arg{$_}{'hash'} =$head;3669}3670if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {3671for(qw(shortlog log)) {3672$arg{$_}{'hash'} =$head;3673}3674}3675}36763677$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;3678$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;36793680my@actions= gitweb_get_feature('actions');3681my%repl= (3682'%'=>'%',3683'n'=>$project,# project name3684'f'=>$git_dir,# project path within filesystem3685'h'=>$treehead||'',# current hash ('h' parameter)3686'b'=>$treebase||'',# hash base ('hb' parameter)3687);3688while(@actions) {3689my($label,$link,$pos) =splice(@actions,0,3);3690# insert3691@navs=map{$_eq$pos? ($_,$label) :$_}@navs;3692# munch munch3693$link=~s/%([%nfhb])/$repl{$1}/g;3694$arg{$label}{'_href'} =$link;3695}36963697print"<div class=\"page_nav\">\n".3698(join" | ",3699map{$_eq$current?3700$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")3701}@navs);3702print"<br/>\n$extra<br/>\n".3703"</div>\n";3704}37053706sub format_paging_nav {3707my($action,$page,$has_next_link) =@_;3708my$paging_nav;370937103711if($page>0) {3712$paging_nav.=3713$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .3714" ⋅ ".3715$cgi->a({-href => href(-replay=>1, page=>$page-1),3716-accesskey =>"p", -title =>"Alt-p"},"prev");3717}else{3718$paging_nav.="first ⋅ prev";3719}37203721if($has_next_link) {3722$paging_nav.=" ⋅ ".3723$cgi->a({-href => href(-replay=>1, page=>$page+1),3724-accesskey =>"n", -title =>"Alt-n"},"next");3725}else{3726$paging_nav.=" ⋅ next";3727}37283729return$paging_nav;3730}37313732## ......................................................................3733## functions printing or outputting HTML: div37343735sub git_print_header_div {3736my($action,$title,$hash,$hash_base) =@_;3737my%args= ();37383739$args{'action'} =$action;3740$args{'hash'} =$hashif$hash;3741$args{'hash_base'} =$hash_baseif$hash_base;37423743print"<div class=\"header\">\n".3744$cgi->a({-href => href(%args), -class=>"title"},3745$title?$title:$action) .3746"\n</div>\n";3747}37483749sub print_local_time {3750print format_local_time(@_);3751}37523753sub format_local_time {3754my$localtime='';3755my%date=@_;3756if($date{'hour_local'} <6) {3757$localtime.=sprintf(" (<span class=\"atnight\">%02d:%02d</span>%s)",3758$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});3759}else{3760$localtime.=sprintf(" (%02d:%02d%s)",3761$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});3762}37633764return$localtime;3765}37663767# Outputs the author name and date in long form3768sub git_print_authorship {3769my$co=shift;3770my%opts=@_;3771my$tag=$opts{-tag} ||'div';3772my$author=$co->{'author_name'};37733774my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});3775print"<$tagclass=\"author_date\">".3776 format_search_author($author,"author", esc_html($author)) .3777" [$ad{'rfc2822'}";3778 print_local_time(%ad)if($opts{-localtime});3779print"]". git_get_avatar($co->{'author_email'}, -pad_before =>1)3780."</$tag>\n";3781}37823783# Outputs table rows containing the full author or committer information,3784# in the format expected for 'commit' view (& similar).3785# Parameters are a commit hash reference, followed by the list of people3786# to output information for. If the list is empty it defaults to both3787# author and committer.3788sub git_print_authorship_rows {3789my$co=shift;3790# too bad we can't use @people = @_ || ('author', 'committer')3791my@people=@_;3792@people= ('author','committer')unless@people;3793foreachmy$who(@people) {3794my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});3795print"<tr><td>$who</td><td>".3796 format_search_author($co->{"${who}_name"},$who,3797 esc_html($co->{"${who}_name"})) ." ".3798 format_search_author($co->{"${who}_email"},$who,3799 esc_html("<".$co->{"${who}_email"} .">")) .3800"</td><td rowspan=\"2\">".3801 git_get_avatar($co->{"${who}_email"}, -size =>'double') .3802"</td></tr>\n".3803"<tr>".3804"<td></td><td>$wd{'rfc2822'}";3805 print_local_time(%wd);3806print"</td>".3807"</tr>\n";3808}3809}38103811sub git_print_page_path {3812my$name=shift;3813my$type=shift;3814my$hb=shift;381538163817print"<div class=\"page_path\">";3818print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),3819-title =>'tree root'}, to_utf8("[$project]"));3820print" / ";3821if(defined$name) {3822my@dirname=split'/',$name;3823my$basename=pop@dirname;3824my$fullname='';38253826foreachmy$dir(@dirname) {3827$fullname.= ($fullname?'/':'') .$dir;3828print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,3829 hash_base=>$hb),3830-title =>$fullname}, esc_path($dir));3831print" / ";3832}3833if(defined$type&&$typeeq'blob') {3834print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,3835 hash_base=>$hb),3836-title =>$name}, esc_path($basename));3837}elsif(defined$type&&$typeeq'tree') {3838print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,3839 hash_base=>$hb),3840-title =>$name}, esc_path($basename));3841print" / ";3842}else{3843print esc_path($basename);3844}3845}3846print"<br/></div>\n";3847}38483849sub git_print_log {3850my$log=shift;3851my%opts=@_;38523853if($opts{'-remove_title'}) {3854# remove title, i.e. first line of log3855shift@$log;3856}3857# remove leading empty lines3858while(defined$log->[0] &&$log->[0]eq"") {3859shift@$log;3860}38613862# print log3863my$signoff=0;3864my$empty=0;3865foreachmy$line(@$log) {3866if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {3867$signoff=1;3868$empty=0;3869if(!$opts{'-remove_signoff'}) {3870print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";3871next;3872}else{3873# remove signoff lines3874next;3875}3876}else{3877$signoff=0;3878}38793880# print only one empty line3881# do not print empty line after signoff3882if($lineeq"") {3883next if($empty||$signoff);3884$empty=1;3885}else{3886$empty=0;3887}38883889print format_log_line_html($line) ."<br/>\n";3890}38913892if($opts{'-final_empty_line'}) {3893# end with single empty line3894print"<br/>\n"unless$empty;3895}3896}38973898# return link target (what link points to)3899sub git_get_link_target {3900my$hash=shift;3901my$link_target;39023903# read link3904open my$fd,"-|", git_cmd(),"cat-file","blob",$hash3905orreturn;3906{3907local$/=undef;3908$link_target= <$fd>;3909}3910close$fd3911orreturn;39123913return$link_target;3914}39153916# given link target, and the directory (basedir) the link is in,3917# return target of link relative to top directory (top tree);3918# return undef if it is not possible (including absolute links).3919sub normalize_link_target {3920my($link_target,$basedir) =@_;39213922# absolute symlinks (beginning with '/') cannot be normalized3923return if(substr($link_target,0,1)eq'/');39243925# normalize link target to path from top (root) tree (dir)3926my$path;3927if($basedir) {3928$path=$basedir.'/'.$link_target;3929}else{3930# we are in top (root) tree (dir)3931$path=$link_target;3932}39333934# remove //, /./, and /../3935my@path_parts;3936foreachmy$part(split('/',$path)) {3937# discard '.' and ''3938next if(!$part||$parteq'.');3939# handle '..'3940if($parteq'..') {3941if(@path_parts) {3942pop@path_parts;3943}else{3944# link leads outside repository (outside top dir)3945return;3946}3947}else{3948push@path_parts,$part;3949}3950}3951$path=join('/',@path_parts);39523953return$path;3954}39553956# print tree entry (row of git_tree), but without encompassing <tr> element3957sub git_print_tree_entry {3958my($t,$basedir,$hash_base,$have_blame) =@_;39593960my%base_key= ();3961$base_key{'hash_base'} =$hash_baseifdefined$hash_base;39623963# The format of a table row is: mode list link. Where mode is3964# the mode of the entry, list is the name of the entry, an href,3965# and link is the action links of the entry.39663967print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";3968if(exists$t->{'size'}) {3969print"<td class=\"size\">$t->{'size'}</td>\n";3970}3971if($t->{'type'}eq"blob") {3972print"<td class=\"list\">".3973$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},3974 file_name=>"$basedir$t->{'name'}",%base_key),3975-class=>"list"}, esc_path($t->{'name'}));3976if(S_ISLNK(oct$t->{'mode'})) {3977my$link_target= git_get_link_target($t->{'hash'});3978if($link_target) {3979my$norm_target= normalize_link_target($link_target,$basedir);3980if(defined$norm_target) {3981print" -> ".3982$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,3983 file_name=>$norm_target),3984-title =>$norm_target}, esc_path($link_target));3985}else{3986print" -> ". esc_path($link_target);3987}3988}3989}3990print"</td>\n";3991print"<td class=\"link\">";3992print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},3993 file_name=>"$basedir$t->{'name'}",%base_key)},3994"blob");3995if($have_blame) {3996print" | ".3997$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},3998 file_name=>"$basedir$t->{'name'}",%base_key)},3999"blame");4000}4001if(defined$hash_base) {4002print" | ".4003$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4004 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4005"history");4006}4007print" | ".4008$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4009 file_name=>"$basedir$t->{'name'}")},4010"raw");4011print"</td>\n";40124013}elsif($t->{'type'}eq"tree") {4014print"<td class=\"list\">";4015print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4016 file_name=>"$basedir$t->{'name'}",4017%base_key)},4018 esc_path($t->{'name'}));4019print"</td>\n";4020print"<td class=\"link\">";4021print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4022 file_name=>"$basedir$t->{'name'}",4023%base_key)},4024"tree");4025if(defined$hash_base) {4026print" | ".4027$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4028 file_name=>"$basedir$t->{'name'}")},4029"history");4030}4031print"</td>\n";4032}else{4033# unknown object: we can only present history for it4034# (this includes 'commit' object, i.e. submodule support)4035print"<td class=\"list\">".4036 esc_path($t->{'name'}) .4037"</td>\n";4038print"<td class=\"link\">";4039if(defined$hash_base) {4040print$cgi->a({-href => href(action=>"history",4041 hash_base=>$hash_base,4042 file_name=>"$basedir$t->{'name'}")},4043"history");4044}4045print"</td>\n";4046}4047}40484049## ......................................................................4050## functions printing large fragments of HTML40514052# get pre-image filenames for merge (combined) diff4053sub fill_from_file_info {4054my($diff,@parents) =@_;40554056$diff->{'from_file'} = [ ];4057$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4058for(my$i=0;$i<$diff->{'nparents'};$i++) {4059if($diff->{'status'}[$i]eq'R'||4060$diff->{'status'}[$i]eq'C') {4061$diff->{'from_file'}[$i] =4062 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4063}4064}40654066return$diff;4067}40684069# is current raw difftree line of file deletion4070sub is_deleted {4071my$diffinfo=shift;40724073return$diffinfo->{'to_id'}eq('0' x 40);4074}40754076# does patch correspond to [previous] difftree raw line4077# $diffinfo - hashref of parsed raw diff format4078# $patchinfo - hashref of parsed patch diff format4079# (the same keys as in $diffinfo)4080sub is_patch_split {4081my($diffinfo,$patchinfo) =@_;40824083returndefined$diffinfo&&defined$patchinfo4084&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4085}408640874088sub git_difftree_body {4089my($difftree,$hash,@parents) =@_;4090my($parent) =$parents[0];4091my$have_blame= gitweb_check_feature('blame');4092print"<div class=\"list_head\">\n";4093if($#{$difftree} >10) {4094print(($#{$difftree} +1) ." files changed:\n");4095}4096print"</div>\n";40974098print"<table class=\"".4099(@parents>1?"combined ":"") .4100"diff_tree\">\n";41014102# header only for combined diff in 'commitdiff' view4103my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4104if($has_header) {4105# table header4106print"<thead><tr>\n".4107"<th></th><th></th>\n";# filename, patchN link4108for(my$i=0;$i<@parents;$i++) {4109my$par=$parents[$i];4110print"<th>".4111$cgi->a({-href => href(action=>"commitdiff",4112 hash=>$hash, hash_parent=>$par),4113-title =>'commitdiff to parent number '.4114($i+1) .': '.substr($par,0,7)},4115$i+1) .4116" </th>\n";4117}4118print"</tr></thead>\n<tbody>\n";4119}41204121my$alternate=1;4122my$patchno=0;4123foreachmy$line(@{$difftree}) {4124my$diff= parsed_difftree_line($line);41254126if($alternate) {4127print"<tr class=\"dark\">\n";4128}else{4129print"<tr class=\"light\">\n";4130}4131$alternate^=1;41324133if(exists$diff->{'nparents'}) {# combined diff41344135 fill_from_file_info($diff,@parents)4136unlessexists$diff->{'from_file'};41374138if(!is_deleted($diff)) {4139# file exists in the result (child) commit4140print"<td>".4141$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4142 file_name=>$diff->{'to_file'},4143 hash_base=>$hash),4144-class=>"list"}, esc_path($diff->{'to_file'})) .4145"</td>\n";4146}else{4147print"<td>".4148 esc_path($diff->{'to_file'}) .4149"</td>\n";4150}41514152if($actioneq'commitdiff') {4153# link to patch4154$patchno++;4155print"<td class=\"link\">".4156$cgi->a({-href =>"#patch$patchno"},"patch") .4157" | ".4158"</td>\n";4159}41604161my$has_history=0;4162my$not_deleted=0;4163for(my$i=0;$i<$diff->{'nparents'};$i++) {4164my$hash_parent=$parents[$i];4165my$from_hash=$diff->{'from_id'}[$i];4166my$from_path=$diff->{'from_file'}[$i];4167my$status=$diff->{'status'}[$i];41684169$has_history||= ($statusne'A');4170$not_deleted||= ($statusne'D');41714172if($statuseq'A') {4173print"<td class=\"link\"align=\"right\"> | </td>\n";4174}elsif($statuseq'D') {4175print"<td class=\"link\">".4176$cgi->a({-href => href(action=>"blob",4177 hash_base=>$hash,4178 hash=>$from_hash,4179 file_name=>$from_path)},4180"blob". ($i+1)) .4181" | </td>\n";4182}else{4183if($diff->{'to_id'}eq$from_hash) {4184print"<td class=\"link nochange\">";4185}else{4186print"<td class=\"link\">";4187}4188print$cgi->a({-href => href(action=>"blobdiff",4189 hash=>$diff->{'to_id'},4190 hash_parent=>$from_hash,4191 hash_base=>$hash,4192 hash_parent_base=>$hash_parent,4193 file_name=>$diff->{'to_file'},4194 file_parent=>$from_path)},4195"diff". ($i+1)) .4196" | </td>\n";4197}4198}41994200print"<td class=\"link\">";4201if($not_deleted) {4202print$cgi->a({-href => href(action=>"blob",4203 hash=>$diff->{'to_id'},4204 file_name=>$diff->{'to_file'},4205 hash_base=>$hash)},4206"blob");4207print" | "if($has_history);4208}4209if($has_history) {4210print$cgi->a({-href => href(action=>"history",4211 file_name=>$diff->{'to_file'},4212 hash_base=>$hash)},4213"history");4214}4215print"</td>\n";42164217print"</tr>\n";4218next;# instead of 'else' clause, to avoid extra indent4219}4220# else ordinary diff42214222my($to_mode_oct,$to_mode_str,$to_file_type);4223my($from_mode_oct,$from_mode_str,$from_file_type);4224if($diff->{'to_mode'}ne('0' x 6)) {4225$to_mode_oct=oct$diff->{'to_mode'};4226if(S_ISREG($to_mode_oct)) {# only for regular file4227$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4228}4229$to_file_type= file_type($diff->{'to_mode'});4230}4231if($diff->{'from_mode'}ne('0' x 6)) {4232$from_mode_oct=oct$diff->{'from_mode'};4233if(S_ISREG($to_mode_oct)) {# only for regular file4234$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4235}4236$from_file_type= file_type($diff->{'from_mode'});4237}42384239if($diff->{'status'}eq"A") {# created4240my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4241$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4242$mode_chng.="]</span>";4243print"<td>";4244print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4245 hash_base=>$hash, file_name=>$diff->{'file'}),4246-class=>"list"}, esc_path($diff->{'file'}));4247print"</td>\n";4248print"<td>$mode_chng</td>\n";4249print"<td class=\"link\">";4250if($actioneq'commitdiff') {4251# link to patch4252$patchno++;4253print$cgi->a({-href =>"#patch$patchno"},"patch");4254print" | ";4255}4256print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4257 hash_base=>$hash, file_name=>$diff->{'file'})},4258"blob");4259print"</td>\n";42604261}elsif($diff->{'status'}eq"D") {# deleted4262my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4263print"<td>";4264print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4265 hash_base=>$parent, file_name=>$diff->{'file'}),4266-class=>"list"}, esc_path($diff->{'file'}));4267print"</td>\n";4268print"<td>$mode_chng</td>\n";4269print"<td class=\"link\">";4270if($actioneq'commitdiff') {4271# link to patch4272$patchno++;4273print$cgi->a({-href =>"#patch$patchno"},"patch");4274print" | ";4275}4276print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4277 hash_base=>$parent, file_name=>$diff->{'file'})},4278"blob") ." | ";4279if($have_blame) {4280print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4281 file_name=>$diff->{'file'})},4282"blame") ." | ";4283}4284print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4285 file_name=>$diff->{'file'})},4286"history");4287print"</td>\n";42884289}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4290my$mode_chnge="";4291if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4292$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4293if($from_file_typene$to_file_type) {4294$mode_chnge.=" from$from_file_typeto$to_file_type";4295}4296if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4297if($from_mode_str&&$to_mode_str) {4298$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4299}elsif($to_mode_str) {4300$mode_chnge.=" mode:$to_mode_str";4301}4302}4303$mode_chnge.="]</span>\n";4304}4305print"<td>";4306print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4307 hash_base=>$hash, file_name=>$diff->{'file'}),4308-class=>"list"}, esc_path($diff->{'file'}));4309print"</td>\n";4310print"<td>$mode_chnge</td>\n";4311print"<td class=\"link\">";4312if($actioneq'commitdiff') {4313# link to patch4314$patchno++;4315print$cgi->a({-href =>"#patch$patchno"},"patch") .4316" | ";4317}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4318# "commit" view and modified file (not onlu mode changed)4319print$cgi->a({-href => href(action=>"blobdiff",4320 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4321 hash_base=>$hash, hash_parent_base=>$parent,4322 file_name=>$diff->{'file'})},4323"diff") .4324" | ";4325}4326print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4327 hash_base=>$hash, file_name=>$diff->{'file'})},4328"blob") ." | ";4329if($have_blame) {4330print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4331 file_name=>$diff->{'file'})},4332"blame") ." | ";4333}4334print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4335 file_name=>$diff->{'file'})},4336"history");4337print"</td>\n";43384339}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4340my%status_name= ('R'=>'moved','C'=>'copied');4341my$nstatus=$status_name{$diff->{'status'}};4342my$mode_chng="";4343if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4344# mode also for directories, so we cannot use $to_mode_str4345$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4346}4347print"<td>".4348$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4349 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4350-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4351"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4352$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4353 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4354-class=>"list"}, esc_path($diff->{'from_file'})) .4355" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4356"<td class=\"link\">";4357if($actioneq'commitdiff') {4358# link to patch4359$patchno++;4360print$cgi->a({-href =>"#patch$patchno"},"patch") .4361" | ";4362}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4363# "commit" view and modified file (not only pure rename or copy)4364print$cgi->a({-href => href(action=>"blobdiff",4365 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4366 hash_base=>$hash, hash_parent_base=>$parent,4367 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4368"diff") .4369" | ";4370}4371print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4372 hash_base=>$parent, file_name=>$diff->{'to_file'})},4373"blob") ." | ";4374if($have_blame) {4375print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4376 file_name=>$diff->{'to_file'})},4377"blame") ." | ";4378}4379print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4380 file_name=>$diff->{'to_file'})},4381"history");4382print"</td>\n";43834384}# we should not encounter Unmerged (U) or Unknown (X) status4385print"</tr>\n";4386}4387print"</tbody>"if$has_header;4388print"</table>\n";4389}43904391sub git_patchset_body {4392my($fd,$difftree,$hash,@hash_parents) =@_;4393my($hash_parent) =$hash_parents[0];43944395my$is_combined= (@hash_parents>1);4396my$patch_idx=0;4397my$patch_number=0;4398my$patch_line;4399my$diffinfo;4400my$to_name;4401my(%from,%to);44024403print"<div class=\"patchset\">\n";44044405# skip to first patch4406while($patch_line= <$fd>) {4407chomp$patch_line;44084409last if($patch_line=~m/^diff /);4410}44114412 PATCH:4413while($patch_line) {44144415# parse "git diff" header line4416if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4417# $1 is from_name, which we do not use4418$to_name= unquote($2);4419$to_name=~s!^b/!!;4420}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4421# $1 is 'cc' or 'combined', which we do not use4422$to_name= unquote($2);4423}else{4424$to_name=undef;4425}44264427# check if current patch belong to current raw line4428# and parse raw git-diff line if needed4429if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4430# this is continuation of a split patch4431print"<div class=\"patch cont\">\n";4432}else{4433# advance raw git-diff output if needed4434$patch_idx++ifdefined$diffinfo;44354436# read and prepare patch information4437$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);44384439# compact combined diff output can have some patches skipped4440# find which patch (using pathname of result) we are at now;4441if($is_combined) {4442while($to_namene$diffinfo->{'to_file'}) {4443print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4444 format_diff_cc_simplified($diffinfo,@hash_parents) .4445"</div>\n";# class="patch"44464447$patch_idx++;4448$patch_number++;44494450last if$patch_idx>$#$difftree;4451$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4452}4453}44544455# modifies %from, %to hashes4456 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);44574458# this is first patch for raw difftree line with $patch_idx index4459# we index @$difftree array from 0, but number patches from 14460print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4461}44624463# git diff header4464#assert($patch_line =~ m/^diff /) if DEBUG;4465#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4466$patch_number++;4467# print "git diff" header4468print format_git_diff_header_line($patch_line,$diffinfo,4469 \%from, \%to);44704471# print extended diff header4472print"<div class=\"diff extended_header\">\n";4473 EXTENDED_HEADER:4474while($patch_line= <$fd>) {4475chomp$patch_line;44764477last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);44784479print format_extended_diff_header_line($patch_line,$diffinfo,4480 \%from, \%to);4481}4482print"</div>\n";# class="diff extended_header"44834484# from-file/to-file diff header4485if(!$patch_line) {4486print"</div>\n";# class="patch"4487last PATCH;4488}4489next PATCH if($patch_line=~m/^diff /);4490#assert($patch_line =~ m/^---/) if DEBUG;44914492my$last_patch_line=$patch_line;4493$patch_line= <$fd>;4494chomp$patch_line;4495#assert($patch_line =~ m/^\+\+\+/) if DEBUG;44964497print format_diff_from_to_header($last_patch_line,$patch_line,4498$diffinfo, \%from, \%to,4499@hash_parents);45004501# the patch itself4502 LINE:4503while($patch_line= <$fd>) {4504chomp$patch_line;45054506next PATCH if($patch_line=~m/^diff /);45074508print format_diff_line($patch_line, \%from, \%to);4509}45104511}continue{4512print"</div>\n";# class="patch"4513}45144515# for compact combined (--cc) format, with chunk and patch simplification4516# the patchset might be empty, but there might be unprocessed raw lines4517for(++$patch_idxif$patch_number>0;4518$patch_idx<@$difftree;4519++$patch_idx) {4520# read and prepare patch information4521$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);45224523# generate anchor for "patch" links in difftree / whatchanged part4524print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4525 format_diff_cc_simplified($diffinfo,@hash_parents) .4526"</div>\n";# class="patch"45274528$patch_number++;4529}45304531if($patch_number==0) {4532if(@hash_parents>1) {4533print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4534}else{4535print"<div class=\"diff nodifferences\">No differences found</div>\n";4536}4537}45384539print"</div>\n";# class="patchset"4540}45414542# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .45434544# fills project list info (age, description, owner, forks) for each4545# project in the list, removing invalid projects from returned list4546# NOTE: modifies $projlist, but does not remove entries from it4547sub fill_project_list_info {4548my($projlist,$check_forks) =@_;4549my@projects;45504551my$show_ctags= gitweb_check_feature('ctags');4552 PROJECT:4553foreachmy$pr(@$projlist) {4554my(@activity) = git_get_last_activity($pr->{'path'});4555unless(@activity) {4556next PROJECT;4557}4558($pr->{'age'},$pr->{'age_string'}) =@activity;4559if(!defined$pr->{'descr'}) {4560my$descr= git_get_project_description($pr->{'path'}) ||"";4561$descr= to_utf8($descr);4562$pr->{'descr_long'} =$descr;4563$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);4564}4565if(!defined$pr->{'owner'}) {4566$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";4567}4568if($check_forks) {4569my$pname=$pr->{'path'};4570if(($pname=~s/\.git$//) &&4571($pname!~/\/$/) &&4572(-d "$projectroot/$pname")) {4573$pr->{'forks'} ="-d$projectroot/$pname";4574}else{4575$pr->{'forks'} =0;4576}4577}4578$show_ctagsand$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});4579push@projects,$pr;4580}45814582return@projects;4583}45844585# print 'sort by' <th> element, generating 'sort by $name' replay link4586# if that order is not selected4587sub print_sort_th {4588print format_sort_th(@_);4589}45904591sub format_sort_th {4592my($name,$order,$header) =@_;4593my$sort_th="";4594$header||=ucfirst($name);45954596if($ordereq$name) {4597$sort_th.="<th>$header</th>\n";4598}else{4599$sort_th.="<th>".4600$cgi->a({-href => href(-replay=>1, order=>$name),4601-class=>"header"},$header) .4602"</th>\n";4603}46044605return$sort_th;4606}46074608sub git_project_list_body {4609# actually uses global variable $project4610my($projlist,$order,$from,$to,$extra,$no_header) =@_;46114612my$check_forks= gitweb_check_feature('forks');4613my@projects= fill_project_list_info($projlist,$check_forks);46144615$order||=$default_projects_order;4616$from=0unlessdefined$from;4617$to=$#projectsif(!defined$to||$#projects<$to);46184619my%order_info= (4620 project => { key =>'path', type =>'str'},4621 descr => { key =>'descr_long', type =>'str'},4622 owner => { key =>'owner', type =>'str'},4623 age => { key =>'age', type =>'num'}4624);4625my$oi=$order_info{$order};4626if($oi->{'type'}eq'str') {4627@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@projects;4628}else{4629@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@projects;4630}46314632my$show_ctags= gitweb_check_feature('ctags');4633if($show_ctags) {4634my%ctags;4635foreachmy$p(@projects) {4636foreachmy$ct(keys%{$p->{'ctags'}}) {4637$ctags{$ct} +=$p->{'ctags'}->{$ct};4638}4639}4640my$cloud= git_populate_project_tagcloud(\%ctags);4641print git_show_project_tagcloud($cloud,64);4642}46434644print"<table class=\"project_list\">\n";4645unless($no_header) {4646print"<tr>\n";4647if($check_forks) {4648print"<th></th>\n";4649}4650 print_sort_th('project',$order,'Project');4651 print_sort_th('descr',$order,'Description');4652 print_sort_th('owner',$order,'Owner');4653 print_sort_th('age',$order,'Last Change');4654print"<th></th>\n".# for links4655"</tr>\n";4656}4657my$alternate=1;4658my$tagfilter=$cgi->param('by_tag');4659for(my$i=$from;$i<=$to;$i++) {4660my$pr=$projects[$i];46614662next if$tagfilterand$show_ctagsand not grep{lc$_eq lc$tagfilter}keys%{$pr->{'ctags'}};4663next if$searchtextand not$pr->{'path'} =~/$searchtext/4664and not$pr->{'descr_long'} =~/$searchtext/;4665# Weed out forks or non-matching entries of search4666if($check_forks) {4667my$forkbase=$project;$forkbase||='';$forkbase=~ s#\.git$#/#;4668$forkbase="^$forkbase"if$forkbase;4669next ifnot$searchtextand not$tagfilterand$show_ctags4670and$pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe4671}46724673if($alternate) {4674print"<tr class=\"dark\">\n";4675}else{4676print"<tr class=\"light\">\n";4677}4678$alternate^=1;4679if($check_forks) {4680print"<td>";4681if($pr->{'forks'}) {4682print"<!--$pr->{'forks'} -->\n";4683print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"+");4684}4685print"</td>\n";4686}4687print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),4688-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".4689"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),4690-class=>"list", -title =>$pr->{'descr_long'}},4691 esc_html($pr->{'descr'})) ."</td>\n".4692"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";4693print"<td class=\"". age_class($pr->{'age'}) ."\">".4694(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".4695"<td class=\"link\">".4696$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".4697$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".4698$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".4699$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .4700($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .4701"</td>\n".4702"</tr>\n";4703}4704if(defined$extra) {4705print"<tr>\n";4706if($check_forks) {4707print"<td></td>\n";4708}4709print"<td colspan=\"5\">$extra</td>\n".4710"</tr>\n";4711}4712print"</table>\n";4713}47144715sub git_log_body {4716# uses global variable $project4717my($commitlist,$from,$to,$refs,$extra) =@_;47184719$from=0unlessdefined$from;4720$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);47214722for(my$i=0;$i<=$to;$i++) {4723my%co= %{$commitlist->[$i]};4724next if!%co;4725my$commit=$co{'id'};4726my$ref= format_ref_marker($refs,$commit);4727my%ad= parse_date($co{'author_epoch'});4728 git_print_header_div('commit',4729"<span class=\"age\">$co{'age_string'}</span>".4730 esc_html($co{'title'}) .$ref,4731$commit);4732print"<div class=\"title_text\">\n".4733"<div class=\"log_link\">\n".4734$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .4735" | ".4736$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .4737" | ".4738$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .4739"<br/>\n".4740"</div>\n";4741 git_print_authorship(\%co, -tag =>'span');4742print"<br/>\n</div>\n";47434744print"<div class=\"log_body\">\n";4745 git_print_log($co{'comment'}, -final_empty_line=>1);4746print"</div>\n";4747}4748if($extra) {4749print"<div class=\"page_nav\">\n";4750print"$extra\n";4751print"</div>\n";4752}4753}47544755sub git_shortlog_body {4756# uses global variable $project4757my($commitlist,$from,$to,$refs,$extra) =@_;47584759$from=0unlessdefined$from;4760$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);47614762print"<table class=\"shortlog\">\n";4763my$alternate=1;4764for(my$i=$from;$i<=$to;$i++) {4765my%co= %{$commitlist->[$i]};4766my$commit=$co{'id'};4767my$ref= format_ref_marker($refs,$commit);4768if($alternate) {4769print"<tr class=\"dark\">\n";4770}else{4771print"<tr class=\"light\">\n";4772}4773$alternate^=1;4774# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .4775print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4776 format_author_html('td', \%co,10) ."<td>";4777print format_subject_html($co{'title'},$co{'title_short'},4778 href(action=>"commit", hash=>$commit),$ref);4779print"</td>\n".4780"<td class=\"link\">".4781$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".4782$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".4783$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");4784my$snapshot_links= format_snapshot_links($commit);4785if(defined$snapshot_links) {4786print" | ".$snapshot_links;4787}4788print"</td>\n".4789"</tr>\n";4790}4791if(defined$extra) {4792print"<tr>\n".4793"<td colspan=\"4\">$extra</td>\n".4794"</tr>\n";4795}4796print"</table>\n";4797}47984799sub git_history_body {4800# Warning: assumes constant type (blob or tree) during history4801my($commitlist,$from,$to,$refs,$extra,4802$file_name,$file_hash,$ftype) =@_;48034804$from=0unlessdefined$from;4805$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});48064807print"<table class=\"history\">\n";4808my$alternate=1;4809for(my$i=$from;$i<=$to;$i++) {4810my%co= %{$commitlist->[$i]};4811if(!%co) {4812next;4813}4814my$commit=$co{'id'};48154816my$ref= format_ref_marker($refs,$commit);48174818if($alternate) {4819print"<tr class=\"dark\">\n";4820}else{4821print"<tr class=\"light\">\n";4822}4823$alternate^=1;4824print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4825# shortlog: format_author_html('td', \%co, 10)4826 format_author_html('td', \%co,15,3) ."<td>";4827# originally git_history used chop_str($co{'title'}, 50)4828print format_subject_html($co{'title'},$co{'title_short'},4829 href(action=>"commit", hash=>$commit),$ref);4830print"</td>\n".4831"<td class=\"link\">".4832$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".4833$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");48344835if($ftypeeq'blob') {4836my$blob_current=$file_hash;4837my$blob_parent= git_get_hash_by_path($commit,$file_name);4838if(defined$blob_current&&defined$blob_parent&&4839$blob_currentne$blob_parent) {4840print" | ".4841$cgi->a({-href => href(action=>"blobdiff",4842 hash=>$blob_current, hash_parent=>$blob_parent,4843 hash_base=>$hash_base, hash_parent_base=>$commit,4844 file_name=>$file_name)},4845"diff to current");4846}4847}4848print"</td>\n".4849"</tr>\n";4850}4851if(defined$extra) {4852print"<tr>\n".4853"<td colspan=\"4\">$extra</td>\n".4854"</tr>\n";4855}4856print"</table>\n";4857}48584859sub git_tags_body {4860# uses global variable $project4861my($taglist,$from,$to,$extra) =@_;4862$from=0unlessdefined$from;4863$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);48644865print"<table class=\"tags\">\n";4866my$alternate=1;4867for(my$i=$from;$i<=$to;$i++) {4868my$entry=$taglist->[$i];4869my%tag=%$entry;4870my$comment=$tag{'subject'};4871my$comment_short;4872if(defined$comment) {4873$comment_short= chop_str($comment,30,5);4874}4875if($alternate) {4876print"<tr class=\"dark\">\n";4877}else{4878print"<tr class=\"light\">\n";4879}4880$alternate^=1;4881if(defined$tag{'age'}) {4882print"<td><i>$tag{'age'}</i></td>\n";4883}else{4884print"<td></td>\n";4885}4886print"<td>".4887$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),4888-class=>"list name"}, esc_html($tag{'name'})) .4889"</td>\n".4890"<td>";4891if(defined$comment) {4892print format_subject_html($comment,$comment_short,4893 href(action=>"tag", hash=>$tag{'id'}));4894}4895print"</td>\n".4896"<td class=\"selflink\">";4897if($tag{'type'}eq"tag") {4898print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");4899}else{4900print" ";4901}4902print"</td>\n".4903"<td class=\"link\">"." | ".4904$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});4905if($tag{'reftype'}eq"commit") {4906print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .4907" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");4908}elsif($tag{'reftype'}eq"blob") {4909print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");4910}4911print"</td>\n".4912"</tr>";4913}4914if(defined$extra) {4915print"<tr>\n".4916"<td colspan=\"5\">$extra</td>\n".4917"</tr>\n";4918}4919print"</table>\n";4920}49214922sub git_heads_body {4923# uses global variable $project4924my($headlist,$head,$from,$to,$extra) =@_;4925$from=0unlessdefined$from;4926$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);49274928print"<table class=\"heads\">\n";4929my$alternate=1;4930for(my$i=$from;$i<=$to;$i++) {4931my$entry=$headlist->[$i];4932my%ref=%$entry;4933my$curr=$ref{'id'}eq$head;4934if($alternate) {4935print"<tr class=\"dark\">\n";4936}else{4937print"<tr class=\"light\">\n";4938}4939$alternate^=1;4940print"<td><i>$ref{'age'}</i></td>\n".4941($curr?"<td class=\"current_head\">":"<td>") .4942$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),4943-class=>"list name"},esc_html($ref{'name'})) .4944"</td>\n".4945"<td class=\"link\">".4946$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".4947$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".4948$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})},"tree") .4949"</td>\n".4950"</tr>";4951}4952if(defined$extra) {4953print"<tr>\n".4954"<td colspan=\"3\">$extra</td>\n".4955"</tr>\n";4956}4957print"</table>\n";4958}49594960sub git_search_grep_body {4961my($commitlist,$from,$to,$extra) =@_;4962$from=0unlessdefined$from;4963$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);49644965print"<table class=\"commit_search\">\n";4966my$alternate=1;4967for(my$i=$from;$i<=$to;$i++) {4968my%co= %{$commitlist->[$i]};4969if(!%co) {4970next;4971}4972my$commit=$co{'id'};4973if($alternate) {4974print"<tr class=\"dark\">\n";4975}else{4976print"<tr class=\"light\">\n";4977}4978$alternate^=1;4979print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4980 format_author_html('td', \%co,15,5) .4981"<td>".4982$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),4983-class=>"list subject"},4984 chop_and_escape_str($co{'title'},50) ."<br/>");4985my$comment=$co{'comment'};4986foreachmy$line(@$comment) {4987if($line=~m/^(.*?)($search_regexp)(.*)$/i) {4988my($lead,$match,$trail) = ($1,$2,$3);4989$match= chop_str($match,70,5,'center');4990my$contextlen=int((80-length($match))/2);4991$contextlen=30if($contextlen>30);4992$lead= chop_str($lead,$contextlen,10,'left');4993$trail= chop_str($trail,$contextlen,10,'right');49944995$lead= esc_html($lead);4996$match= esc_html($match);4997$trail= esc_html($trail);49984999print"$lead<span class=\"match\">$match</span>$trail<br />";5000}5001}5002print"</td>\n".5003"<td class=\"link\">".5004$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .5005" | ".5006$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .5007" | ".5008$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");5009print"</td>\n".5010"</tr>\n";5011}5012if(defined$extra) {5013print"<tr>\n".5014"<td colspan=\"3\">$extra</td>\n".5015"</tr>\n";5016}5017print"</table>\n";5018}50195020## ======================================================================5021## ======================================================================5022## actions50235024sub git_project_list {5025my$order=$input_params{'order'};5026if(defined$order&&$order!~m/none|project|descr|owner|age/) {5027 die_error(400,"Unknown order parameter");5028}50295030my@list= git_get_projects_list();5031if(!@list) {5032 die_error(404,"No projects found");5033}50345035 git_header_html();5036if(defined$home_text&& -f $home_text) {5037print"<div class=\"index_include\">\n";5038 insert_file($home_text);5039print"</div>\n";5040}5041print$cgi->startform(-method=>"get") .5042"<p class=\"projsearch\">Search:\n".5043$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".5044"</p>".5045$cgi->end_form() ."\n";5046 git_project_list_body(\@list,$order);5047 git_footer_html();5048}50495050sub git_forks {5051my$order=$input_params{'order'};5052if(defined$order&&$order!~m/none|project|descr|owner|age/) {5053 die_error(400,"Unknown order parameter");5054}50555056my@list= git_get_projects_list($project);5057if(!@list) {5058 die_error(404,"No forks found");5059}50605061 git_header_html();5062 git_print_page_nav('','');5063 git_print_header_div('summary',"$projectforks");5064 git_project_list_body(\@list,$order);5065 git_footer_html();5066}50675068sub git_project_index {5069my@projects= git_get_projects_list($project);50705071print$cgi->header(5072-type =>'text/plain',5073-charset =>'utf-8',5074-content_disposition =>'inline; filename="index.aux"');50755076foreachmy$pr(@projects) {5077if(!exists$pr->{'owner'}) {5078$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");5079}50805081my($path,$owner) = ($pr->{'path'},$pr->{'owner'});5082# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '5083$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5084$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5085$path=~s/ /\+/g;5086$owner=~s/ /\+/g;50875088print"$path$owner\n";5089}5090}50915092sub git_summary {5093my$descr= git_get_project_description($project) ||"none";5094my%co= parse_commit("HEAD");5095my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();5096my$head=$co{'id'};50975098my$owner= git_get_project_owner($project);50995100my$refs= git_get_references();5101# These get_*_list functions return one more to allow us to see if5102# there are more ...5103my@taglist= git_get_tags_list(16);5104my@headlist= git_get_heads_list(16);5105my@forklist;5106my$check_forks= gitweb_check_feature('forks');51075108if($check_forks) {5109@forklist= git_get_projects_list($project);5110}51115112 git_header_html();5113 git_print_page_nav('summary','',$head);51145115print"<div class=\"title\"> </div>\n";5116print"<table class=\"projects_list\">\n".5117"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".5118"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";5119if(defined$cd{'rfc2822'}) {5120print"<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";5121}51225123# use per project git URL list in $projectroot/$project/cloneurl5124# or make project git URL from git base URL and project name5125my$url_tag="URL";5126my@url_list= git_get_project_url_list($project);5127@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;5128foreachmy$git_url(@url_list) {5129next unless$git_url;5130print"<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";5131$url_tag="";5132}51335134# Tag cloud5135my$show_ctags= gitweb_check_feature('ctags');5136if($show_ctags) {5137my$ctags= git_get_project_ctags($project);5138my$cloud= git_populate_project_tagcloud($ctags);5139print"<tr id=\"metadata_ctags\"><td>Content tags:<br />";5140print"</td>\n<td>"unless%$ctags;5141print"<form action=\"$show_ctags\"method=\"post\"><input type=\"hidden\"name=\"p\"value=\"$project\"/>Add: <input type=\"text\"name=\"t\"size=\"8\"/></form>";5142print"</td>\n<td>"if%$ctags;5143print git_show_project_tagcloud($cloud,48);5144print"</td></tr>";5145}51465147print"</table>\n";51485149# If XSS prevention is on, we don't include README.html.5150# TODO: Allow a readme in some safe format.5151if(!$prevent_xss&& -s "$projectroot/$project/README.html") {5152print"<div class=\"title\">readme</div>\n".5153"<div class=\"readme\">\n";5154 insert_file("$projectroot/$project/README.html");5155print"\n</div>\n";# class="readme"5156}51575158# we need to request one more than 16 (0..15) to check if5159# those 16 are all5160my@commitlist=$head? parse_commits($head,17) : ();5161if(@commitlist) {5162 git_print_header_div('shortlog');5163 git_shortlog_body(\@commitlist,0,15,$refs,5164$#commitlist<=15?undef:5165$cgi->a({-href => href(action=>"shortlog")},"..."));5166}51675168if(@taglist) {5169 git_print_header_div('tags');5170 git_tags_body(\@taglist,0,15,5171$#taglist<=15?undef:5172$cgi->a({-href => href(action=>"tags")},"..."));5173}51745175if(@headlist) {5176 git_print_header_div('heads');5177 git_heads_body(\@headlist,$head,0,15,5178$#headlist<=15?undef:5179$cgi->a({-href => href(action=>"heads")},"..."));5180}51815182if(@forklist) {5183 git_print_header_div('forks');5184 git_project_list_body(\@forklist,'age',0,15,5185$#forklist<=15?undef:5186$cgi->a({-href => href(action=>"forks")},"..."),5187'no_header');5188}51895190 git_footer_html();5191}51925193sub git_tag {5194my%tag= parse_tag($hash);51955196if(!%tag) {5197 die_error(404,"Unknown tag object");5198}51995200my$head= git_get_head_hash($project);5201 git_header_html();5202 git_print_page_nav('','',$head,undef,$head);5203 git_print_header_div('commit', esc_html($tag{'name'}),$hash);5204print"<div class=\"title_text\">\n".5205"<table class=\"object_header\">\n".5206"<tr>\n".5207"<td>object</td>\n".5208"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5209$tag{'object'}) ."</td>\n".5210"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5211$tag{'type'}) ."</td>\n".5212"</tr>\n";5213if(defined($tag{'author'})) {5214 git_print_authorship_rows(\%tag,'author');5215}5216print"</table>\n\n".5217"</div>\n";5218print"<div class=\"page_body\">";5219my$comment=$tag{'comment'};5220foreachmy$line(@$comment) {5221chomp$line;5222print esc_html($line, -nbsp=>1) ."<br/>\n";5223}5224print"</div>\n";5225 git_footer_html();5226}52275228sub git_blame_common {5229my$format=shift||'porcelain';5230if($formateq'porcelain'&&$cgi->param('js')) {5231$format='incremental';5232$action='blame_incremental';# for page title etc5233}52345235# permissions5236 gitweb_check_feature('blame')5237or die_error(403,"Blame view not allowed");52385239# error checking5240 die_error(400,"No file name given")unless$file_name;5241$hash_base||= git_get_head_hash($project);5242 die_error(404,"Couldn't find base commit")unless$hash_base;5243my%co= parse_commit($hash_base)5244or die_error(404,"Commit not found");5245my$ftype="blob";5246if(!defined$hash) {5247$hash= git_get_hash_by_path($hash_base,$file_name,"blob")5248or die_error(404,"Error looking up file");5249}else{5250$ftype= git_get_type($hash);5251if($ftype!~"blob") {5252 die_error(400,"Object is not a blob");5253}5254}52555256my$fd;5257if($formateq'incremental') {5258# get file contents (as base)5259open$fd,"-|", git_cmd(),'cat-file','blob',$hash5260or die_error(500,"Open git-cat-file failed");5261}elsif($formateq'data') {5262# run git-blame --incremental5263open$fd,"-|", git_cmd(),"blame","--incremental",5264$hash_base,"--",$file_name5265or die_error(500,"Open git-blame --incremental failed");5266}else{5267# run git-blame --porcelain5268open$fd,"-|", git_cmd(),"blame",'-p',5269$hash_base,'--',$file_name5270or die_error(500,"Open git-blame --porcelain failed");5271}52725273# incremental blame data returns early5274if($formateq'data') {5275print$cgi->header(5276-type=>"text/plain", -charset =>"utf-8",5277-status=>"200 OK");5278local$| =1;# output autoflush5279printwhile<$fd>;5280close$fd5281or print"ERROR$!\n";52825283print'END';5284if(defined$t0&& gitweb_check_feature('timed')) {5285print' '.5286 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).5287' '.$number_of_git_cmds;5288}5289print"\n";52905291return;5292}52935294# page header5295 git_header_html();5296my$formats_nav=5297$cgi->a({-href => href(action=>"blob", -replay=>1)},5298"blob") .5299" | ";5300if($formateq'incremental') {5301$formats_nav.=5302$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},5303"blame") ." (non-incremental)";5304}else{5305$formats_nav.=5306$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},5307"blame") ." (incremental)";5308}5309$formats_nav.=5310" | ".5311$cgi->a({-href => href(action=>"history", -replay=>1)},5312"history") .5313" | ".5314$cgi->a({-href => href(action=>$action, file_name=>$file_name)},5315"HEAD");5316 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5317 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5318 git_print_page_path($file_name,$ftype,$hash_base);53195320# page body5321if($formateq'incremental') {5322print"<noscript>\n<div class=\"error\"><center><b>\n".5323"This page requires JavaScript to run.\nUse ".5324$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},5325'this page').5326" instead.\n".5327"</b></center></div>\n</noscript>\n";53285329print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;5330}53315332print qq!<div class="page_body">\n!;5333print qq!<div id="progress_info">.../ ...</div>\n!5334if($formateq'incremental');5335print qq!<table id="blame_table"class="blame" width="100%">\n!.5336#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.5337 qq!<thead>\n!.5338 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.5339 qq!</thead>\n!.5340 qq!<tbody>\n!;53415342my@rev_color=qw(light dark);5343my$num_colors=scalar(@rev_color);5344my$current_color=0;53455346if($formateq'incremental') {5347my$color_class=$rev_color[$current_color];53485349#contents of a file5350my$linenr=0;5351 LINE:5352while(my$line= <$fd>) {5353chomp$line;5354$linenr++;53555356print qq!<tr id="l$linenr"class="$color_class">!.5357 qq!<td class="sha1"><a href=""> </a></td>!.5358 qq!<td class="linenr">!.5359 qq!<a class="linenr" href="">$linenr</a></td>!;5360print qq!<td class="pre">! . esc_html($line) ."</td>\n";5361print qq!</tr>\n!;5362}53635364}else{# porcelain, i.e. ordinary blame5365my%metainfo= ();# saves information about commits53665367# blame data5368 LINE:5369while(my$line= <$fd>) {5370chomp$line;5371# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]5372# no <lines in group> for subsequent lines in group of lines5373my($full_rev,$orig_lineno,$lineno,$group_size) =5374($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);5375if(!exists$metainfo{$full_rev}) {5376$metainfo{$full_rev} = {'nprevious'=>0};5377}5378my$meta=$metainfo{$full_rev};5379my$data;5380while($data= <$fd>) {5381chomp$data;5382last if($data=~s/^\t//);# contents of line5383if($data=~/^(\S+)(?: (.*))?$/) {5384$meta->{$1} =$2unlessexists$meta->{$1};5385}5386if($data=~/^previous /) {5387$meta->{'nprevious'}++;5388}5389}5390my$short_rev=substr($full_rev,0,8);5391my$author=$meta->{'author'};5392my%date=5393 parse_date($meta->{'author-time'},$meta->{'author-tz'});5394my$date=$date{'iso-tz'};5395if($group_size) {5396$current_color= ($current_color+1) %$num_colors;5397}5398my$tr_class=$rev_color[$current_color];5399$tr_class.=' boundary'if(exists$meta->{'boundary'});5400$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);5401$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);5402print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";5403if($group_size) {5404print"<td class=\"sha1\"";5405print" title=\"". esc_html($author) .",$date\"";5406print" rowspan=\"$group_size\""if($group_size>1);5407print">";5408print$cgi->a({-href => href(action=>"commit",5409 hash=>$full_rev,5410 file_name=>$file_name)},5411 esc_html($short_rev));5412if($group_size>=2) {5413my@author_initials= ($author=~/\b([[:upper:]])\B/g);5414if(@author_initials) {5415print"<br />".5416 esc_html(join('',@author_initials));5417# or join('.', ...)5418}5419}5420print"</td>\n";5421}5422# 'previous' <sha1 of parent commit> <filename at commit>5423if(exists$meta->{'previous'} &&5424$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {5425$meta->{'parent'} =$1;5426$meta->{'file_parent'} = unquote($2);5427}5428my$linenr_commit=5429exists($meta->{'parent'}) ?5430$meta->{'parent'} :$full_rev;5431my$linenr_filename=5432exists($meta->{'file_parent'}) ?5433$meta->{'file_parent'} : unquote($meta->{'filename'});5434my$blamed= href(action =>'blame',5435 file_name =>$linenr_filename,5436 hash_base =>$linenr_commit);5437print"<td class=\"linenr\">";5438print$cgi->a({ -href =>"$blamed#l$orig_lineno",5439-class=>"linenr"},5440 esc_html($lineno));5441print"</td>";5442print"<td class=\"pre\">". esc_html($data) ."</td>\n";5443print"</tr>\n";5444}# end while54455446}54475448# footer5449print"</tbody>\n".5450"</table>\n";# class="blame"5451print"</div>\n";# class="blame_body"5452close$fd5453or print"Reading blob failed\n";54545455 git_footer_html();5456}54575458sub git_blame {5459 git_blame_common();5460}54615462sub git_blame_incremental {5463 git_blame_common('incremental');5464}54655466sub git_blame_data {5467 git_blame_common('data');5468}54695470sub git_tags {5471my$head= git_get_head_hash($project);5472 git_header_html();5473 git_print_page_nav('','',$head,undef,$head);5474 git_print_header_div('summary',$project);54755476my@tagslist= git_get_tags_list();5477if(@tagslist) {5478 git_tags_body(\@tagslist);5479}5480 git_footer_html();5481}54825483sub git_heads {5484my$head= git_get_head_hash($project);5485 git_header_html();5486 git_print_page_nav('','',$head,undef,$head);5487 git_print_header_div('summary',$project);54885489my@headslist= git_get_heads_list();5490if(@headslist) {5491 git_heads_body(\@headslist,$head);5492}5493 git_footer_html();5494}54955496sub git_blob_plain {5497my$type=shift;5498my$expires;54995500if(!defined$hash) {5501if(defined$file_name) {5502my$base=$hash_base|| git_get_head_hash($project);5503$hash= git_get_hash_by_path($base,$file_name,"blob")5504or die_error(404,"Cannot find file");5505}else{5506 die_error(400,"No file name defined");5507}5508}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {5509# blobs defined by non-textual hash id's can be cached5510$expires="+1d";5511}55125513open my$fd,"-|", git_cmd(),"cat-file","blob",$hash5514or die_error(500,"Open git-cat-file blob '$hash' failed");55155516# content-type (can include charset)5517$type= blob_contenttype($fd,$file_name,$type);55185519# "save as" filename, even when no $file_name is given5520my$save_as="$hash";5521if(defined$file_name) {5522$save_as=$file_name;5523}elsif($type=~m/^text\//) {5524$save_as.='.txt';5525}55265527# With XSS prevention on, blobs of all types except a few known safe5528# ones are served with "Content-Disposition: attachment" to make sure5529# they don't run in our security domain. For certain image types,5530# blob view writes an <img> tag referring to blob_plain view, and we5531# want to be sure not to break that by serving the image as an5532# attachment (though Firefox 3 doesn't seem to care).5533my$sandbox=$prevent_xss&&5534$type!~m!^(?:text/plain|image/(?:gif|png|jpeg))$!;55355536print$cgi->header(5537-type =>$type,5538-expires =>$expires,5539-content_disposition =>5540($sandbox?'attachment':'inline')5541.'; filename="'.$save_as.'"');5542local$/=undef;5543binmode STDOUT,':raw';5544print<$fd>;5545binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi5546close$fd;5547}55485549sub git_blob {5550my$expires;55515552if(!defined$hash) {5553if(defined$file_name) {5554my$base=$hash_base|| git_get_head_hash($project);5555$hash= git_get_hash_by_path($base,$file_name,"blob")5556or die_error(404,"Cannot find file");5557}else{5558 die_error(400,"No file name defined");5559}5560}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {5561# blobs defined by non-textual hash id's can be cached5562$expires="+1d";5563}55645565my$have_blame= gitweb_check_feature('blame');5566open my$fd,"-|", git_cmd(),"cat-file","blob",$hash5567or die_error(500,"Couldn't cat$file_name,$hash");5568my$mimetype= blob_mimetype($fd,$file_name);5569# use 'blob_plain' (aka 'raw') view for files that cannot be displayed5570if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {5571close$fd;5572return git_blob_plain($mimetype);5573}5574# we can have blame only for text/* mimetype5575$have_blame&&= ($mimetype=~m!^text/!);55765577my$highlight= gitweb_check_feature('highlight');5578my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);5579$fd= run_highlighter($fd,$highlight,$syntax)5580if$syntax;55815582 git_header_html(undef,$expires);5583my$formats_nav='';5584if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5585if(defined$file_name) {5586if($have_blame) {5587$formats_nav.=5588$cgi->a({-href => href(action=>"blame", -replay=>1)},5589"blame") .5590" | ";5591}5592$formats_nav.=5593$cgi->a({-href => href(action=>"history", -replay=>1)},5594"history") .5595" | ".5596$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},5597"raw") .5598" | ".5599$cgi->a({-href => href(action=>"blob",5600 hash_base=>"HEAD", file_name=>$file_name)},5601"HEAD");5602}else{5603$formats_nav.=5604$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},5605"raw");5606}5607 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5608 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5609}else{5610print"<div class=\"page_nav\">\n".5611"<br/><br/></div>\n".5612"<div class=\"title\">$hash</div>\n";5613}5614 git_print_page_path($file_name,"blob",$hash_base);5615print"<div class=\"page_body\">\n";5616if($mimetype=~m!^image/!) {5617print qq!<img type="$mimetype"!;5618if($file_name) {5619print qq! alt="$file_name" title="$file_name"!;5620}5621print qq! src="! .5622 href(action=>"blob_plain", hash=>$hash,5623 hash_base=>$hash_base, file_name=>$file_name) .5624 qq!"/>\n!;5625}else{5626my$nr;5627while(my$line= <$fd>) {5628chomp$line;5629$nr++;5630$line= untabify($line);5631printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,5632$nr, href(-replay =>1),$nr,$nr,$syntax?$line: esc_html($line, -nbsp=>1);5633}5634}5635close$fd5636or print"Reading blob failed.\n";5637print"</div>";5638 git_footer_html();5639}56405641sub git_tree {5642if(!defined$hash_base) {5643$hash_base="HEAD";5644}5645if(!defined$hash) {5646if(defined$file_name) {5647$hash= git_get_hash_by_path($hash_base,$file_name,"tree");5648}else{5649$hash=$hash_base;5650}5651}5652 die_error(404,"No such tree")unlessdefined($hash);56535654my$show_sizes= gitweb_check_feature('show-sizes');5655my$have_blame= gitweb_check_feature('blame');56565657my@entries= ();5658{5659local$/="\0";5660open my$fd,"-|", git_cmd(),"ls-tree",'-z',5661($show_sizes?'-l': ()),@extra_options,$hash5662or die_error(500,"Open git-ls-tree failed");5663@entries=map{chomp;$_} <$fd>;5664close$fd5665or die_error(404,"Reading tree failed");5666}56675668my$refs= git_get_references();5669my$ref= format_ref_marker($refs,$hash_base);5670 git_header_html();5671my$basedir='';5672if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5673my@views_nav= ();5674if(defined$file_name) {5675push@views_nav,5676$cgi->a({-href => href(action=>"history", -replay=>1)},5677"history"),5678$cgi->a({-href => href(action=>"tree",5679 hash_base=>"HEAD", file_name=>$file_name)},5680"HEAD"),5681}5682my$snapshot_links= format_snapshot_links($hash);5683if(defined$snapshot_links) {5684# FIXME: Should be available when we have no hash base as well.5685push@views_nav,$snapshot_links;5686}5687 git_print_page_nav('tree','',$hash_base,undef,undef,5688join(' | ',@views_nav));5689 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);5690}else{5691undef$hash_base;5692print"<div class=\"page_nav\">\n";5693print"<br/><br/></div>\n";5694print"<div class=\"title\">$hash</div>\n";5695}5696if(defined$file_name) {5697$basedir=$file_name;5698if($basedirne''&&substr($basedir, -1)ne'/') {5699$basedir.='/';5700}5701 git_print_page_path($file_name,'tree',$hash_base);5702}5703print"<div class=\"page_body\">\n";5704print"<table class=\"tree\">\n";5705my$alternate=1;5706# '..' (top directory) link if possible5707if(defined$hash_base&&5708defined$file_name&&$file_name=~m![^/]+$!) {5709if($alternate) {5710print"<tr class=\"dark\">\n";5711}else{5712print"<tr class=\"light\">\n";5713}5714$alternate^=1;57155716my$up=$file_name;5717$up=~s!/?[^/]+$!!;5718undef$upunless$up;5719# based on git_print_tree_entry5720print'<td class="mode">'. mode_str('040000') ."</td>\n";5721print'<td class="size"> </td>'."\n"if$show_sizes;5722print'<td class="list">';5723print$cgi->a({-href => href(action=>"tree",5724 hash_base=>$hash_base,5725 file_name=>$up)},5726"..");5727print"</td>\n";5728print"<td class=\"link\"></td>\n";57295730print"</tr>\n";5731}5732foreachmy$line(@entries) {5733my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);57345735if($alternate) {5736print"<tr class=\"dark\">\n";5737}else{5738print"<tr class=\"light\">\n";5739}5740$alternate^=1;57415742 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);57435744print"</tr>\n";5745}5746print"</table>\n".5747"</div>";5748 git_footer_html();5749}57505751sub snapshot_name {5752my($project,$hash) =@_;57535754# path/to/project.git -> project5755# path/to/project/.git -> project5756my$name= to_utf8($project);5757$name=~ s,([^/])/*\.git$,$1,;5758$name= basename($name);5759# sanitize name5760$name=~s/[[:cntrl:]]/?/g;57615762my$ver=$hash;5763if($hash=~/^[0-9a-fA-F]+$/) {5764# shorten SHA-1 hash5765my$full_hash= git_get_full_hash($project,$hash);5766if($full_hash=~/^$hash/&&length($hash) >7) {5767$ver= git_get_short_hash($project,$hash);5768}5769}elsif($hash=~m!^refs/tags/(.*)$!) {5770# tags don't need shortened SHA-1 hash5771$ver=$1;5772}else{5773# branches and other need shortened SHA-1 hash5774if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {5775$ver=$1;5776}5777$ver.='-'. git_get_short_hash($project,$hash);5778}5779# in case of hierarchical branch names5780$ver=~s!/!.!g;57815782# name = project-version_string5783$name="$name-$ver";57845785returnwantarray? ($name,$name) :$name;5786}57875788sub git_snapshot {5789my$format=$input_params{'snapshot_format'};5790if(!@snapshot_fmts) {5791 die_error(403,"Snapshots not allowed");5792}5793# default to first supported snapshot format5794$format||=$snapshot_fmts[0];5795if($format!~m/^[a-z0-9]+$/) {5796 die_error(400,"Invalid snapshot format parameter");5797}elsif(!exists($known_snapshot_formats{$format})) {5798 die_error(400,"Unknown snapshot format");5799}elsif($known_snapshot_formats{$format}{'disabled'}) {5800 die_error(403,"Snapshot format not allowed");5801}elsif(!grep($_eq$format,@snapshot_fmts)) {5802 die_error(403,"Unsupported snapshot format");5803}58045805my$type= git_get_type("$hash^{}");5806if(!$type) {5807 die_error(404,'Object does not exist');5808}elsif($typeeq'blob') {5809 die_error(400,'Object is not a tree-ish');5810}58115812my($name,$prefix) = snapshot_name($project,$hash);5813my$filename="$name$known_snapshot_formats{$format}{'suffix'}";5814my$cmd= quote_command(5815 git_cmd(),'archive',5816"--format=$known_snapshot_formats{$format}{'format'}",5817"--prefix=$prefix/",$hash);5818if(exists$known_snapshot_formats{$format}{'compressor'}) {5819$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});5820}58215822$filename=~s/(["\\])/\\$1/g;5823print$cgi->header(5824-type =>$known_snapshot_formats{$format}{'type'},5825-content_disposition =>'inline; filename="'.$filename.'"',5826-status =>'200 OK');58275828open my$fd,"-|",$cmd5829or die_error(500,"Execute git-archive failed");5830binmode STDOUT,':raw';5831print<$fd>;5832binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi5833close$fd;5834}58355836sub git_log_generic {5837my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;58385839my$head= git_get_head_hash($project);5840if(!defined$base) {5841$base=$head;5842}5843if(!defined$page) {5844$page=0;5845}5846my$refs= git_get_references();58475848my$commit_hash=$base;5849if(defined$parent) {5850$commit_hash="$parent..$base";5851}5852my@commitlist=5853 parse_commits($commit_hash,101, (100*$page),5854defined$file_name? ($file_name,"--full-history") : ());58555856my$ftype;5857if(!defined$file_hash&&defined$file_name) {5858# some commits could have deleted file in question,5859# and not have it in tree, but one of them has to have it5860for(my$i=0;$i<@commitlist;$i++) {5861$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);5862last ifdefined$file_hash;5863}5864}5865if(defined$file_hash) {5866$ftype= git_get_type($file_hash);5867}5868if(defined$file_name&& !defined$ftype) {5869 die_error(500,"Unknown type of object");5870}5871my%co;5872if(defined$file_name) {5873%co= parse_commit($base)5874or die_error(404,"Unknown commit object");5875}587658775878my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);5879my$next_link='';5880if($#commitlist>=100) {5881$next_link=5882$cgi->a({-href => href(-replay=>1, page=>$page+1),5883-accesskey =>"n", -title =>"Alt-n"},"next");5884}5885my$patch_max= gitweb_get_feature('patches');5886if($patch_max&& !defined$file_name) {5887if($patch_max<0||@commitlist<=$patch_max) {5888$paging_nav.=" ⋅ ".5889$cgi->a({-href => href(action=>"patches", -replay=>1)},5890"patches");5891}5892}58935894 git_header_html();5895 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);5896if(defined$file_name) {5897 git_print_header_div('commit', esc_html($co{'title'}),$base);5898}else{5899 git_print_header_div('summary',$project)5900}5901 git_print_page_path($file_name,$ftype,$hash_base)5902if(defined$file_name);59035904$body_subr->(\@commitlist,0,99,$refs,$next_link,5905$file_name,$file_hash,$ftype);59065907 git_footer_html();5908}59095910sub git_log {5911 git_log_generic('log', \&git_log_body,5912$hash,$hash_parent);5913}59145915sub git_commit {5916$hash||=$hash_base||"HEAD";5917my%co= parse_commit($hash)5918or die_error(404,"Unknown commit object");59195920my$parent=$co{'parent'};5921my$parents=$co{'parents'};# listref59225923# we need to prepare $formats_nav before any parameter munging5924my$formats_nav;5925if(!defined$parent) {5926# --root commitdiff5927$formats_nav.='(initial)';5928}elsif(@$parents==1) {5929# single parent commit5930$formats_nav.=5931'(parent: '.5932$cgi->a({-href => href(action=>"commit",5933 hash=>$parent)},5934 esc_html(substr($parent,0,7))) .5935')';5936}else{5937# merge commit5938$formats_nav.=5939'(merge: '.5940join(' ',map{5941$cgi->a({-href => href(action=>"commit",5942 hash=>$_)},5943 esc_html(substr($_,0,7)));5944}@$parents) .5945')';5946}5947if(gitweb_check_feature('patches') &&@$parents<=1) {5948$formats_nav.=" | ".5949$cgi->a({-href => href(action=>"patch", -replay=>1)},5950"patch");5951}59525953if(!defined$parent) {5954$parent="--root";5955}5956my@difftree;5957open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",5958@diff_opts,5959(@$parents<=1?$parent:'-c'),5960$hash,"--"5961or die_error(500,"Open git-diff-tree failed");5962@difftree=map{chomp;$_} <$fd>;5963close$fdor die_error(404,"Reading git-diff-tree failed");59645965# non-textual hash id's can be cached5966my$expires;5967if($hash=~m/^[0-9a-fA-F]{40}$/) {5968$expires="+1d";5969}5970my$refs= git_get_references();5971my$ref= format_ref_marker($refs,$co{'id'});59725973 git_header_html(undef,$expires);5974 git_print_page_nav('commit','',5975$hash,$co{'tree'},$hash,5976$formats_nav);59775978if(defined$co{'parent'}) {5979 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);5980}else{5981 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);5982}5983print"<div class=\"title_text\">\n".5984"<table class=\"object_header\">\n";5985 git_print_authorship_rows(\%co);5986print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";5987print"<tr>".5988"<td>tree</td>".5989"<td class=\"sha1\">".5990$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),5991class=>"list"},$co{'tree'}) .5992"</td>".5993"<td class=\"link\">".5994$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},5995"tree");5996my$snapshot_links= format_snapshot_links($hash);5997if(defined$snapshot_links) {5998print" | ".$snapshot_links;5999}6000print"</td>".6001"</tr>\n";60026003foreachmy$par(@$parents) {6004print"<tr>".6005"<td>parent</td>".6006"<td class=\"sha1\">".6007$cgi->a({-href => href(action=>"commit", hash=>$par),6008class=>"list"},$par) .6009"</td>".6010"<td class=\"link\">".6011$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .6012" | ".6013$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .6014"</td>".6015"</tr>\n";6016}6017print"</table>".6018"</div>\n";60196020print"<div class=\"page_body\">\n";6021 git_print_log($co{'comment'});6022print"</div>\n";60236024 git_difftree_body(\@difftree,$hash,@$parents);60256026 git_footer_html();6027}60286029sub git_object {6030# object is defined by:6031# - hash or hash_base alone6032# - hash_base and file_name6033my$type;60346035# - hash or hash_base alone6036if($hash|| ($hash_base&& !defined$file_name)) {6037my$object_id=$hash||$hash_base;60386039open my$fd,"-|", quote_command(6040 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'6041or die_error(404,"Object does not exist");6042$type= <$fd>;6043chomp$type;6044close$fd6045or die_error(404,"Object does not exist");60466047# - hash_base and file_name6048}elsif($hash_base&&defined$file_name) {6049$file_name=~ s,/+$,,;60506051system(git_cmd(),"cat-file",'-e',$hash_base) ==06052or die_error(404,"Base object does not exist");60536054# here errors should not hapen6055open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name6056or die_error(500,"Open git-ls-tree failed");6057my$line= <$fd>;6058close$fd;60596060#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'6061unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {6062 die_error(404,"File or directory for given base does not exist");6063}6064$type=$2;6065$hash=$3;6066}else{6067 die_error(400,"Not enough information to find object");6068}60696070print$cgi->redirect(-uri => href(action=>$type, -full=>1,6071 hash=>$hash, hash_base=>$hash_base,6072 file_name=>$file_name),6073-status =>'302 Found');6074}60756076sub git_blobdiff {6077my$format=shift||'html';60786079my$fd;6080my@difftree;6081my%diffinfo;6082my$expires;60836084# preparing $fd and %diffinfo for git_patchset_body6085# new style URI6086if(defined$hash_base&&defined$hash_parent_base) {6087if(defined$file_name) {6088# read raw output6089open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6090$hash_parent_base,$hash_base,6091"--", (defined$file_parent?$file_parent: ()),$file_name6092or die_error(500,"Open git-diff-tree failed");6093@difftree=map{chomp;$_} <$fd>;6094close$fd6095or die_error(404,"Reading git-diff-tree failed");6096@difftree6097or die_error(404,"Blob diff not found");60986099}elsif(defined$hash&&6100$hash=~/[0-9a-fA-F]{40}/) {6101# try to find filename from $hash61026103# read filtered raw output6104open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6105$hash_parent_base,$hash_base,"--"6106or die_error(500,"Open git-diff-tree failed");6107@difftree=6108# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'6109# $hash == to_id6110grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}6111map{chomp;$_} <$fd>;6112close$fd6113or die_error(404,"Reading git-diff-tree failed");6114@difftree6115or die_error(404,"Blob diff not found");61166117}else{6118 die_error(400,"Missing one of the blob diff parameters");6119}61206121if(@difftree>1) {6122 die_error(400,"Ambiguous blob diff specification");6123}61246125%diffinfo= parse_difftree_raw_line($difftree[0]);6126$file_parent||=$diffinfo{'from_file'} ||$file_name;6127$file_name||=$diffinfo{'to_file'};61286129$hash_parent||=$diffinfo{'from_id'};6130$hash||=$diffinfo{'to_id'};61316132# non-textual hash id's can be cached6133if($hash_base=~m/^[0-9a-fA-F]{40}$/&&6134$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {6135$expires='+1d';6136}61376138# open patch output6139open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6140'-p', ($formateq'html'?"--full-index": ()),6141$hash_parent_base,$hash_base,6142"--", (defined$file_parent?$file_parent: ()),$file_name6143or die_error(500,"Open git-diff-tree failed");6144}61456146# old/legacy style URI -- not generated anymore since 1.4.3.6147if(!%diffinfo) {6148 die_error('404 Not Found',"Missing one of the blob diff parameters")6149}61506151# header6152if($formateq'html') {6153my$formats_nav=6154$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},6155"raw");6156 git_header_html(undef,$expires);6157if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6158 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6159 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6160}else{6161print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";6162print"<div class=\"title\">$hashvs$hash_parent</div>\n";6163}6164if(defined$file_name) {6165 git_print_page_path($file_name,"blob",$hash_base);6166}else{6167print"<div class=\"page_path\"></div>\n";6168}61696170}elsif($formateq'plain') {6171print$cgi->header(6172-type =>'text/plain',6173-charset =>'utf-8',6174-expires =>$expires,6175-content_disposition =>'inline; filename="'."$file_name".'.patch"');61766177print"X-Git-Url: ".$cgi->self_url() ."\n\n";61786179}else{6180 die_error(400,"Unknown blobdiff format");6181}61826183# patch6184if($formateq'html') {6185print"<div class=\"page_body\">\n";61866187 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);6188close$fd;61896190print"</div>\n";# class="page_body"6191 git_footer_html();61926193}else{6194while(my$line= <$fd>) {6195$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;6196$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;61976198print$line;61996200last if$line=~m!^\+\+\+!;6201}6202local$/=undef;6203print<$fd>;6204close$fd;6205}6206}62076208sub git_blobdiff_plain {6209 git_blobdiff('plain');6210}62116212sub git_commitdiff {6213my%params=@_;6214my$format=$params{-format} ||'html';62156216my($patch_max) = gitweb_get_feature('patches');6217if($formateq'patch') {6218 die_error(403,"Patch view not allowed")unless$patch_max;6219}62206221$hash||=$hash_base||"HEAD";6222my%co= parse_commit($hash)6223or die_error(404,"Unknown commit object");62246225# choose format for commitdiff for merge6226if(!defined$hash_parent&& @{$co{'parents'}} >1) {6227$hash_parent='--cc';6228}6229# we need to prepare $formats_nav before almost any parameter munging6230my$formats_nav;6231if($formateq'html') {6232$formats_nav=6233$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},6234"raw");6235if($patch_max&& @{$co{'parents'}} <=1) {6236$formats_nav.=" | ".6237$cgi->a({-href => href(action=>"patch", -replay=>1)},6238"patch");6239}62406241if(defined$hash_parent&&6242$hash_parentne'-c'&&$hash_parentne'--cc') {6243# commitdiff with two commits given6244my$hash_parent_short=$hash_parent;6245if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {6246$hash_parent_short=substr($hash_parent,0,7);6247}6248$formats_nav.=6249' (from';6250for(my$i=0;$i< @{$co{'parents'}};$i++) {6251if($co{'parents'}[$i]eq$hash_parent) {6252$formats_nav.=' parent '. ($i+1);6253last;6254}6255}6256$formats_nav.=': '.6257$cgi->a({-href => href(action=>"commitdiff",6258 hash=>$hash_parent)},6259 esc_html($hash_parent_short)) .6260')';6261}elsif(!$co{'parent'}) {6262# --root commitdiff6263$formats_nav.=' (initial)';6264}elsif(scalar@{$co{'parents'}} ==1) {6265# single parent commit6266$formats_nav.=6267' (parent: '.6268$cgi->a({-href => href(action=>"commitdiff",6269 hash=>$co{'parent'})},6270 esc_html(substr($co{'parent'},0,7))) .6271')';6272}else{6273# merge commit6274if($hash_parenteq'--cc') {6275$formats_nav.=' | '.6276$cgi->a({-href => href(action=>"commitdiff",6277 hash=>$hash, hash_parent=>'-c')},6278'combined');6279}else{# $hash_parent eq '-c'6280$formats_nav.=' | '.6281$cgi->a({-href => href(action=>"commitdiff",6282 hash=>$hash, hash_parent=>'--cc')},6283'compact');6284}6285$formats_nav.=6286' (merge: '.6287join(' ',map{6288$cgi->a({-href => href(action=>"commitdiff",6289 hash=>$_)},6290 esc_html(substr($_,0,7)));6291} @{$co{'parents'}} ) .6292')';6293}6294}62956296my$hash_parent_param=$hash_parent;6297if(!defined$hash_parent_param) {6298# --cc for multiple parents, --root for parentless6299$hash_parent_param=6300@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';6301}63026303# read commitdiff6304my$fd;6305my@difftree;6306if($formateq'html') {6307open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6308"--no-commit-id","--patch-with-raw","--full-index",6309$hash_parent_param,$hash,"--"6310or die_error(500,"Open git-diff-tree failed");63116312while(my$line= <$fd>) {6313chomp$line;6314# empty line ends raw part of diff-tree output6315last unless$line;6316push@difftree,scalar parse_difftree_raw_line($line);6317}63186319}elsif($formateq'plain') {6320open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6321'-p',$hash_parent_param,$hash,"--"6322or die_error(500,"Open git-diff-tree failed");6323}elsif($formateq'patch') {6324# For commit ranges, we limit the output to the number of6325# patches specified in the 'patches' feature.6326# For single commits, we limit the output to a single patch,6327# diverging from the git-format-patch default.6328my@commit_spec= ();6329if($hash_parent) {6330if($patch_max>0) {6331push@commit_spec,"-$patch_max";6332}6333push@commit_spec,'-n',"$hash_parent..$hash";6334}else{6335if($params{-single}) {6336push@commit_spec,'-1';6337}else{6338if($patch_max>0) {6339push@commit_spec,"-$patch_max";6340}6341push@commit_spec,"-n";6342}6343push@commit_spec,'--root',$hash;6344}6345open$fd,"-|", git_cmd(),"format-patch",@diff_opts,6346'--encoding=utf8','--stdout',@commit_spec6347or die_error(500,"Open git-format-patch failed");6348}else{6349 die_error(400,"Unknown commitdiff format");6350}63516352# non-textual hash id's can be cached6353my$expires;6354if($hash=~m/^[0-9a-fA-F]{40}$/) {6355$expires="+1d";6356}63576358# write commit message6359if($formateq'html') {6360my$refs= git_get_references();6361my$ref= format_ref_marker($refs,$co{'id'});63626363 git_header_html(undef,$expires);6364 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);6365 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);6366print"<div class=\"title_text\">\n".6367"<table class=\"object_header\">\n";6368 git_print_authorship_rows(\%co);6369print"</table>".6370"</div>\n";6371print"<div class=\"page_body\">\n";6372if(@{$co{'comment'}} >1) {6373print"<div class=\"log\">\n";6374 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);6375print"</div>\n";# class="log"6376}63776378}elsif($formateq'plain') {6379my$refs= git_get_references("tags");6380my$tagname= git_get_rev_name_tags($hash);6381my$filename= basename($project) ."-$hash.patch";63826383print$cgi->header(6384-type =>'text/plain',6385-charset =>'utf-8',6386-expires =>$expires,6387-content_disposition =>'inline; filename="'."$filename".'"');6388my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});6389print"From: ". to_utf8($co{'author'}) ."\n";6390print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";6391print"Subject: ". to_utf8($co{'title'}) ."\n";63926393print"X-Git-Tag:$tagname\n"if$tagname;6394print"X-Git-Url: ".$cgi->self_url() ."\n\n";63956396foreachmy$line(@{$co{'comment'}}) {6397print to_utf8($line) ."\n";6398}6399print"---\n\n";6400}elsif($formateq'patch') {6401my$filename= basename($project) ."-$hash.patch";64026403print$cgi->header(6404-type =>'text/plain',6405-charset =>'utf-8',6406-expires =>$expires,6407-content_disposition =>'inline; filename="'."$filename".'"');6408}64096410# write patch6411if($formateq'html') {6412my$use_parents= !defined$hash_parent||6413$hash_parenteq'-c'||$hash_parenteq'--cc';6414 git_difftree_body(\@difftree,$hash,6415$use_parents? @{$co{'parents'}} :$hash_parent);6416print"<br/>\n";64176418 git_patchset_body($fd, \@difftree,$hash,6419$use_parents? @{$co{'parents'}} :$hash_parent);6420close$fd;6421print"</div>\n";# class="page_body"6422 git_footer_html();64236424}elsif($formateq'plain') {6425local$/=undef;6426print<$fd>;6427close$fd6428or print"Reading git-diff-tree failed\n";6429}elsif($formateq'patch') {6430local$/=undef;6431print<$fd>;6432close$fd6433or print"Reading git-format-patch failed\n";6434}6435}64366437sub git_commitdiff_plain {6438 git_commitdiff(-format =>'plain');6439}64406441# format-patch-style patches6442sub git_patch {6443 git_commitdiff(-format =>'patch', -single =>1);6444}64456446sub git_patches {6447 git_commitdiff(-format =>'patch');6448}64496450sub git_history {6451 git_log_generic('history', \&git_history_body,6452$hash_base,$hash_parent_base,6453$file_name,$hash);6454}64556456sub git_search {6457 gitweb_check_feature('search')or die_error(403,"Search is disabled");6458if(!defined$searchtext) {6459 die_error(400,"Text field is empty");6460}6461if(!defined$hash) {6462$hash= git_get_head_hash($project);6463}6464my%co= parse_commit($hash);6465if(!%co) {6466 die_error(404,"Unknown commit object");6467}6468if(!defined$page) {6469$page=0;6470}64716472$searchtype||='commit';6473if($searchtypeeq'pickaxe') {6474# pickaxe may take all resources of your box and run for several minutes6475# with every query - so decide by yourself how public you make this feature6476 gitweb_check_feature('pickaxe')6477or die_error(403,"Pickaxe is disabled");6478}6479if($searchtypeeq'grep') {6480 gitweb_check_feature('grep')6481or die_error(403,"Grep is disabled");6482}64836484 git_header_html();64856486if($searchtypeeq'commit'or$searchtypeeq'author'or$searchtypeeq'committer') {6487my$greptype;6488if($searchtypeeq'commit') {6489$greptype="--grep=";6490}elsif($searchtypeeq'author') {6491$greptype="--author=";6492}elsif($searchtypeeq'committer') {6493$greptype="--committer=";6494}6495$greptype.=$searchtext;6496my@commitlist= parse_commits($hash,101, (100*$page),undef,6497$greptype,'--regexp-ignore-case',6498$search_use_regexp?'--extended-regexp':'--fixed-strings');64996500my$paging_nav='';6501if($page>0) {6502$paging_nav.=6503$cgi->a({-href => href(action=>"search", hash=>$hash,6504 searchtext=>$searchtext,6505 searchtype=>$searchtype)},6506"first");6507$paging_nav.=" ⋅ ".6508$cgi->a({-href => href(-replay=>1, page=>$page-1),6509-accesskey =>"p", -title =>"Alt-p"},"prev");6510}else{6511$paging_nav.="first";6512$paging_nav.=" ⋅ prev";6513}6514my$next_link='';6515if($#commitlist>=100) {6516$next_link=6517$cgi->a({-href => href(-replay=>1, page=>$page+1),6518-accesskey =>"n", -title =>"Alt-n"},"next");6519$paging_nav.=" ⋅$next_link";6520}else{6521$paging_nav.=" ⋅ next";6522}65236524 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);6525 git_print_header_div('commit', esc_html($co{'title'}),$hash);6526if($page==0&& !@commitlist) {6527print"<p>No match.</p>\n";6528}else{6529 git_search_grep_body(\@commitlist,0,99,$next_link);6530}6531}65326533if($searchtypeeq'pickaxe') {6534 git_print_page_nav('','',$hash,$co{'tree'},$hash);6535 git_print_header_div('commit', esc_html($co{'title'}),$hash);65366537print"<table class=\"pickaxe search\">\n";6538my$alternate=1;6539local$/="\n";6540open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,6541'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",6542($search_use_regexp?'--pickaxe-regex': ());6543undef%co;6544my@files;6545while(my$line= <$fd>) {6546chomp$line;6547next unless$line;65486549my%set= parse_difftree_raw_line($line);6550if(defined$set{'commit'}) {6551# finish previous commit6552if(%co) {6553print"</td>\n".6554"<td class=\"link\">".6555$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6556" | ".6557$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6558print"</td>\n".6559"</tr>\n";6560}65616562if($alternate) {6563print"<tr class=\"dark\">\n";6564}else{6565print"<tr class=\"light\">\n";6566}6567$alternate^=1;6568%co= parse_commit($set{'commit'});6569my$author= chop_and_escape_str($co{'author_name'},15,5);6570print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6571"<td><i>$author</i></td>\n".6572"<td>".6573$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6574-class=>"list subject"},6575 chop_and_escape_str($co{'title'},50) ."<br/>");6576}elsif(defined$set{'to_id'}) {6577next if($set{'to_id'} =~m/^0{40}$/);65786579print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},6580 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),6581-class=>"list"},6582"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .6583"<br/>\n";6584}6585}6586close$fd;65876588# finish last commit (warning: repetition!)6589if(%co) {6590print"</td>\n".6591"<td class=\"link\">".6592$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6593" | ".6594$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6595print"</td>\n".6596"</tr>\n";6597}65986599print"</table>\n";6600}66016602if($searchtypeeq'grep') {6603 git_print_page_nav('','',$hash,$co{'tree'},$hash);6604 git_print_header_div('commit', esc_html($co{'title'}),$hash);66056606print"<table class=\"grep_search\">\n";6607my$alternate=1;6608my$matches=0;6609local$/="\n";6610open my$fd,"-|", git_cmd(),'grep','-n',6611$search_use_regexp? ('-E','-i') :'-F',6612$searchtext,$co{'tree'};6613my$lastfile='';6614while(my$line= <$fd>) {6615chomp$line;6616my($file,$lno,$ltext,$binary);6617last if($matches++>1000);6618if($line=~/^Binary file (.+) matches$/) {6619$file=$1;6620$binary=1;6621}else{6622(undef,$file,$lno,$ltext) =split(/:/,$line,4);6623}6624if($filene$lastfile) {6625$lastfileand print"</td></tr>\n";6626if($alternate++) {6627print"<tr class=\"dark\">\n";6628}else{6629print"<tr class=\"light\">\n";6630}6631print"<td class=\"list\">".6632$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},6633 file_name=>"$file"),6634-class=>"list"}, esc_path($file));6635print"</td><td>\n";6636$lastfile=$file;6637}6638if($binary) {6639print"<div class=\"binary\">Binary file</div>\n";6640}else{6641$ltext= untabify($ltext);6642if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6643$ltext= esc_html($1, -nbsp=>1);6644$ltext.='<span class="match">';6645$ltext.= esc_html($2, -nbsp=>1);6646$ltext.='</span>';6647$ltext.= esc_html($3, -nbsp=>1);6648}else{6649$ltext= esc_html($ltext, -nbsp=>1);6650}6651print"<div class=\"pre\">".6652$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},6653 file_name=>"$file").'#l'.$lno,6654-class=>"linenr"},sprintf('%4i',$lno))6655.' '.$ltext."</div>\n";6656}6657}6658if($lastfile) {6659print"</td></tr>\n";6660if($matches>1000) {6661print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6662}6663}else{6664print"<div class=\"diff nodifferences\">No matches found</div>\n";6665}6666close$fd;66676668print"</table>\n";6669}6670 git_footer_html();6671}66726673sub git_search_help {6674 git_header_html();6675 git_print_page_nav('','',$hash,$hash,$hash);6676print<<EOT;6677<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without6678regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,6679the pattern entered is recognized as the POSIX extended6680<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case6681insensitive).</p>6682<dl>6683<dt><b>commit</b></dt>6684<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>6685EOT6686my$have_grep= gitweb_check_feature('grep');6687if($have_grep) {6688print<<EOT;6689<dt><b>grep</b></dt>6690<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing6691 a different one) are searched for the given pattern. On large trees, this search can take6692a while and put some strain on the server, so please use it with some consideration. Note that6693due to git-grep peculiarity, currently if regexp mode is turned off, the matches are6694case-sensitive.</dd>6695EOT6696}6697print<<EOT;6698<dt><b>author</b></dt>6699<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>6700<dt><b>committer</b></dt>6701<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>6702EOT6703my$have_pickaxe= gitweb_check_feature('pickaxe');6704if($have_pickaxe) {6705print<<EOT;6706<dt><b>pickaxe</b></dt>6707<dd>All commits that caused the string to appear or disappear from any file (changes that6708added, removed or "modified" the string) will be listed. This search can take a while and6709takes a lot of strain on the server, so please use it wisely. Note that since you may be6710interested even in changes just changing the case as well, this search is case sensitive.</dd>6711EOT6712}6713print"</dl>\n";6714 git_footer_html();6715}67166717sub git_shortlog {6718 git_log_generic('shortlog', \&git_shortlog_body,6719$hash,$hash_parent);6720}67216722## ......................................................................6723## feeds (RSS, Atom; OPML)67246725sub git_feed {6726my$format=shift||'atom';6727my$have_blame= gitweb_check_feature('blame');67286729# Atom: http://www.atomenabled.org/developers/syndication/6730# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ6731if($formatne'rss'&&$formatne'atom') {6732 die_error(400,"Unknown web feed format");6733}67346735# log/feed of current (HEAD) branch, log of given branch, history of file/directory6736my$head=$hash||'HEAD';6737my@commitlist= parse_commits($head,150,0,$file_name);67386739my%latest_commit;6740my%latest_date;6741my$content_type="application/$format+xml";6742if(defined$cgi->http('HTTP_ACCEPT') &&6743$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {6744# browser (feed reader) prefers text/xml6745$content_type='text/xml';6746}6747if(defined($commitlist[0])) {6748%latest_commit= %{$commitlist[0]};6749my$latest_epoch=$latest_commit{'committer_epoch'};6750%latest_date= parse_date($latest_epoch);6751my$if_modified=$cgi->http('IF_MODIFIED_SINCE');6752if(defined$if_modified) {6753my$since;6754if(eval{require HTTP::Date;1; }) {6755$since= HTTP::Date::str2time($if_modified);6756}elsif(eval{require Time::ParseDate;1; }) {6757$since= Time::ParseDate::parsedate($if_modified, GMT =>1);6758}6759if(defined$since&&$latest_epoch<=$since) {6760print$cgi->header(6761-type =>$content_type,6762-charset =>'utf-8',6763-last_modified =>$latest_date{'rfc2822'},6764-status =>'304 Not Modified');6765return;6766}6767}6768print$cgi->header(6769-type =>$content_type,6770-charset =>'utf-8',6771-last_modified =>$latest_date{'rfc2822'});6772}else{6773print$cgi->header(6774-type =>$content_type,6775-charset =>'utf-8');6776}67776778# Optimization: skip generating the body if client asks only6779# for Last-Modified date.6780return if($cgi->request_method()eq'HEAD');67816782# header variables6783my$title="$site_name-$project/$action";6784my$feed_type='log';6785if(defined$hash) {6786$title.=" - '$hash'";6787$feed_type='branch log';6788if(defined$file_name) {6789$title.=" ::$file_name";6790$feed_type='history';6791}6792}elsif(defined$file_name) {6793$title.=" -$file_name";6794$feed_type='history';6795}6796$title.="$feed_type";6797my$descr= git_get_project_description($project);6798if(defined$descr) {6799$descr= esc_html($descr);6800}else{6801$descr="$project".6802($formateq'rss'?'RSS':'Atom') .6803" feed";6804}6805my$owner= git_get_project_owner($project);6806$owner= esc_html($owner);68076808#header6809my$alt_url;6810if(defined$file_name) {6811$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);6812}elsif(defined$hash) {6813$alt_url= href(-full=>1, action=>"log", hash=>$hash);6814}else{6815$alt_url= href(-full=>1, action=>"summary");6816}6817print qq!<?xml version="1.0" encoding="utf-8"?>\n!;6818if($formateq'rss') {6819print<<XML;6820<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">6821<channel>6822XML6823print"<title>$title</title>\n".6824"<link>$alt_url</link>\n".6825"<description>$descr</description>\n".6826"<language>en</language>\n".6827# project owner is responsible for 'editorial' content6828"<managingEditor>$owner</managingEditor>\n";6829if(defined$logo||defined$favicon) {6830# prefer the logo to the favicon, since RSS6831# doesn't allow both6832my$img= esc_url($logo||$favicon);6833print"<image>\n".6834"<url>$img</url>\n".6835"<title>$title</title>\n".6836"<link>$alt_url</link>\n".6837"</image>\n";6838}6839if(%latest_date) {6840print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";6841print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";6842}6843print"<generator>gitweb v.$version/$git_version</generator>\n";6844}elsif($formateq'atom') {6845print<<XML;6846<feed xmlns="http://www.w3.org/2005/Atom">6847XML6848print"<title>$title</title>\n".6849"<subtitle>$descr</subtitle>\n".6850'<link rel="alternate" type="text/html" href="'.6851$alt_url.'" />'."\n".6852'<link rel="self" type="'.$content_type.'" href="'.6853$cgi->self_url() .'" />'."\n".6854"<id>". href(-full=>1) ."</id>\n".6855# use project owner for feed author6856"<author><name>$owner</name></author>\n";6857if(defined$favicon) {6858print"<icon>". esc_url($favicon) ."</icon>\n";6859}6860if(defined$logo_url) {6861# not twice as wide as tall: 72 x 27 pixels6862print"<logo>". esc_url($logo) ."</logo>\n";6863}6864if(!%latest_date) {6865# dummy date to keep the feed valid until commits trickle in:6866print"<updated>1970-01-01T00:00:00Z</updated>\n";6867}else{6868print"<updated>$latest_date{'iso-8601'}</updated>\n";6869}6870print"<generator version='$version/$git_version'>gitweb</generator>\n";6871}68726873# contents6874for(my$i=0;$i<=$#commitlist;$i++) {6875my%co= %{$commitlist[$i]};6876my$commit=$co{'id'};6877# we read 150, we always show 30 and the ones more recent than 48 hours6878if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {6879last;6880}6881my%cd= parse_date($co{'author_epoch'});68826883# get list of changed files6884open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6885$co{'parent'} ||"--root",6886$co{'id'},"--", (defined$file_name?$file_name: ())6887ornext;6888my@difftree=map{chomp;$_} <$fd>;6889close$fd6890ornext;68916892# print element (entry, item)6893my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);6894if($formateq'rss') {6895print"<item>\n".6896"<title>". esc_html($co{'title'}) ."</title>\n".6897"<author>". esc_html($co{'author'}) ."</author>\n".6898"<pubDate>$cd{'rfc2822'}</pubDate>\n".6899"<guid isPermaLink=\"true\">$co_url</guid>\n".6900"<link>$co_url</link>\n".6901"<description>". esc_html($co{'title'}) ."</description>\n".6902"<content:encoded>".6903"<![CDATA[\n";6904}elsif($formateq'atom') {6905print"<entry>\n".6906"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".6907"<updated>$cd{'iso-8601'}</updated>\n".6908"<author>\n".6909" <name>". esc_html($co{'author_name'}) ."</name>\n";6910if($co{'author_email'}) {6911print" <email>". esc_html($co{'author_email'}) ."</email>\n";6912}6913print"</author>\n".6914# use committer for contributor6915"<contributor>\n".6916" <name>". esc_html($co{'committer_name'}) ."</name>\n";6917if($co{'committer_email'}) {6918print" <email>". esc_html($co{'committer_email'}) ."</email>\n";6919}6920print"</contributor>\n".6921"<published>$cd{'iso-8601'}</published>\n".6922"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".6923"<id>$co_url</id>\n".6924"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".6925"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";6926}6927my$comment=$co{'comment'};6928print"<pre>\n";6929foreachmy$line(@$comment) {6930$line= esc_html($line);6931print"$line\n";6932}6933print"</pre><ul>\n";6934foreachmy$difftree_line(@difftree) {6935my%difftree= parse_difftree_raw_line($difftree_line);6936next if!$difftree{'from_id'};69376938my$file=$difftree{'file'} ||$difftree{'to_file'};69396940print"<li>".6941"[".6942$cgi->a({-href => href(-full=>1, action=>"blobdiff",6943 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},6944 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},6945 file_name=>$file, file_parent=>$difftree{'from_file'}),6946-title =>"diff"},'D');6947if($have_blame) {6948print$cgi->a({-href => href(-full=>1, action=>"blame",6949 file_name=>$file, hash_base=>$commit),6950-title =>"blame"},'B');6951}6952# if this is not a feed of a file history6953if(!defined$file_name||$file_namene$file) {6954print$cgi->a({-href => href(-full=>1, action=>"history",6955 file_name=>$file, hash=>$commit),6956-title =>"history"},'H');6957}6958$file= esc_path($file);6959print"] ".6960"$file</li>\n";6961}6962if($formateq'rss') {6963print"</ul>]]>\n".6964"</content:encoded>\n".6965"</item>\n";6966}elsif($formateq'atom') {6967print"</ul>\n</div>\n".6968"</content>\n".6969"</entry>\n";6970}6971}69726973# end of feed6974if($formateq'rss') {6975print"</channel>\n</rss>\n";6976}elsif($formateq'atom') {6977print"</feed>\n";6978}6979}69806981sub git_rss {6982 git_feed('rss');6983}69846985sub git_atom {6986 git_feed('atom');6987}69886989sub git_opml {6990my@list= git_get_projects_list();69916992print$cgi->header(6993-type =>'text/xml',6994-charset =>'utf-8',6995-content_disposition =>'inline; filename="opml.xml"');69966997print<<XML;6998<?xml version="1.0" encoding="utf-8"?>6999<opml version="1.0">7000<head>7001 <title>$site_nameOPML Export</title>7002</head>7003<body>7004<outline text="git RSS feeds">7005XML70067007foreachmy$pr(@list) {7008my%proj=%$pr;7009my$head= git_get_head_hash($proj{'path'});7010if(!defined$head) {7011next;7012}7013$git_dir="$projectroot/$proj{'path'}";7014my%co= parse_commit($head);7015if(!%co) {7016next;7017}70187019my$path= esc_html(chop_str($proj{'path'},25,5));7020my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);7021my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);7022print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";7023}7024print<<XML;7025</outline>7026</body>7027</opml>7028XML7029}