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 10use5.008; 11use strict; 12use warnings; 13use CGI qw(:standard :escapeHTML -nosticky); 14use CGI::Util qw(unescape); 15use CGI::Carp qw(fatalsToBrowser set_message); 16use Encode; 17use Fcntl ':mode'; 18use File::Find qw(); 19use File::Basename qw(basename); 20use Time::HiRes qw(gettimeofday tv_interval); 21binmode STDOUT,':utf8'; 22 23our$t0= [ gettimeofday() ]; 24our$number_of_git_cmds=0; 25 26BEGIN{ 27 CGI->compile()if$ENV{'MOD_PERL'}; 28} 29 30our$version="++GIT_VERSION++"; 31 32our($my_url,$my_uri,$base_url,$path_info,$home_link); 33sub evaluate_uri { 34our$cgi; 35 36our$my_url=$cgi->url(); 37our$my_uri=$cgi->url(-absolute =>1); 38 39# Base URL for relative URLs in gitweb ($logo, $favicon, ...), 40# needed and used only for URLs with nonempty PATH_INFO 41our$base_url=$my_url; 42 43# When the script is used as DirectoryIndex, the URL does not contain the name 44# of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we 45# have to do it ourselves. We make $path_info global because it's also used 46# later on. 47# 48# Another issue with the script being the DirectoryIndex is that the resulting 49# $my_url data is not the full script URL: this is good, because we want 50# generated links to keep implying the script name if it wasn't explicitly 51# indicated in the URL we're handling, but it means that $my_url cannot be used 52# as base URL. 53# Therefore, if we needed to strip PATH_INFO, then we know that we have 54# to build the base URL ourselves: 55our$path_info= decode_utf8($ENV{"PATH_INFO"}); 56if($path_info) { 57# $path_info has already been URL-decoded by the web server, but 58# $my_url and $my_uri have not. URL-decode them so we can properly 59# strip $path_info. 60$my_url= unescape($my_url); 61$my_uri= unescape($my_uri); 62if($my_url=~ s,\Q$path_info\E$,, && 63$my_uri=~ s,\Q$path_info\E$,, && 64defined$ENV{'SCRIPT_NAME'}) { 65$base_url=$cgi->url(-base =>1) .$ENV{'SCRIPT_NAME'}; 66} 67} 68 69# target of the home link on top of all pages 70our$home_link=$my_uri||"/"; 71} 72 73# core git executable to use 74# this can just be "git" if your webserver has a sensible PATH 75our$GIT="++GIT_BINDIR++/git"; 76 77# absolute fs-path which will be prepended to the project path 78#our $projectroot = "/pub/scm"; 79our$projectroot="++GITWEB_PROJECTROOT++"; 80 81# fs traversing limit for getting project list 82# the number is relative to the projectroot 83our$project_maxdepth="++GITWEB_PROJECT_MAXDEPTH++"; 84 85# string of the home link on top of all pages 86our$home_link_str="++GITWEB_HOME_LINK_STR++"; 87 88# extra breadcrumbs preceding the home link 89our@extra_breadcrumbs= (); 90 91# name of your site or organization to appear in page titles 92# replace this with something more descriptive for clearer bookmarks 93our$site_name="++GITWEB_SITENAME++" 94|| ($ENV{'SERVER_NAME'} ||"Untitled") ." Git"; 95 96# html snippet to include in the <head> section of each page 97our$site_html_head_string="++GITWEB_SITE_HTML_HEAD_STRING++"; 98# filename of html text to include at top of each page 99our$site_header="++GITWEB_SITE_HEADER++"; 100# html text to include at home page 101our$home_text="++GITWEB_HOMETEXT++"; 102# filename of html text to include at bottom of each page 103our$site_footer="++GITWEB_SITE_FOOTER++"; 104 105# URI of stylesheets 106our@stylesheets= ("++GITWEB_CSS++"); 107# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG. 108our$stylesheet=undef; 109# URI of GIT logo (72x27 size) 110our$logo="++GITWEB_LOGO++"; 111# URI of GIT favicon, assumed to be image/png type 112our$favicon="++GITWEB_FAVICON++"; 113# URI of gitweb.js (JavaScript code for gitweb) 114our$javascript="++GITWEB_JS++"; 115 116# URI and label (title) of GIT logo link 117#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/"; 118#our $logo_label = "git documentation"; 119our$logo_url="http://git-scm.com/"; 120our$logo_label="git homepage"; 121 122# source of projects list 123our$projects_list="++GITWEB_LIST++"; 124 125# the width (in characters) of the projects list "Description" column 126our$projects_list_description_width=25; 127 128# group projects by category on the projects list 129# (enabled if this variable evaluates to true) 130our$projects_list_group_categories=0; 131 132# default category if none specified 133# (leave the empty string for no category) 134our$project_list_default_category=""; 135 136# default order of projects list 137# valid values are none, project, descr, owner, and age 138our$default_projects_order="project"; 139 140# show repository only if this file exists 141# (only effective if this variable evaluates to true) 142our$export_ok="++GITWEB_EXPORT_OK++"; 143 144# don't generate age column on the projects list page 145our$omit_age_column=0; 146 147# don't generate information about owners of repositories 148our$omit_owner=0; 149 150# show repository only if this subroutine returns true 151# when given the path to the project, for example: 152# sub { return -e "$_[0]/git-daemon-export-ok"; } 153our$export_auth_hook=undef; 154 155# only allow viewing of repositories also shown on the overview page 156our$strict_export="++GITWEB_STRICT_EXPORT++"; 157 158# list of git base URLs used for URL to where fetch project from, 159# i.e. full URL is "$git_base_url/$project" 160our@git_base_url_list=grep{$_ne''} ("++GITWEB_BASE_URL++"); 161 162# default blob_plain mimetype and default charset for text/plain blob 163our$default_blob_plain_mimetype='text/plain'; 164our$default_text_plain_charset=undef; 165 166# file to use for guessing MIME types before trying /etc/mime.types 167# (relative to the current git repository) 168our$mimetypes_file=undef; 169 170# assume this charset if line contains non-UTF-8 characters; 171# it should be valid encoding (see Encoding::Supported(3pm) for list), 172# for which encoding all byte sequences are valid, for example 173# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it 174# could be even 'utf-8' for the old behavior) 175our$fallback_encoding='latin1'; 176 177# rename detection options for git-diff and git-diff-tree 178# - default is '-M', with the cost proportional to 179# (number of removed files) * (number of new files). 180# - more costly is '-C' (which implies '-M'), with the cost proportional to 181# (number of changed files + number of removed files) * (number of new files) 182# - even more costly is '-C', '--find-copies-harder' with cost 183# (number of files in the original tree) * (number of new files) 184# - one might want to include '-B' option, e.g. '-B', '-M' 185our@diff_opts= ('-M');# taken from git_commit 186 187# Disables features that would allow repository owners to inject script into 188# the gitweb domain. 189our$prevent_xss=0; 190 191# Path to the highlight executable to use (must be the one from 192# http://www.andre-simon.de due to assumptions about parameters and output). 193# Useful if highlight is not installed on your webserver's PATH. 194# [Default: highlight] 195our$highlight_bin="++HIGHLIGHT_BIN++"; 196 197# information about snapshot formats that gitweb is capable of serving 198our%known_snapshot_formats= ( 199# name => { 200# 'display' => display name, 201# 'type' => mime type, 202# 'suffix' => filename suffix, 203# 'format' => --format for git-archive, 204# 'compressor' => [compressor command and arguments] 205# (array reference, optional) 206# 'disabled' => boolean (optional)} 207# 208'tgz'=> { 209'display'=>'tar.gz', 210'type'=>'application/x-gzip', 211'suffix'=>'.tar.gz', 212'format'=>'tar', 213'compressor'=> ['gzip','-n']}, 214 215'tbz2'=> { 216'display'=>'tar.bz2', 217'type'=>'application/x-bzip2', 218'suffix'=>'.tar.bz2', 219'format'=>'tar', 220'compressor'=> ['bzip2']}, 221 222'txz'=> { 223'display'=>'tar.xz', 224'type'=>'application/x-xz', 225'suffix'=>'.tar.xz', 226'format'=>'tar', 227'compressor'=> ['xz'], 228'disabled'=>1}, 229 230'zip'=> { 231'display'=>'zip', 232'type'=>'application/x-zip', 233'suffix'=>'.zip', 234'format'=>'zip'}, 235); 236 237# Aliases so we understand old gitweb.snapshot values in repository 238# configuration. 239our%known_snapshot_format_aliases= ( 240'gzip'=>'tgz', 241'bzip2'=>'tbz2', 242'xz'=>'txz', 243 244# backward compatibility: legacy gitweb config support 245'x-gzip'=>undef,'gz'=>undef, 246'x-bzip2'=>undef,'bz2'=>undef, 247'x-zip'=>undef,''=>undef, 248); 249 250# Pixel sizes for icons and avatars. If the default font sizes or lineheights 251# are changed, it may be appropriate to change these values too via 252# $GITWEB_CONFIG. 253our%avatar_size= ( 254'default'=>16, 255'double'=>32 256); 257 258# Used to set the maximum load that we will still respond to gitweb queries. 259# If server load exceed this value then return "503 server busy" error. 260# If gitweb cannot determined server load, it is taken to be 0. 261# Leave it undefined (or set to 'undef') to turn off load checking. 262our$maxload=300; 263 264# configuration for 'highlight' (http://www.andre-simon.de/) 265# match by basename 266our%highlight_basename= ( 267#'Program' => 'py', 268#'Library' => 'py', 269'SConstruct'=>'py',# SCons equivalent of Makefile 270'Makefile'=>'make', 271); 272# match by extension 273our%highlight_ext= ( 274# main extensions, defining name of syntax; 275# see files in /usr/share/highlight/langDefs/ directory 276(map{$_=>$_}qw(py rb java css js tex bib xml awk bat ini spec tcl sql)), 277# alternate extensions, see /etc/highlight/filetypes.conf 278(map{$_=>'c'}qw(c h)), 279(map{$_=>'sh'}qw(sh bash zsh ksh)), 280(map{$_=>'cpp'}qw(cpp cxx c++ cc)), 281(map{$_=>'php'}qw(php php3 php4 php5 phps)), 282(map{$_=>'pl'}qw(pl perl pm)),# perhaps also 'cgi' 283(map{$_=>'make'}qw(make mak mk)), 284(map{$_=>'xml'}qw(xml xhtml html htm)), 285); 286 287# You define site-wide feature defaults here; override them with 288# $GITWEB_CONFIG as necessary. 289our%feature= ( 290# feature => { 291# 'sub' => feature-sub (subroutine), 292# 'override' => allow-override (boolean), 293# 'default' => [ default options...] (array reference)} 294# 295# if feature is overridable (it means that allow-override has true value), 296# then feature-sub will be called with default options as parameters; 297# return value of feature-sub indicates if to enable specified feature 298# 299# if there is no 'sub' key (no feature-sub), then feature cannot be 300# overridden 301# 302# use gitweb_get_feature(<feature>) to retrieve the <feature> value 303# (an array) or gitweb_check_feature(<feature>) to check if <feature> 304# is enabled 305 306# Enable the 'blame' blob view, showing the last commit that modified 307# each line in the file. This can be very CPU-intensive. 308 309# To enable system wide have in $GITWEB_CONFIG 310# $feature{'blame'}{'default'} = [1]; 311# To have project specific config enable override in $GITWEB_CONFIG 312# $feature{'blame'}{'override'} = 1; 313# and in project config gitweb.blame = 0|1; 314'blame'=> { 315'sub'=>sub{ feature_bool('blame',@_) }, 316'override'=>0, 317'default'=> [0]}, 318 319# Enable the 'snapshot' link, providing a compressed archive of any 320# tree. This can potentially generate high traffic if you have large 321# project. 322 323# Value is a list of formats defined in %known_snapshot_formats that 324# you wish to offer. 325# To disable system wide have in $GITWEB_CONFIG 326# $feature{'snapshot'}{'default'} = []; 327# To have project specific config enable override in $GITWEB_CONFIG 328# $feature{'snapshot'}{'override'} = 1; 329# and in project config, a comma-separated list of formats or "none" 330# to disable. Example: gitweb.snapshot = tbz2,zip; 331'snapshot'=> { 332'sub'=> \&feature_snapshot, 333'override'=>0, 334'default'=> ['tgz']}, 335 336# Enable text search, which will list the commits which match author, 337# committer or commit text to a given string. Enabled by default. 338# Project specific override is not supported. 339# 340# Note that this controls all search features, which means that if 341# it is disabled, then 'grep' and 'pickaxe' search would also be 342# disabled. 343'search'=> { 344'override'=>0, 345'default'=> [1]}, 346 347# Enable grep search, which will list the files in currently selected 348# tree containing the given string. Enabled by default. This can be 349# potentially CPU-intensive, of course. 350# Note that you need to have 'search' feature enabled too. 351 352# To enable system wide have in $GITWEB_CONFIG 353# $feature{'grep'}{'default'} = [1]; 354# To have project specific config enable override in $GITWEB_CONFIG 355# $feature{'grep'}{'override'} = 1; 356# and in project config gitweb.grep = 0|1; 357'grep'=> { 358'sub'=>sub{ feature_bool('grep',@_) }, 359'override'=>0, 360'default'=> [1]}, 361 362# Enable the pickaxe search, which will list the commits that modified 363# a given string in a file. This can be practical and quite faster 364# alternative to 'blame', but still potentially CPU-intensive. 365# Note that you need to have 'search' feature enabled too. 366 367# To enable system wide have in $GITWEB_CONFIG 368# $feature{'pickaxe'}{'default'} = [1]; 369# To have project specific config enable override in $GITWEB_CONFIG 370# $feature{'pickaxe'}{'override'} = 1; 371# and in project config gitweb.pickaxe = 0|1; 372'pickaxe'=> { 373'sub'=>sub{ feature_bool('pickaxe',@_) }, 374'override'=>0, 375'default'=> [1]}, 376 377# Enable showing size of blobs in a 'tree' view, in a separate 378# column, similar to what 'ls -l' does. This cost a bit of IO. 379 380# To disable system wide have in $GITWEB_CONFIG 381# $feature{'show-sizes'}{'default'} = [0]; 382# To have project specific config enable override in $GITWEB_CONFIG 383# $feature{'show-sizes'}{'override'} = 1; 384# and in project config gitweb.showsizes = 0|1; 385'show-sizes'=> { 386'sub'=>sub{ feature_bool('showsizes',@_) }, 387'override'=>0, 388'default'=> [1]}, 389 390# Make gitweb use an alternative format of the URLs which can be 391# more readable and natural-looking: project name is embedded 392# directly in the path and the query string contains other 393# auxiliary information. All gitweb installations recognize 394# URL in either format; this configures in which formats gitweb 395# generates links. 396 397# To enable system wide have in $GITWEB_CONFIG 398# $feature{'pathinfo'}{'default'} = [1]; 399# Project specific override is not supported. 400 401# Note that you will need to change the default location of CSS, 402# favicon, logo and possibly other files to an absolute URL. Also, 403# if gitweb.cgi serves as your indexfile, you will need to force 404# $my_uri to contain the script name in your $GITWEB_CONFIG. 405'pathinfo'=> { 406'override'=>0, 407'default'=> [0]}, 408 409# Make gitweb consider projects in project root subdirectories 410# to be forks of existing projects. Given project $projname.git, 411# projects matching $projname/*.git will not be shown in the main 412# projects list, instead a '+' mark will be added to $projname 413# there and a 'forks' view will be enabled for the project, listing 414# all the forks. If project list is taken from a file, forks have 415# to be listed after the main project. 416 417# To enable system wide have in $GITWEB_CONFIG 418# $feature{'forks'}{'default'} = [1]; 419# Project specific override is not supported. 420'forks'=> { 421'override'=>0, 422'default'=> [0]}, 423 424# Insert custom links to the action bar of all project pages. 425# This enables you mainly to link to third-party scripts integrating 426# into gitweb; e.g. git-browser for graphical history representation 427# or custom web-based repository administration interface. 428 429# The 'default' value consists of a list of triplets in the form 430# (label, link, position) where position is the label after which 431# to insert the link and link is a format string where %n expands 432# to the project name, %f to the project path within the filesystem, 433# %h to the current hash (h gitweb parameter) and %b to the current 434# hash base (hb gitweb parameter); %% expands to %. 435 436# To enable system wide have in $GITWEB_CONFIG e.g. 437# $feature{'actions'}{'default'} = [('graphiclog', 438# '/git-browser/by-commit.html?r=%n', 'summary')]; 439# Project specific override is not supported. 440'actions'=> { 441'override'=>0, 442'default'=> []}, 443 444# Allow gitweb scan project content tags of project repository, 445# and display the popular Web 2.0-ish "tag cloud" near the projects 446# list. Note that this is something COMPLETELY different from the 447# normal Git tags. 448 449# gitweb by itself can show existing tags, but it does not handle 450# tagging itself; you need to do it externally, outside gitweb. 451# The format is described in git_get_project_ctags() subroutine. 452# You may want to install the HTML::TagCloud Perl module to get 453# a pretty tag cloud instead of just a list of tags. 454 455# To enable system wide have in $GITWEB_CONFIG 456# $feature{'ctags'}{'default'} = [1]; 457# Project specific override is not supported. 458 459# In the future whether ctags editing is enabled might depend 460# on the value, but using 1 should always mean no editing of ctags. 461'ctags'=> { 462'override'=>0, 463'default'=> [0]}, 464 465# The maximum number of patches in a patchset generated in patch 466# view. Set this to 0 or undef to disable patch view, or to a 467# negative number to remove any limit. 468 469# To disable system wide have in $GITWEB_CONFIG 470# $feature{'patches'}{'default'} = [0]; 471# To have project specific config enable override in $GITWEB_CONFIG 472# $feature{'patches'}{'override'} = 1; 473# and in project config gitweb.patches = 0|n; 474# where n is the maximum number of patches allowed in a patchset. 475'patches'=> { 476'sub'=> \&feature_patches, 477'override'=>0, 478'default'=> [16]}, 479 480# Avatar support. When this feature is enabled, views such as 481# shortlog or commit will display an avatar associated with 482# the email of the committer(s) and/or author(s). 483 484# Currently available providers are gravatar and picon. 485# If an unknown provider is specified, the feature is disabled. 486 487# Gravatar depends on Digest::MD5. 488# Picon currently relies on the indiana.edu database. 489 490# To enable system wide have in $GITWEB_CONFIG 491# $feature{'avatar'}{'default'} = ['<provider>']; 492# where <provider> is either gravatar or picon. 493# To have project specific config enable override in $GITWEB_CONFIG 494# $feature{'avatar'}{'override'} = 1; 495# and in project config gitweb.avatar = <provider>; 496'avatar'=> { 497'sub'=> \&feature_avatar, 498'override'=>0, 499'default'=> ['']}, 500 501# Enable displaying how much time and how many git commands 502# it took to generate and display page. Disabled by default. 503# Project specific override is not supported. 504'timed'=> { 505'override'=>0, 506'default'=> [0]}, 507 508# Enable turning some links into links to actions which require 509# JavaScript to run (like 'blame_incremental'). Not enabled by 510# default. Project specific override is currently not supported. 511'javascript-actions'=> { 512'override'=>0, 513'default'=> [0]}, 514 515# Enable and configure ability to change common timezone for dates 516# in gitweb output via JavaScript. Enabled by default. 517# Project specific override is not supported. 518'javascript-timezone'=> { 519'override'=>0, 520'default'=> [ 521'local',# default timezone: 'utc', 'local', or '(-|+)HHMM' format, 522# or undef to turn off this feature 523'gitweb_tz',# name of cookie where to store selected timezone 524'datetime',# CSS class used to mark up dates for manipulation 525]}, 526 527# Syntax highlighting support. This is based on Daniel Svensson's 528# and Sham Chukoury's work in gitweb-xmms2.git. 529# It requires the 'highlight' program present in $PATH, 530# and therefore is disabled by default. 531 532# To enable system wide have in $GITWEB_CONFIG 533# $feature{'highlight'}{'default'} = [1]; 534 535'highlight'=> { 536'sub'=>sub{ feature_bool('highlight',@_) }, 537'override'=>0, 538'default'=> [0]}, 539 540# Enable displaying of remote heads in the heads list 541 542# To enable system wide have in $GITWEB_CONFIG 543# $feature{'remote_heads'}{'default'} = [1]; 544# To have project specific config enable override in $GITWEB_CONFIG 545# $feature{'remote_heads'}{'override'} = 1; 546# and in project config gitweb.remoteheads = 0|1; 547'remote_heads'=> { 548'sub'=>sub{ feature_bool('remote_heads',@_) }, 549'override'=>0, 550'default'=> [0]}, 551 552# Enable showing branches under other refs in addition to heads 553 554# To set system wide extra branch refs have in $GITWEB_CONFIG 555# $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice']; 556# To have project specific config enable override in $GITWEB_CONFIG 557# $feature{'extra-branch-refs'}{'override'} = 1; 558# and in project config gitweb.extrabranchrefs = dirs of choice 559# Every directory is separated with whitespace. 560 561'extra-branch-refs'=> { 562'sub'=> \&feature_extra_branch_refs, 563'override'=>0, 564'default'=> []}, 565); 566 567sub gitweb_get_feature { 568my($name) =@_; 569return unlessexists$feature{$name}; 570my($sub,$override,@defaults) = ( 571$feature{$name}{'sub'}, 572$feature{$name}{'override'}, 573@{$feature{$name}{'default'}}); 574# project specific override is possible only if we have project 575our$git_dir;# global variable, declared later 576if(!$override|| !defined$git_dir) { 577return@defaults; 578} 579if(!defined$sub) { 580warn"feature$nameis not overridable"; 581return@defaults; 582} 583return$sub->(@defaults); 584} 585 586# A wrapper to check if a given feature is enabled. 587# With this, you can say 588# 589# my $bool_feat = gitweb_check_feature('bool_feat'); 590# gitweb_check_feature('bool_feat') or somecode; 591# 592# instead of 593# 594# my ($bool_feat) = gitweb_get_feature('bool_feat'); 595# (gitweb_get_feature('bool_feat'))[0] or somecode; 596# 597sub gitweb_check_feature { 598return(gitweb_get_feature(@_))[0]; 599} 600 601 602sub feature_bool { 603my$key=shift; 604my($val) = git_get_project_config($key,'--bool'); 605 606if(!defined$val) { 607return($_[0]); 608}elsif($valeq'true') { 609return(1); 610}elsif($valeq'false') { 611return(0); 612} 613} 614 615sub feature_snapshot { 616my(@fmts) =@_; 617 618my($val) = git_get_project_config('snapshot'); 619 620if($val) { 621@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 622} 623 624return@fmts; 625} 626 627sub feature_patches { 628my@val= (git_get_project_config('patches','--int')); 629 630if(@val) { 631return@val; 632} 633 634return($_[0]); 635} 636 637sub feature_avatar { 638my@val= (git_get_project_config('avatar')); 639 640return@val?@val:@_; 641} 642 643sub feature_extra_branch_refs { 644my(@branch_refs) =@_; 645my$values= git_get_project_config('extrabranchrefs'); 646 647if($values) { 648$values= config_to_multi ($values); 649@branch_refs= (); 650foreachmy$value(@{$values}) { 651push@branch_refs,split/\s+/,$value; 652} 653} 654 655return@branch_refs; 656} 657 658# checking HEAD file with -e is fragile if the repository was 659# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 660# and then pruned. 661sub check_head_link { 662my($dir) =@_; 663my$headfile="$dir/HEAD"; 664return((-e $headfile) || 665(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 666} 667 668sub check_export_ok { 669my($dir) =@_; 670return(check_head_link($dir) && 671(!$export_ok|| -e "$dir/$export_ok") && 672(!$export_auth_hook||$export_auth_hook->($dir))); 673} 674 675# process alternate names for backward compatibility 676# filter out unsupported (unknown) snapshot formats 677sub filter_snapshot_fmts { 678my@fmts=@_; 679 680@fmts=map{ 681exists$known_snapshot_format_aliases{$_} ? 682$known_snapshot_format_aliases{$_} :$_}@fmts; 683@fmts=grep{ 684exists$known_snapshot_formats{$_} && 685!$known_snapshot_formats{$_}{'disabled'}}@fmts; 686} 687 688sub filter_and_validate_refs { 689my@refs=@_; 690my%unique_refs= (); 691 692foreachmy$ref(@refs) { 693 die_error(500,"Invalid ref '$ref' in 'extra-branch-refs' feature")unless(is_valid_ref_format($ref)); 694# 'heads' are added implicitly in get_branch_refs(). 695$unique_refs{$ref} =1if($refne'heads'); 696} 697returnsort keys%unique_refs; 698} 699 700# If it is set to code reference, it is code that it is to be run once per 701# request, allowing updating configurations that change with each request, 702# while running other code in config file only once. 703# 704# Otherwise, if it is false then gitweb would process config file only once; 705# if it is true then gitweb config would be run for each request. 706our$per_request_config=1; 707 708# read and parse gitweb config file given by its parameter. 709# returns true on success, false on recoverable error, allowing 710# to chain this subroutine, using first file that exists. 711# dies on errors during parsing config file, as it is unrecoverable. 712sub read_config_file { 713my$filename=shift; 714return unlessdefined$filename; 715# die if there are errors parsing config file 716if(-e $filename) { 717do$filename; 718die$@if$@; 719return1; 720} 721return; 722} 723 724our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM,$GITWEB_CONFIG_COMMON); 725sub evaluate_gitweb_config { 726our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 727our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 728our$GITWEB_CONFIG_COMMON=$ENV{'GITWEB_CONFIG_COMMON'} ||"++GITWEB_CONFIG_COMMON++"; 729 730# Protect against duplications of file names, to not read config twice. 731# Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so 732# there possibility of duplication of filename there doesn't matter. 733$GITWEB_CONFIG=""if($GITWEB_CONFIGeq$GITWEB_CONFIG_COMMON); 734$GITWEB_CONFIG_SYSTEM=""if($GITWEB_CONFIG_SYSTEMeq$GITWEB_CONFIG_COMMON); 735 736# Common system-wide settings for convenience. 737# Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM. 738 read_config_file($GITWEB_CONFIG_COMMON); 739 740# Use first config file that exists. This means use the per-instance 741# GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG. 742 read_config_file($GITWEB_CONFIG)andreturn; 743 read_config_file($GITWEB_CONFIG_SYSTEM); 744} 745 746# Get loadavg of system, to compare against $maxload. 747# Currently it requires '/proc/loadavg' present to get loadavg; 748# if it is not present it returns 0, which means no load checking. 749sub get_loadavg { 750if( -e '/proc/loadavg'){ 751open my$fd,'<','/proc/loadavg' 752orreturn0; 753my@load=split(/\s+/,scalar<$fd>); 754close$fd; 755 756# The first three columns measure CPU and IO utilization of the last one, 757# five, and 10 minute periods. The fourth column shows the number of 758# currently running processes and the total number of processes in the m/n 759# format. The last column displays the last process ID used. 760return$load[0] ||0; 761} 762# additional checks for load average should go here for things that don't export 763# /proc/loadavg 764 765return0; 766} 767 768# version of the core git binary 769our$git_version; 770sub evaluate_git_version { 771our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 772$number_of_git_cmds++; 773} 774 775sub check_loadavg { 776if(defined$maxload&& get_loadavg() >$maxload) { 777 die_error(503,"The load average on the server is too high"); 778} 779} 780 781# ====================================================================== 782# input validation and dispatch 783 784# input parameters can be collected from a variety of sources (presently, CGI 785# and PATH_INFO), so we define an %input_params hash that collects them all 786# together during validation: this allows subsequent uses (e.g. href()) to be 787# agnostic of the parameter origin 788 789our%input_params= (); 790 791# input parameters are stored with the long parameter name as key. This will 792# also be used in the href subroutine to convert parameters to their CGI 793# equivalent, and since the href() usage is the most frequent one, we store 794# the name -> CGI key mapping here, instead of the reverse. 795# 796# XXX: Warning: If you touch this, check the search form for updating, 797# too. 798 799our@cgi_param_mapping= ( 800 project =>"p", 801 action =>"a", 802 file_name =>"f", 803 file_parent =>"fp", 804 hash =>"h", 805 hash_parent =>"hp", 806 hash_base =>"hb", 807 hash_parent_base =>"hpb", 808 page =>"pg", 809 order =>"o", 810 searchtext =>"s", 811 searchtype =>"st", 812 snapshot_format =>"sf", 813 extra_options =>"opt", 814 search_use_regexp =>"sr", 815 ctag =>"by_tag", 816 diff_style =>"ds", 817 project_filter =>"pf", 818# this must be last entry (for manipulation from JavaScript) 819 javascript =>"js" 820); 821our%cgi_param_mapping=@cgi_param_mapping; 822 823# we will also need to know the possible actions, for validation 824our%actions= ( 825"blame"=> \&git_blame, 826"blame_incremental"=> \&git_blame_incremental, 827"blame_data"=> \&git_blame_data, 828"blobdiff"=> \&git_blobdiff, 829"blobdiff_plain"=> \&git_blobdiff_plain, 830"blob"=> \&git_blob, 831"blob_plain"=> \&git_blob_plain, 832"commitdiff"=> \&git_commitdiff, 833"commitdiff_plain"=> \&git_commitdiff_plain, 834"commit"=> \&git_commit, 835"forks"=> \&git_forks, 836"heads"=> \&git_heads, 837"history"=> \&git_history, 838"log"=> \&git_log, 839"patch"=> \&git_patch, 840"patches"=> \&git_patches, 841"remotes"=> \&git_remotes, 842"rss"=> \&git_rss, 843"atom"=> \&git_atom, 844"search"=> \&git_search, 845"search_help"=> \&git_search_help, 846"shortlog"=> \&git_shortlog, 847"summary"=> \&git_summary, 848"tag"=> \&git_tag, 849"tags"=> \&git_tags, 850"tree"=> \&git_tree, 851"snapshot"=> \&git_snapshot, 852"object"=> \&git_object, 853# those below don't need $project 854"opml"=> \&git_opml, 855"project_list"=> \&git_project_list, 856"project_index"=> \&git_project_index, 857); 858 859# finally, we have the hash of allowed extra_options for the commands that 860# allow them 861our%allowed_options= ( 862"--no-merges"=> [qw(rss atom log shortlog history)], 863); 864 865# fill %input_params with the CGI parameters. All values except for 'opt' 866# should be single values, but opt can be an array. We should probably 867# build an array of parameters that can be multi-valued, but since for the time 868# being it's only this one, we just single it out 869sub evaluate_query_params { 870our$cgi; 871 872while(my($name,$symbol) =each%cgi_param_mapping) { 873if($symboleq'opt') { 874$input_params{$name} = [map{ decode_utf8($_) }$cgi->param($symbol) ]; 875}else{ 876$input_params{$name} = decode_utf8($cgi->param($symbol)); 877} 878} 879} 880 881# now read PATH_INFO and update the parameter list for missing parameters 882sub evaluate_path_info { 883return ifdefined$input_params{'project'}; 884return if!$path_info; 885$path_info=~ s,^/+,,; 886return if!$path_info; 887 888# find which part of PATH_INFO is project 889my$project=$path_info; 890$project=~ s,/+$,,; 891while($project&& !check_head_link("$projectroot/$project")) { 892$project=~ s,/*[^/]*$,,; 893} 894return unless$project; 895$input_params{'project'} =$project; 896 897# do not change any parameters if an action is given using the query string 898return if$input_params{'action'}; 899$path_info=~ s,^\Q$project\E/*,,; 900 901# next, check if we have an action 902my$action=$path_info; 903$action=~ s,/.*$,,; 904if(exists$actions{$action}) { 905$path_info=~ s,^$action/*,,; 906$input_params{'action'} =$action; 907} 908 909# list of actions that want hash_base instead of hash, but can have no 910# pathname (f) parameter 911my@wants_base= ( 912'tree', 913'history', 914); 915 916# we want to catch, among others 917# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 918my($parentrefname,$parentpathname,$refname,$pathname) = 919($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/); 920 921# first, analyze the 'current' part 922if(defined$pathname) { 923# we got "branch:filename" or "branch:dir/" 924# we could use git_get_type(branch:pathname), but: 925# - it needs $git_dir 926# - it does a git() call 927# - the convention of terminating directories with a slash 928# makes it superfluous 929# - embedding the action in the PATH_INFO would make it even 930# more superfluous 931$pathname=~ s,^/+,,; 932if(!$pathname||substr($pathname, -1)eq"/") { 933$input_params{'action'} ||="tree"; 934$pathname=~ s,/$,,; 935}else{ 936# the default action depends on whether we had parent info 937# or not 938if($parentrefname) { 939$input_params{'action'} ||="blobdiff_plain"; 940}else{ 941$input_params{'action'} ||="blob_plain"; 942} 943} 944$input_params{'hash_base'} ||=$refname; 945$input_params{'file_name'} ||=$pathname; 946}elsif(defined$refname) { 947# we got "branch". In this case we have to choose if we have to 948# set hash or hash_base. 949# 950# Most of the actions without a pathname only want hash to be 951# set, except for the ones specified in @wants_base that want 952# hash_base instead. It should also be noted that hand-crafted 953# links having 'history' as an action and no pathname or hash 954# set will fail, but that happens regardless of PATH_INFO. 955if(defined$parentrefname) { 956# if there is parent let the default be 'shortlog' action 957# (for http://git.example.com/repo.git/A..B links); if there 958# is no parent, dispatch will detect type of object and set 959# action appropriately if required (if action is not set) 960$input_params{'action'} ||="shortlog"; 961} 962if($input_params{'action'} && 963grep{$_eq$input_params{'action'} }@wants_base) { 964$input_params{'hash_base'} ||=$refname; 965}else{ 966$input_params{'hash'} ||=$refname; 967} 968} 969 970# next, handle the 'parent' part, if present 971if(defined$parentrefname) { 972# a missing pathspec defaults to the 'current' filename, allowing e.g. 973# someproject/blobdiff/oldrev..newrev:/filename 974if($parentpathname) { 975$parentpathname=~ s,^/+,,; 976$parentpathname=~ s,/$,,; 977$input_params{'file_parent'} ||=$parentpathname; 978}else{ 979$input_params{'file_parent'} ||=$input_params{'file_name'}; 980} 981# we assume that hash_parent_base is wanted if a path was specified, 982# or if the action wants hash_base instead of hash 983if(defined$input_params{'file_parent'} || 984grep{$_eq$input_params{'action'} }@wants_base) { 985$input_params{'hash_parent_base'} ||=$parentrefname; 986}else{ 987$input_params{'hash_parent'} ||=$parentrefname; 988} 989} 990 991# for the snapshot action, we allow URLs in the form 992# $project/snapshot/$hash.ext 993# where .ext determines the snapshot and gets removed from the 994# passed $refname to provide the $hash. 995# 996# To be able to tell that $refname includes the format extension, we 997# require the following two conditions to be satisfied: 998# - the hash input parameter MUST have been set from the $refname part 999# of the URL (i.e. they must be equal)1000# - the snapshot format MUST NOT have been defined already (e.g. from1001# CGI parameter sf)1002# It's also useless to try any matching unless $refname has a dot,1003# so we check for that too1004if(defined$input_params{'action'} &&1005$input_params{'action'}eq'snapshot'&&1006defined$refname&&index($refname,'.') != -1&&1007$refnameeq$input_params{'hash'} &&1008!defined$input_params{'snapshot_format'}) {1009# We loop over the known snapshot formats, checking for1010# extensions. Allowed extensions are both the defined suffix1011# (which includes the initial dot already) and the snapshot1012# format key itself, with a prepended dot1013while(my($fmt,$opt) =each%known_snapshot_formats) {1014my$hash=$refname;1015unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {1016next;1017}1018my$sfx=$1;1019# a valid suffix was found, so set the snapshot format1020# and reset the hash parameter1021$input_params{'snapshot_format'} =$fmt;1022$input_params{'hash'} =$hash;1023# we also set the format suffix to the one requested1024# in the URL: this way a request for e.g. .tgz returns1025# a .tgz instead of a .tar.gz1026$known_snapshot_formats{$fmt}{'suffix'} =$sfx;1027last;1028}1029}1030}10311032our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base,1033$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp,1034$searchtext,$search_regexp,$project_filter);1035sub evaluate_and_validate_params {1036our$action=$input_params{'action'};1037if(defined$action) {1038if(!is_valid_action($action)) {1039 die_error(400,"Invalid action parameter");1040}1041}10421043# parameters which are pathnames1044our$project=$input_params{'project'};1045if(defined$project) {1046if(!is_valid_project($project)) {1047undef$project;1048 die_error(404,"No such project");1049}1050}10511052our$project_filter=$input_params{'project_filter'};1053if(defined$project_filter) {1054if(!is_valid_pathname($project_filter)) {1055 die_error(404,"Invalid project_filter parameter");1056}1057}10581059our$file_name=$input_params{'file_name'};1060if(defined$file_name) {1061if(!is_valid_pathname($file_name)) {1062 die_error(400,"Invalid file parameter");1063}1064}10651066our$file_parent=$input_params{'file_parent'};1067if(defined$file_parent) {1068if(!is_valid_pathname($file_parent)) {1069 die_error(400,"Invalid file parent parameter");1070}1071}10721073# parameters which are refnames1074our$hash=$input_params{'hash'};1075if(defined$hash) {1076if(!is_valid_refname($hash)) {1077 die_error(400,"Invalid hash parameter");1078}1079}10801081our$hash_parent=$input_params{'hash_parent'};1082if(defined$hash_parent) {1083if(!is_valid_refname($hash_parent)) {1084 die_error(400,"Invalid hash parent parameter");1085}1086}10871088our$hash_base=$input_params{'hash_base'};1089if(defined$hash_base) {1090if(!is_valid_refname($hash_base)) {1091 die_error(400,"Invalid hash base parameter");1092}1093}10941095our@extra_options= @{$input_params{'extra_options'}};1096# @extra_options is always defined, since it can only be (currently) set from1097# CGI, and $cgi->param() returns the empty array in array context if the param1098# is not set1099foreachmy$opt(@extra_options) {1100if(not exists$allowed_options{$opt}) {1101 die_error(400,"Invalid option parameter");1102}1103if(not grep(/^$action$/, @{$allowed_options{$opt}})) {1104 die_error(400,"Invalid option parameter for this action");1105}1106}11071108our$hash_parent_base=$input_params{'hash_parent_base'};1109if(defined$hash_parent_base) {1110if(!is_valid_refname($hash_parent_base)) {1111 die_error(400,"Invalid hash parent base parameter");1112}1113}11141115# other parameters1116our$page=$input_params{'page'};1117if(defined$page) {1118if($page=~m/[^0-9]/) {1119 die_error(400,"Invalid page parameter");1120}1121}11221123our$searchtype=$input_params{'searchtype'};1124if(defined$searchtype) {1125if($searchtype=~m/[^a-z]/) {1126 die_error(400,"Invalid searchtype parameter");1127}1128}11291130our$search_use_regexp=$input_params{'search_use_regexp'};11311132our$searchtext=$input_params{'searchtext'};1133our$search_regexp=undef;1134if(defined$searchtext) {1135if(length($searchtext) <2) {1136 die_error(403,"At least two characters are required for search parameter");1137}1138if($search_use_regexp) {1139$search_regexp=$searchtext;1140if(!eval{qr/$search_regexp/;1; }) {1141(my$error=$@) =~s/ at \S+ line \d+.*\n?//;1142 die_error(400,"Invalid search regexp '$search_regexp'",1143 esc_html($error));1144}1145}else{1146$search_regexp=quotemeta$searchtext;1147}1148}1149}11501151# path to the current git repository1152our$git_dir;1153sub evaluate_git_dir {1154our$git_dir="$projectroot/$project"if$project;1155}11561157our(@snapshot_fmts,$git_avatar,@extra_branch_refs);1158sub configure_gitweb_features {1159# list of supported snapshot formats1160our@snapshot_fmts= gitweb_get_feature('snapshot');1161@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);11621163# check that the avatar feature is set to a known provider name,1164# and for each provider check if the dependencies are satisfied.1165# if the provider name is invalid or the dependencies are not met,1166# reset $git_avatar to the empty string.1167our($git_avatar) = gitweb_get_feature('avatar');1168if($git_avatareq'gravatar') {1169$git_avatar=''unless(eval{require Digest::MD5;1; });1170}elsif($git_avatareq'picon') {1171# no dependencies1172}else{1173$git_avatar='';1174}11751176our@extra_branch_refs= gitweb_get_feature('extra-branch-refs');1177@extra_branch_refs= filter_and_validate_refs (@extra_branch_refs);1178}11791180sub get_branch_refs {1181return('heads',@extra_branch_refs);1182}11831184# custom error handler: 'die <message>' is Internal Server Error1185sub handle_errors_html {1186my$msg=shift;# it is already HTML escaped11871188# to avoid infinite loop where error occurs in die_error,1189# change handler to default handler, disabling handle_errors_html1190 set_message("Error occurred when inside die_error:\n$msg");11911192# you cannot jump out of die_error when called as error handler;1193# the subroutine set via CGI::Carp::set_message is called _after_1194# HTTP headers are already written, so it cannot write them itself1195 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1196}1197set_message(\&handle_errors_html);11981199# dispatch1200sub dispatch {1201if(!defined$action) {1202if(defined$hash) {1203$action= git_get_type($hash);1204$actionor die_error(404,"Object does not exist");1205}elsif(defined$hash_base&&defined$file_name) {1206$action= git_get_type("$hash_base:$file_name");1207$actionor die_error(404,"File or directory does not exist");1208}elsif(defined$project) {1209$action='summary';1210}else{1211$action='project_list';1212}1213}1214if(!defined($actions{$action})) {1215 die_error(400,"Unknown action");1216}1217if($action!~m/^(?:opml|project_list|project_index)$/&&1218!$project) {1219 die_error(400,"Project needed");1220}1221$actions{$action}->();1222}12231224sub reset_timer {1225our$t0= [ gettimeofday() ]1226ifdefined$t0;1227our$number_of_git_cmds=0;1228}12291230our$first_request=1;1231sub run_request {1232 reset_timer();12331234 evaluate_uri();1235if($first_request) {1236 evaluate_gitweb_config();1237 evaluate_git_version();1238}1239if($per_request_config) {1240if(ref($per_request_config)eq'CODE') {1241$per_request_config->();1242}elsif(!$first_request) {1243 evaluate_gitweb_config();1244}1245}1246 check_loadavg();12471248# $projectroot and $projects_list might be set in gitweb config file1249$projects_list||=$projectroot;12501251 evaluate_query_params();1252 evaluate_path_info();1253 evaluate_and_validate_params();1254 evaluate_git_dir();12551256 configure_gitweb_features();12571258 dispatch();1259}12601261our$is_last_request=sub{1};1262our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1263our$CGI='CGI';1264our$cgi;1265sub configure_as_fcgi {1266require CGI::Fast;1267our$CGI='CGI::Fast';12681269my$request_number=0;1270# let each child service 100 requests1271our$is_last_request=sub{ ++$request_number>100};1272}1273sub evaluate_argv {1274my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1275 configure_as_fcgi()1276if$script_name=~/\.fcgi$/;12771278return unless(@ARGV);12791280require Getopt::Long;1281 Getopt::Long::GetOptions(1282'fastcgi|fcgi|f'=> \&configure_as_fcgi,1283'nproc|n=i'=>sub{1284my($arg,$val) =@_;1285return unlesseval{require FCGI::ProcManager;1; };1286my$proc_manager= FCGI::ProcManager->new({1287 n_processes =>$val,1288});1289our$pre_listen_hook=sub{$proc_manager->pm_manage() };1290our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1291our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1292},1293);1294}12951296sub run {1297 evaluate_argv();12981299$first_request=1;1300$pre_listen_hook->()1301if$pre_listen_hook;13021303 REQUEST:1304while($cgi=$CGI->new()) {1305$pre_dispatch_hook->()1306if$pre_dispatch_hook;13071308 run_request();13091310$post_dispatch_hook->()1311if$post_dispatch_hook;1312$first_request=0;13131314last REQUEST if($is_last_request->());1315}13161317 DONE_GITWEB:13181;1319}13201321run();13221323if(defined caller) {1324# wrapped in a subroutine processing requests,1325# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1326return;1327}else{1328# pure CGI script, serving single request1329exit;1330}13311332## ======================================================================1333## action links13341335# possible values of extra options1336# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1337# -replay => 1 - start from a current view (replay with modifications)1338# -path_info => 0|1 - don't use/use path_info URL (if possible)1339# -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone1340sub href {1341my%params=@_;1342# default is to use -absolute url() i.e. $my_uri1343my$href=$params{-full} ?$my_url:$my_uri;13441345# implicit -replay, must be first of implicit params1346$params{-replay} =1if(keys%params==1&&$params{-anchor});13471348$params{'project'} =$projectunlessexists$params{'project'};13491350if($params{-replay}) {1351while(my($name,$symbol) =each%cgi_param_mapping) {1352if(!exists$params{$name}) {1353$params{$name} =$input_params{$name};1354}1355}1356}13571358my$use_pathinfo= gitweb_check_feature('pathinfo');1359if(defined$params{'project'} &&1360(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1361# try to put as many parameters as possible in PATH_INFO:1362# - project name1363# - action1364# - hash_parent or hash_parent_base:/file_parent1365# - hash or hash_base:/filename1366# - the snapshot_format as an appropriate suffix13671368# When the script is the root DirectoryIndex for the domain,1369# $href here would be something like http://gitweb.example.com/1370# Thus, we strip any trailing / from $href, to spare us double1371# slashes in the final URL1372$href=~ s,/$,,;13731374# Then add the project name, if present1375$href.="/".esc_path_info($params{'project'});1376delete$params{'project'};13771378# since we destructively absorb parameters, we keep this1379# boolean that remembers if we're handling a snapshot1380my$is_snapshot=$params{'action'}eq'snapshot';13811382# Summary just uses the project path URL, any other action is1383# added to the URL1384if(defined$params{'action'}) {1385$href.="/".esc_path_info($params{'action'})1386unless$params{'action'}eq'summary';1387delete$params{'action'};1388}13891390# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1391# stripping nonexistent or useless pieces1392$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1393||$params{'hash_parent'} ||$params{'hash'});1394if(defined$params{'hash_base'}) {1395if(defined$params{'hash_parent_base'}) {1396$href.= esc_path_info($params{'hash_parent_base'});1397# skip the file_parent if it's the same as the file_name1398if(defined$params{'file_parent'}) {1399if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1400delete$params{'file_parent'};1401}elsif($params{'file_parent'} !~/\.\./) {1402$href.=":/".esc_path_info($params{'file_parent'});1403delete$params{'file_parent'};1404}1405}1406$href.="..";1407delete$params{'hash_parent'};1408delete$params{'hash_parent_base'};1409}elsif(defined$params{'hash_parent'}) {1410$href.= esc_path_info($params{'hash_parent'})."..";1411delete$params{'hash_parent'};1412}14131414$href.= esc_path_info($params{'hash_base'});1415if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1416$href.=":/".esc_path_info($params{'file_name'});1417delete$params{'file_name'};1418}1419delete$params{'hash'};1420delete$params{'hash_base'};1421}elsif(defined$params{'hash'}) {1422$href.= esc_path_info($params{'hash'});1423delete$params{'hash'};1424}14251426# If the action was a snapshot, we can absorb the1427# snapshot_format parameter too1428if($is_snapshot) {1429my$fmt=$params{'snapshot_format'};1430# snapshot_format should always be defined when href()1431# is called, but just in case some code forgets, we1432# fall back to the default1433$fmt||=$snapshot_fmts[0];1434$href.=$known_snapshot_formats{$fmt}{'suffix'};1435delete$params{'snapshot_format'};1436}1437}14381439# now encode the parameters explicitly1440my@result= ();1441for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1442my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1443if(defined$params{$name}) {1444if(ref($params{$name})eq"ARRAY") {1445foreachmy$par(@{$params{$name}}) {1446push@result,$symbol."=". esc_param($par);1447}1448}else{1449push@result,$symbol."=". esc_param($params{$name});1450}1451}1452}1453$href.="?".join(';',@result)ifscalar@result;14541455# final transformation: trailing spaces must be escaped (URI-encoded)1456$href=~s/(\s+)$/CGI::escape($1)/e;14571458if($params{-anchor}) {1459$href.="#".esc_param($params{-anchor});1460}14611462return$href;1463}146414651466## ======================================================================1467## validation, quoting/unquoting and escaping14681469sub is_valid_action {1470my$input=shift;1471returnundefunlessexists$actions{$input};1472return1;1473}14741475sub is_valid_project {1476my$input=shift;14771478return unlessdefined$input;1479if(!is_valid_pathname($input) ||1480!(-d "$projectroot/$input") ||1481!check_export_ok("$projectroot/$input") ||1482($strict_export&& !project_in_list($input))) {1483returnundef;1484}else{1485return1;1486}1487}14881489sub is_valid_pathname {1490my$input=shift;14911492returnundefunlessdefined$input;1493# no '.' or '..' as elements of path, i.e. no '.' nor '..'1494# at the beginning, at the end, and between slashes.1495# also this catches doubled slashes1496if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1497returnundef;1498}1499# no null characters1500if($input=~m!\0!) {1501returnundef;1502}1503return1;1504}15051506sub is_valid_ref_format {1507my$input=shift;15081509returnundefunlessdefined$input;1510# restrictions on ref name according to git-check-ref-format1511if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1512returnundef;1513}1514return1;1515}15161517sub is_valid_refname {1518my$input=shift;15191520returnundefunlessdefined$input;1521# textual hashes are O.K.1522if($input=~m/^[0-9a-fA-F]{40}$/) {1523return1;1524}1525# it must be correct pathname1526 is_valid_pathname($input)orreturnundef;1527# check git-check-ref-format restrictions1528 is_valid_ref_format($input)orreturnundef;1529return1;1530}15311532# decode sequences of octets in utf8 into Perl's internal form,1533# which is utf-8 with utf8 flag set if needed. gitweb writes out1534# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1535sub to_utf8 {1536my$str=shift;1537returnundefunlessdefined$str;15381539if(utf8::is_utf8($str) || utf8::decode($str)) {1540return$str;1541}else{1542return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1543}1544}15451546# quote unsafe chars, but keep the slash, even when it's not1547# correct, but quoted slashes look too horrible in bookmarks1548sub esc_param {1549my$str=shift;1550returnundefunlessdefined$str;1551$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1552$str=~s/ /\+/g;1553return$str;1554}15551556# the quoting rules for path_info fragment are slightly different1557sub esc_path_info {1558my$str=shift;1559returnundefunlessdefined$str;15601561# path_info doesn't treat '+' as space (specially), but '?' must be escaped1562$str=~s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;15631564return$str;1565}15661567# quote unsafe chars in whole URL, so some characters cannot be quoted1568sub esc_url {1569my$str=shift;1570returnundefunlessdefined$str;1571$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1572$str=~s/ /\+/g;1573return$str;1574}15751576# quote unsafe characters in HTML attributes1577sub esc_attr {15781579# for XHTML conformance escaping '"' to '"' is not enough1580return esc_html(@_);1581}15821583# replace invalid utf8 character with SUBSTITUTION sequence1584sub esc_html {1585my$str=shift;1586my%opts=@_;15871588returnundefunlessdefined$str;15891590$str= to_utf8($str);1591$str=$cgi->escapeHTML($str);1592if($opts{'-nbsp'}) {1593$str=~s/ / /g;1594}1595$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1596return$str;1597}15981599# quote control characters and escape filename to HTML1600sub esc_path {1601my$str=shift;1602my%opts=@_;16031604returnundefunlessdefined$str;16051606$str= to_utf8($str);1607$str=$cgi->escapeHTML($str);1608if($opts{'-nbsp'}) {1609$str=~s/ / /g;1610}1611$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1612return$str;1613}16141615# Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)1616sub sanitize {1617my$str=shift;16181619returnundefunlessdefined$str;16201621$str= to_utf8($str);1622$str=~ s|([[:cntrl:]])|(index("\t\n\r",$1) != -1?$1: quot_cec($1))|eg;1623return$str;1624}16251626# Make control characters "printable", using character escape codes (CEC)1627sub quot_cec {1628my$cntrl=shift;1629my%opts=@_;1630my%es= (# character escape codes, aka escape sequences1631"\t"=>'\t',# tab (HT)1632"\n"=>'\n',# line feed (LF)1633"\r"=>'\r',# carrige return (CR)1634"\f"=>'\f',# form feed (FF)1635"\b"=>'\b',# backspace (BS)1636"\a"=>'\a',# alarm (bell) (BEL)1637"\e"=>'\e',# escape (ESC)1638"\013"=>'\v',# vertical tab (VT)1639"\000"=>'\0',# nul character (NUL)1640);1641my$chr= ( (exists$es{$cntrl})1642?$es{$cntrl}1643:sprintf('\%2x',ord($cntrl)) );1644if($opts{-nohtml}) {1645return$chr;1646}else{1647return"<span class=\"cntrl\">$chr</span>";1648}1649}16501651# Alternatively use unicode control pictures codepoints,1652# Unicode "printable representation" (PR)1653sub quot_upr {1654my$cntrl=shift;1655my%opts=@_;16561657my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1658if($opts{-nohtml}) {1659return$chr;1660}else{1661return"<span class=\"cntrl\">$chr</span>";1662}1663}16641665# git may return quoted and escaped filenames1666sub unquote {1667my$str=shift;16681669sub unq {1670my$seq=shift;1671my%es= (# character escape codes, aka escape sequences1672't'=>"\t",# tab (HT, TAB)1673'n'=>"\n",# newline (NL)1674'r'=>"\r",# return (CR)1675'f'=>"\f",# form feed (FF)1676'b'=>"\b",# backspace (BS)1677'a'=>"\a",# alarm (bell) (BEL)1678'e'=>"\e",# escape (ESC)1679'v'=>"\013",# vertical tab (VT)1680);16811682if($seq=~m/^[0-7]{1,3}$/) {1683# octal char sequence1684returnchr(oct($seq));1685}elsif(exists$es{$seq}) {1686# C escape sequence, aka character escape code1687return$es{$seq};1688}1689# quoted ordinary character1690return$seq;1691}16921693if($str=~m/^"(.*)"$/) {1694# needs unquoting1695$str=$1;1696$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1697}1698return$str;1699}17001701# escape tabs (convert tabs to spaces)1702sub untabify {1703my$line=shift;17041705while((my$pos=index($line,"\t")) != -1) {1706if(my$count= (8- ($pos%8))) {1707my$spaces=' ' x $count;1708$line=~s/\t/$spaces/;1709}1710}17111712return$line;1713}17141715sub project_in_list {1716my$project=shift;1717my@list= git_get_projects_list();1718return@list&&scalar(grep{$_->{'path'}eq$project}@list);1719}17201721## ----------------------------------------------------------------------1722## HTML aware string manipulation17231724# Try to chop given string on a word boundary between position1725# $len and $len+$add_len. If there is no word boundary there,1726# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1727# (marking chopped part) would be longer than given string.1728sub chop_str {1729my$str=shift;1730my$len=shift;1731my$add_len=shift||10;1732my$where=shift||'right';# 'left' | 'center' | 'right'17331734# Make sure perl knows it is utf8 encoded so we don't1735# cut in the middle of a utf8 multibyte char.1736$str= to_utf8($str);17371738# allow only $len chars, but don't cut a word if it would fit in $add_len1739# if it doesn't fit, cut it if it's still longer than the dots we would add1740# remove chopped character entities entirely17411742# when chopping in the middle, distribute $len into left and right part1743# return early if chopping wouldn't make string shorter1744if($whereeq'center') {1745return$strif($len+5>=length($str));# filler is length 51746$len=int($len/2);1747}else{1748return$strif($len+4>=length($str));# filler is length 41749}17501751# regexps: ending and beginning with word part up to $add_len1752my$endre=qr/.{$len}\w{0,$add_len}/;1753my$begre=qr/\w{0,$add_len}.{$len}/;17541755if($whereeq'left') {1756$str=~m/^(.*?)($begre)$/;1757my($lead,$body) = ($1,$2);1758if(length($lead) >4) {1759$lead=" ...";1760}1761return"$lead$body";17621763}elsif($whereeq'center') {1764$str=~m/^($endre)(.*)$/;1765my($left,$str) = ($1,$2);1766$str=~m/^(.*?)($begre)$/;1767my($mid,$right) = ($1,$2);1768if(length($mid) >5) {1769$mid=" ... ";1770}1771return"$left$mid$right";17721773}else{1774$str=~m/^($endre)(.*)$/;1775my$body=$1;1776my$tail=$2;1777if(length($tail) >4) {1778$tail="... ";1779}1780return"$body$tail";1781}1782}17831784# takes the same arguments as chop_str, but also wraps a <span> around the1785# result with a title attribute if it does get chopped. Additionally, the1786# string is HTML-escaped.1787sub chop_and_escape_str {1788my($str) =@_;17891790my$chopped= chop_str(@_);1791$str= to_utf8($str);1792if($choppedeq$str) {1793return esc_html($chopped);1794}else{1795$str=~s/[[:cntrl:]]/?/g;1796return$cgi->span({-title=>$str}, esc_html($chopped));1797}1798}17991800# Highlight selected fragments of string, using given CSS class,1801# and escape HTML. It is assumed that fragments do not overlap.1802# Regions are passed as list of pairs (array references).1803#1804# Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns1805# '<span class="mark">foo</span>bar'1806sub esc_html_hl_regions {1807my($str,$css_class,@sel) =@_;1808my%opts=grep{ref($_)ne'ARRAY'}@sel;1809@sel=grep{ref($_)eq'ARRAY'}@sel;1810return esc_html($str,%opts)unless@sel;18111812my$out='';1813my$pos=0;18141815formy$s(@sel) {1816my($begin,$end) =@$s;18171818# Don't create empty <span> elements.1819next if$end<=$begin;18201821my$escaped= esc_html(substr($str,$begin,$end-$begin),1822%opts);18231824$out.= esc_html(substr($str,$pos,$begin-$pos),%opts)1825if($begin-$pos>0);1826$out.=$cgi->span({-class=>$css_class},$escaped);18271828$pos=$end;1829}1830$out.= esc_html(substr($str,$pos),%opts)1831if($pos<length($str));18321833return$out;1834}18351836# return positions of beginning and end of each match1837sub matchpos_list {1838my($str,$regexp) =@_;1839return unless(defined$str&&defined$regexp);18401841my@matches;1842while($str=~/$regexp/g) {1843push@matches, [$-[0],$+[0]];1844}1845return@matches;1846}18471848# highlight match (if any), and escape HTML1849sub esc_html_match_hl {1850my($str,$regexp) =@_;1851return esc_html($str)unlessdefined$regexp;18521853my@matches= matchpos_list($str,$regexp);1854return esc_html($str)unless@matches;18551856return esc_html_hl_regions($str,'match',@matches);1857}185818591860# highlight match (if any) of shortened string, and escape HTML1861sub esc_html_match_hl_chopped {1862my($str,$chopped,$regexp) =@_;1863return esc_html_match_hl($str,$regexp)unlessdefined$chopped;18641865my@matches= matchpos_list($str,$regexp);1866return esc_html($chopped)unless@matches;18671868# filter matches so that we mark chopped string1869my$tail="... ";# see chop_str1870unless($chopped=~s/\Q$tail\E$//) {1871$tail='';1872}1873my$chop_len=length($chopped);1874my$tail_len=length($tail);1875my@filtered;18761877formy$m(@matches) {1878if($m->[0] >$chop_len) {1879push@filtered, [$chop_len,$chop_len+$tail_len]if($tail_len>0);1880last;1881}elsif($m->[1] >$chop_len) {1882push@filtered, [$m->[0],$chop_len+$tail_len];1883last;1884}1885push@filtered,$m;1886}18871888return esc_html_hl_regions($chopped.$tail,'match',@filtered);1889}18901891## ----------------------------------------------------------------------1892## functions returning short strings18931894# CSS class for given age value (in seconds)1895sub age_class {1896my$age=shift;18971898if(!defined$age) {1899return"noage";1900}elsif($age<60*60*2) {1901return"age0";1902}elsif($age<60*60*24*2) {1903return"age1";1904}else{1905return"age2";1906}1907}19081909# convert age in seconds to "nn units ago" string1910sub age_string {1911my$age=shift;1912my$age_str;19131914if($age>60*60*24*365*2) {1915$age_str= (int$age/60/60/24/365);1916$age_str.=" years ago";1917}elsif($age>60*60*24*(365/12)*2) {1918$age_str=int$age/60/60/24/(365/12);1919$age_str.=" months ago";1920}elsif($age>60*60*24*7*2) {1921$age_str=int$age/60/60/24/7;1922$age_str.=" weeks ago";1923}elsif($age>60*60*24*2) {1924$age_str=int$age/60/60/24;1925$age_str.=" days ago";1926}elsif($age>60*60*2) {1927$age_str=int$age/60/60;1928$age_str.=" hours ago";1929}elsif($age>60*2) {1930$age_str=int$age/60;1931$age_str.=" min ago";1932}elsif($age>2) {1933$age_str=int$age;1934$age_str.=" sec ago";1935}else{1936$age_str.=" right now";1937}1938return$age_str;1939}19401941useconstant{1942 S_IFINVALID =>0030000,1943 S_IFGITLINK =>0160000,1944};19451946# submodule/subproject, a commit object reference1947sub S_ISGITLINK {1948my$mode=shift;19491950return(($mode& S_IFMT) == S_IFGITLINK)1951}19521953# convert file mode in octal to symbolic file mode string1954sub mode_str {1955my$mode=oct shift;19561957if(S_ISGITLINK($mode)) {1958return'm---------';1959}elsif(S_ISDIR($mode& S_IFMT)) {1960return'drwxr-xr-x';1961}elsif(S_ISLNK($mode)) {1962return'lrwxrwxrwx';1963}elsif(S_ISREG($mode)) {1964# git cares only about the executable bit1965if($mode& S_IXUSR) {1966return'-rwxr-xr-x';1967}else{1968return'-rw-r--r--';1969};1970}else{1971return'----------';1972}1973}19741975# convert file mode in octal to file type string1976sub file_type {1977my$mode=shift;19781979if($mode!~m/^[0-7]+$/) {1980return$mode;1981}else{1982$mode=oct$mode;1983}19841985if(S_ISGITLINK($mode)) {1986return"submodule";1987}elsif(S_ISDIR($mode& S_IFMT)) {1988return"directory";1989}elsif(S_ISLNK($mode)) {1990return"symlink";1991}elsif(S_ISREG($mode)) {1992return"file";1993}else{1994return"unknown";1995}1996}19971998# convert file mode in octal to file type description string1999sub file_type_long {2000my$mode=shift;20012002if($mode!~m/^[0-7]+$/) {2003return$mode;2004}else{2005$mode=oct$mode;2006}20072008if(S_ISGITLINK($mode)) {2009return"submodule";2010}elsif(S_ISDIR($mode& S_IFMT)) {2011return"directory";2012}elsif(S_ISLNK($mode)) {2013return"symlink";2014}elsif(S_ISREG($mode)) {2015if($mode& S_IXUSR) {2016return"executable";2017}else{2018return"file";2019};2020}else{2021return"unknown";2022}2023}202420252026## ----------------------------------------------------------------------2027## functions returning short HTML fragments, or transforming HTML fragments2028## which don't belong to other sections20292030# format line of commit message.2031sub format_log_line_html {2032my$line=shift;20332034$line= esc_html($line, -nbsp=>1);2035$line=~ s{\b([0-9a-fA-F]{8,40})\b}{2036$cgi->a({-href => href(action=>"object", hash=>$1),2037-class=>"text"},$1);2038}eg;20392040return$line;2041}20422043# format marker of refs pointing to given object20442045# the destination action is chosen based on object type and current context:2046# - for annotated tags, we choose the tag view unless it's the current view2047# already, in which case we go to shortlog view2048# - for other refs, we keep the current view if we're in history, shortlog or2049# log view, and select shortlog otherwise2050sub format_ref_marker {2051my($refs,$id) =@_;2052my$markers='';20532054if(defined$refs->{$id}) {2055foreachmy$ref(@{$refs->{$id}}) {2056# this code exploits the fact that non-lightweight tags are the2057# only indirect objects, and that they are the only objects for which2058# we want to use tag instead of shortlog as action2059my($type,$name) =qw();2060my$indirect= ($ref=~s/\^\{\}$//);2061# e.g. tags/v2.6.11 or heads/next2062if($ref=~m!^(.*?)s?/(.*)$!) {2063$type=$1;2064$name=$2;2065}else{2066$type="ref";2067$name=$ref;2068}20692070my$class=$type;2071$class.=" indirect"if$indirect;20722073my$dest_action="shortlog";20742075if($indirect) {2076$dest_action="tag"unless$actioneq"tag";2077}elsif($action=~/^(history|(short)?log)$/) {2078$dest_action=$action;2079}20802081my$dest="";2082$dest.="refs/"unless$ref=~ m!^refs/!;2083$dest.=$ref;20842085my$link=$cgi->a({2086-href => href(2087 action=>$dest_action,2088 hash=>$dest2089)},$name);20902091$markers.=" <span class=\"".esc_attr($class)."\"title=\"".esc_attr($ref)."\">".2092$link."</span>";2093}2094}20952096if($markers) {2097return' <span class="refs">'.$markers.'</span>';2098}else{2099return"";2100}2101}21022103# format, perhaps shortened and with markers, title line2104sub format_subject_html {2105my($long,$short,$href,$extra) =@_;2106$extra=''unlessdefined($extra);21072108if(length($short) <length($long)) {2109$long=~s/[[:cntrl:]]/?/g;2110return$cgi->a({-href =>$href, -class=>"list subject",2111-title => to_utf8($long)},2112 esc_html($short)) .$extra;2113}else{2114return$cgi->a({-href =>$href, -class=>"list subject"},2115 esc_html($long)) .$extra;2116}2117}21182119# Rather than recomputing the url for an email multiple times, we cache it2120# after the first hit. This gives a visible benefit in views where the avatar2121# for the same email is used repeatedly (e.g. shortlog).2122# The cache is shared by all avatar engines (currently gravatar only), which2123# are free to use it as preferred. Since only one avatar engine is used for any2124# given page, there's no risk for cache conflicts.2125our%avatar_cache= ();21262127# Compute the picon url for a given email, by using the picon search service over at2128# http://www.cs.indiana.edu/picons/search.html2129sub picon_url {2130my$email=lc shift;2131if(!$avatar_cache{$email}) {2132my($user,$domain) =split('@',$email);2133$avatar_cache{$email} =2134"//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".2135"$domain/$user/".2136"users+domains+unknown/up/single";2137}2138return$avatar_cache{$email};2139}21402141# Compute the gravatar url for a given email, if it's not in the cache already.2142# Gravatar stores only the part of the URL before the size, since that's the2143# one computationally more expensive. This also allows reuse of the cache for2144# different sizes (for this particular engine).2145sub gravatar_url {2146my$email=lc shift;2147my$size=shift;2148$avatar_cache{$email} ||=2149"//www.gravatar.com/avatar/".2150 Digest::MD5::md5_hex($email) ."?s=";2151return$avatar_cache{$email} .$size;2152}21532154# Insert an avatar for the given $email at the given $size if the feature2155# is enabled.2156sub git_get_avatar {2157my($email,%opts) =@_;2158my$pre_white= ($opts{-pad_before} ?" ":"");2159my$post_white= ($opts{-pad_after} ?" ":"");2160$opts{-size} ||='default';2161my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};2162my$url="";2163if($git_avatareq'gravatar') {2164$url= gravatar_url($email,$size);2165}elsif($git_avatareq'picon') {2166$url= picon_url($email);2167}2168# Other providers can be added by extending the if chain, defining $url2169# as needed. If no variant puts something in $url, we assume avatars2170# are completely disabled/unavailable.2171if($url) {2172return$pre_white.2173"<img width=\"$size\"".2174"class=\"avatar\"".2175"src=\"".esc_url($url)."\"".2176"alt=\"\"".2177"/>".$post_white;2178}else{2179return"";2180}2181}21822183sub format_search_author {2184my($author,$searchtype,$displaytext) =@_;2185my$have_search= gitweb_check_feature('search');21862187if($have_search) {2188my$performed="";2189if($searchtypeeq'author') {2190$performed="authored";2191}elsif($searchtypeeq'committer') {2192$performed="committed";2193}21942195return$cgi->a({-href => href(action=>"search", hash=>$hash,2196 searchtext=>$author,2197 searchtype=>$searchtype),class=>"list",2198 title=>"Search for commits$performedby$author"},2199$displaytext);22002201}else{2202return$displaytext;2203}2204}22052206# format the author name of the given commit with the given tag2207# the author name is chopped and escaped according to the other2208# optional parameters (see chop_str).2209sub format_author_html {2210my$tag=shift;2211my$co=shift;2212my$author= chop_and_escape_str($co->{'author_name'},@_);2213return"<$tagclass=\"author\">".2214 format_search_author($co->{'author_name'},"author",2215 git_get_avatar($co->{'author_email'}, -pad_after =>1) .2216$author) .2217"</$tag>";2218}22192220# format git diff header line, i.e. "diff --(git|combined|cc) ..."2221sub format_git_diff_header_line {2222my$line=shift;2223my$diffinfo=shift;2224my($from,$to) =@_;22252226if($diffinfo->{'nparents'}) {2227# combined diff2228$line=~s!^(diff (.*?) )"?.*$!$1!;2229if($to->{'href'}) {2230$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2231 esc_path($to->{'file'}));2232}else{# file was deleted (no href)2233$line.= esc_path($to->{'file'});2234}2235}else{2236# "ordinary" diff2237$line=~s!^(diff (.*?) )"?a/.*$!$1!;2238if($from->{'href'}) {2239$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},2240'a/'. esc_path($from->{'file'}));2241}else{# file was added (no href)2242$line.='a/'. esc_path($from->{'file'});2243}2244$line.=' ';2245if($to->{'href'}) {2246$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2247'b/'. esc_path($to->{'file'}));2248}else{# file was deleted2249$line.='b/'. esc_path($to->{'file'});2250}2251}22522253return"<div class=\"diff header\">$line</div>\n";2254}22552256# format extended diff header line, before patch itself2257sub format_extended_diff_header_line {2258my$line=shift;2259my$diffinfo=shift;2260my($from,$to) =@_;22612262# match <path>2263if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {2264$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},2265 esc_path($from->{'file'}));2266}2267if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {2268$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},2269 esc_path($to->{'file'}));2270}2271# match single <mode>2272if($line=~m/\s(\d{6})$/) {2273$line.='<span class="info"> ('.2274 file_type_long($1) .2275')</span>';2276}2277# match <hash>2278if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {2279# can match only for combined diff2280$line='index ';2281for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2282if($from->{'href'}[$i]) {2283$line.=$cgi->a({-href=>$from->{'href'}[$i],2284-class=>"hash"},2285substr($diffinfo->{'from_id'}[$i],0,7));2286}else{2287$line.='0' x 7;2288}2289# separator2290$line.=','if($i<$diffinfo->{'nparents'} -1);2291}2292$line.='..';2293if($to->{'href'}) {2294$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2295substr($diffinfo->{'to_id'},0,7));2296}else{2297$line.='0' x 7;2298}22992300}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {2301# can match only for ordinary diff2302my($from_link,$to_link);2303if($from->{'href'}) {2304$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},2305substr($diffinfo->{'from_id'},0,7));2306}else{2307$from_link='0' x 7;2308}2309if($to->{'href'}) {2310$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2311substr($diffinfo->{'to_id'},0,7));2312}else{2313$to_link='0' x 7;2314}2315my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});2316$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;2317}23182319return$line."<br/>\n";2320}23212322# format from-file/to-file diff header2323sub format_diff_from_to_header {2324my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2325my$line;2326my$result='';23272328$line=$from_line;2329#assert($line =~ m/^---/) if DEBUG;2330# no extra formatting for "^--- /dev/null"2331if(!$diffinfo->{'nparents'}) {2332# ordinary (single parent) diff2333if($line=~m!^--- "?a/!) {2334if($from->{'href'}) {2335$line='--- a/'.2336$cgi->a({-href=>$from->{'href'}, -class=>"path"},2337 esc_path($from->{'file'}));2338}else{2339$line='--- a/'.2340 esc_path($from->{'file'});2341}2342}2343$result.= qq!<div class="diff from_file">$line</div>\n!;23442345}else{2346# combined diff (merge commit)2347for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2348if($from->{'href'}[$i]) {2349$line='--- '.2350$cgi->a({-href=>href(action=>"blobdiff",2351 hash_parent=>$diffinfo->{'from_id'}[$i],2352 hash_parent_base=>$parents[$i],2353 file_parent=>$from->{'file'}[$i],2354 hash=>$diffinfo->{'to_id'},2355 hash_base=>$hash,2356 file_name=>$to->{'file'}),2357-class=>"path",2358-title=>"diff". ($i+1)},2359$i+1) .2360'/'.2361$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2362 esc_path($from->{'file'}[$i]));2363}else{2364$line='--- /dev/null';2365}2366$result.= qq!<div class="diff from_file">$line</div>\n!;2367}2368}23692370$line=$to_line;2371#assert($line =~ m/^\+\+\+/) if DEBUG;2372# no extra formatting for "^+++ /dev/null"2373if($line=~m!^\+\+\+ "?b/!) {2374if($to->{'href'}) {2375$line='+++ b/'.2376$cgi->a({-href=>$to->{'href'}, -class=>"path"},2377 esc_path($to->{'file'}));2378}else{2379$line='+++ b/'.2380 esc_path($to->{'file'});2381}2382}2383$result.= qq!<div class="diff to_file">$line</div>\n!;23842385return$result;2386}23872388# create note for patch simplified by combined diff2389sub format_diff_cc_simplified {2390my($diffinfo,@parents) =@_;2391my$result='';23922393$result.="<div class=\"diff header\">".2394"diff --cc ";2395if(!is_deleted($diffinfo)) {2396$result.=$cgi->a({-href => href(action=>"blob",2397 hash_base=>$hash,2398 hash=>$diffinfo->{'to_id'},2399 file_name=>$diffinfo->{'to_file'}),2400-class=>"path"},2401 esc_path($diffinfo->{'to_file'}));2402}else{2403$result.= esc_path($diffinfo->{'to_file'});2404}2405$result.="</div>\n".# class="diff header"2406"<div class=\"diff nodifferences\">".2407"Simple merge".2408"</div>\n";# class="diff nodifferences"24092410return$result;2411}24122413sub diff_line_class {2414my($line,$from,$to) =@_;24152416# ordinary diff2417my$num_sign=1;2418# combined diff2419if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2420$num_sign=scalar@{$from->{'href'}};2421}24222423my@diff_line_classifier= (2424{ regexp =>qr/^\@\@{$num_sign} /,class=>"chunk_header"},2425{ regexp =>qr/^\\/,class=>"incomplete"},2426{ regexp =>qr/^ {$num_sign}/,class=>"ctx"},2427# classifier for context must come before classifier add/rem,2428# or we would have to use more complicated regexp, for example2429# qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;2430{ regexp =>qr/^[+ ]{$num_sign}/,class=>"add"},2431{ regexp =>qr/^[- ]{$num_sign}/,class=>"rem"},2432);2433formy$clsfy(@diff_line_classifier) {2434return$clsfy->{'class'}2435if($line=~$clsfy->{'regexp'});2436}24372438# fallback2439return"";2440}24412442# assumes that $from and $to are defined and correctly filled,2443# and that $line holds a line of chunk header for unified diff2444sub format_unidiff_chunk_header {2445my($line,$from,$to) =@_;24462447my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2448$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;24492450$from_lines=0unlessdefined$from_lines;2451$to_lines=0unlessdefined$to_lines;24522453if($from->{'href'}) {2454$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2455-class=>"list"},$from_text);2456}2457if($to->{'href'}) {2458$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2459-class=>"list"},$to_text);2460}2461$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2462"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2463return$line;2464}24652466# assumes that $from and $to are defined and correctly filled,2467# and that $line holds a line of chunk header for combined diff2468sub format_cc_diff_chunk_header {2469my($line,$from,$to) =@_;24702471my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2472my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);24732474@from_text=split(' ',$ranges);2475for(my$i=0;$i<@from_text; ++$i) {2476($from_start[$i],$from_nlines[$i]) =2477(split(',',substr($from_text[$i],1)),0);2478}24792480$to_text=pop@from_text;2481$to_start=pop@from_start;2482$to_nlines=pop@from_nlines;24832484$line="<span class=\"chunk_info\">$prefix";2485for(my$i=0;$i<@from_text; ++$i) {2486if($from->{'href'}[$i]) {2487$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2488-class=>"list"},$from_text[$i]);2489}else{2490$line.=$from_text[$i];2491}2492$line.=" ";2493}2494if($to->{'href'}) {2495$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2496-class=>"list"},$to_text);2497}else{2498$line.=$to_text;2499}2500$line.="$prefix</span>".2501"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2502return$line;2503}25042505# process patch (diff) line (not to be used for diff headers),2506# returning HTML-formatted (but not wrapped) line.2507# If the line is passed as a reference, it is treated as HTML and not2508# esc_html()'ed.2509sub format_diff_line {2510my($line,$diff_class,$from,$to) =@_;25112512if(ref($line)) {2513$line=$$line;2514}else{2515chomp$line;2516$line= untabify($line);25172518if($from&&$to&&$line=~m/^\@{2} /) {2519$line= format_unidiff_chunk_header($line,$from,$to);2520}elsif($from&&$to&&$line=~m/^\@{3}/) {2521$line= format_cc_diff_chunk_header($line,$from,$to);2522}else{2523$line= esc_html($line, -nbsp=>1);2524}2525}25262527my$diff_classes="diff";2528$diff_classes.="$diff_class"if($diff_class);2529$line="<div class=\"$diff_classes\">$line</div>\n";25302531return$line;2532}25332534# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2535# linked. Pass the hash of the tree/commit to snapshot.2536sub format_snapshot_links {2537my($hash) =@_;2538my$num_fmts=@snapshot_fmts;2539if($num_fmts>1) {2540# A parenthesized list of links bearing format names.2541# e.g. "snapshot (_tar.gz_ _zip_)"2542return"snapshot (".join(' ',map2543$cgi->a({2544-href => href(2545 action=>"snapshot",2546 hash=>$hash,2547 snapshot_format=>$_2548)2549},$known_snapshot_formats{$_}{'display'})2550,@snapshot_fmts) .")";2551}elsif($num_fmts==1) {2552# A single "snapshot" link whose tooltip bears the format name.2553# i.e. "_snapshot_"2554my($fmt) =@snapshot_fmts;2555return2556$cgi->a({2557-href => href(2558 action=>"snapshot",2559 hash=>$hash,2560 snapshot_format=>$fmt2561),2562-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2563},"snapshot");2564}else{# $num_fmts == 02565returnundef;2566}2567}25682569## ......................................................................2570## functions returning values to be passed, perhaps after some2571## transformation, to other functions; e.g. returning arguments to href()25722573# returns hash to be passed to href to generate gitweb URL2574# in -title key it returns description of link2575sub get_feed_info {2576my$format=shift||'Atom';2577my%res= (action =>lc($format));2578my$matched_ref=0;25792580# feed links are possible only for project views2581return unless(defined$project);2582# some views should link to OPML, or to generic project feed,2583# or don't have specific feed yet (so they should use generic)2584return if(!$action||$action=~/^(?:tags|heads|forks|tag|search)$/x);25852586my$branch=undef;2587# branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix2588# (fullname) to differentiate from tag links; this also makes2589# possible to detect branch links2590formy$ref(get_branch_refs()) {2591if((defined$hash_base&&$hash_base=~m!^refs/\Q$ref\E/(.*)$!) ||2592(defined$hash&&$hash=~m!^refs/\Q$ref\E/(.*)$!)) {2593$branch=$1;2594$matched_ref=$ref;2595last;2596}2597}2598# find log type for feed description (title)2599my$type='log';2600if(defined$file_name) {2601$type="history of$file_name";2602$type.="/"if($actioneq'tree');2603$type.=" on '$branch'"if(defined$branch);2604}else{2605$type="log of$branch"if(defined$branch);2606}26072608$res{-title} =$type;2609$res{'hash'} = (defined$branch?"refs/$matched_ref/$branch":undef);2610$res{'file_name'} =$file_name;26112612return%res;2613}26142615## ----------------------------------------------------------------------2616## git utility subroutines, invoking git commands26172618# returns path to the core git executable and the --git-dir parameter as list2619sub git_cmd {2620$number_of_git_cmds++;2621return$GIT,'--git-dir='.$git_dir;2622}26232624# quote the given arguments for passing them to the shell2625# quote_command("command", "arg 1", "arg with ' and ! characters")2626# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2627# Try to avoid using this function wherever possible.2628sub quote_command {2629returnjoin(' ',2630map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2631}26322633# get HEAD ref of given project as hash2634sub git_get_head_hash {2635return git_get_full_hash(shift,'HEAD');2636}26372638sub git_get_full_hash {2639return git_get_hash(@_);2640}26412642sub git_get_short_hash {2643return git_get_hash(@_,'--short=7');2644}26452646sub git_get_hash {2647my($project,$hash,@options) =@_;2648my$o_git_dir=$git_dir;2649my$retval=undef;2650$git_dir="$projectroot/$project";2651if(open my$fd,'-|', git_cmd(),'rev-parse',2652'--verify','-q',@options,$hash) {2653$retval= <$fd>;2654chomp$retvalifdefined$retval;2655close$fd;2656}2657if(defined$o_git_dir) {2658$git_dir=$o_git_dir;2659}2660return$retval;2661}26622663# get type of given object2664sub git_get_type {2665my$hash=shift;26662667open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2668my$type= <$fd>;2669close$fdorreturn;2670chomp$type;2671return$type;2672}26732674# repository configuration2675our$config_file='';2676our%config;26772678# store multiple values for single key as anonymous array reference2679# single values stored directly in the hash, not as [ <value> ]2680sub hash_set_multi {2681my($hash,$key,$value) =@_;26822683if(!exists$hash->{$key}) {2684$hash->{$key} =$value;2685}elsif(!ref$hash->{$key}) {2686$hash->{$key} = [$hash->{$key},$value];2687}else{2688push@{$hash->{$key}},$value;2689}2690}26912692# return hash of git project configuration2693# optionally limited to some section, e.g. 'gitweb'2694sub git_parse_project_config {2695my$section_regexp=shift;2696my%config;26972698local$/="\0";26992700open my$fh,"-|", git_cmd(),"config",'-z','-l',2701orreturn;27022703while(my$keyval= <$fh>) {2704chomp$keyval;2705my($key,$value) =split(/\n/,$keyval,2);27062707 hash_set_multi(\%config,$key,$value)2708if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2709}2710close$fh;27112712return%config;2713}27142715# convert config value to boolean: 'true' or 'false'2716# no value, number > 0, 'true' and 'yes' values are true2717# rest of values are treated as false (never as error)2718sub config_to_bool {2719my$val=shift;27202721return1if!defined$val;# section.key27222723# strip leading and trailing whitespace2724$val=~s/^\s+//;2725$val=~s/\s+$//;27262727return(($val=~/^\d+$/&&$val) ||# section.key = 12728($val=~/^(?:true|yes)$/i));# section.key = true2729}27302731# convert config value to simple decimal number2732# an optional value suffix of 'k', 'm', or 'g' will cause the value2733# to be multiplied by 1024, 1048576, or 10737418242734sub config_to_int {2735my$val=shift;27362737# strip leading and trailing whitespace2738$val=~s/^\s+//;2739$val=~s/\s+$//;27402741if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2742$unit=lc($unit);2743# unknown unit is treated as 12744return$num* ($uniteq'g'?1073741824:2745$uniteq'm'?1048576:2746$uniteq'k'?1024:1);2747}2748return$val;2749}27502751# convert config value to array reference, if needed2752sub config_to_multi {2753my$val=shift;27542755returnref($val) ?$val: (defined($val) ? [$val] : []);2756}27572758sub git_get_project_config {2759my($key,$type) =@_;27602761return unlessdefined$git_dir;27622763# key sanity check2764return unless($key);2765# only subsection, if exists, is case sensitive,2766# and not lowercased by 'git config -z -l'2767if(my($hi,$mi,$lo) = ($key=~/^([^.]*)\.(.*)\.([^.]*)$/)) {2768$lo=~s/_//g;2769$key=join(".",lc($hi),$mi,lc($lo));2770return if($lo=~/\W/||$hi=~/\W/);2771}else{2772$key=lc($key);2773$key=~s/_//g;2774return if($key=~/\W/);2775}2776$key=~s/^gitweb\.//;27772778# type sanity check2779if(defined$type) {2780$type=~s/^--//;2781$type=undef2782unless($typeeq'bool'||$typeeq'int');2783}27842785# get config2786if(!defined$config_file||2787$config_filene"$git_dir/config") {2788%config= git_parse_project_config('gitweb');2789$config_file="$git_dir/config";2790}27912792# check if config variable (key) exists2793return unlessexists$config{"gitweb.$key"};27942795# ensure given type2796if(!defined$type) {2797return$config{"gitweb.$key"};2798}elsif($typeeq'bool') {2799# backward compatibility: 'git config --bool' returns true/false2800return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2801}elsif($typeeq'int') {2802return config_to_int($config{"gitweb.$key"});2803}2804return$config{"gitweb.$key"};2805}28062807# get hash of given path at given ref2808sub git_get_hash_by_path {2809my$base=shift;2810my$path=shift||returnundef;2811my$type=shift;28122813$path=~ s,/+$,,;28142815open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2816or die_error(500,"Open git-ls-tree failed");2817my$line= <$fd>;2818close$fdorreturnundef;28192820if(!defined$line) {2821# there is no tree or hash given by $path at $base2822returnundef;2823}28242825#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2826$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2827if(defined$type&&$typene$2) {2828# type doesn't match2829returnundef;2830}2831return$3;2832}28332834# get path of entry with given hash at given tree-ish (ref)2835# used to get 'from' filename for combined diff (merge commit) for renames2836sub git_get_path_by_hash {2837my$base=shift||return;2838my$hash=shift||return;28392840local$/="\0";28412842open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2843orreturnundef;2844while(my$line= <$fd>) {2845chomp$line;28462847#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2848#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2849if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2850close$fd;2851return$1;2852}2853}2854close$fd;2855returnundef;2856}28572858## ......................................................................2859## git utility functions, directly accessing git repository28602861# get the value of config variable either from file named as the variable2862# itself in the repository ($GIT_DIR/$name file), or from gitweb.$name2863# configuration variable in the repository config file.2864sub git_get_file_or_project_config {2865my($path,$name) =@_;28662867$git_dir="$projectroot/$path";2868open my$fd,'<',"$git_dir/$name"2869orreturn git_get_project_config($name);2870my$conf= <$fd>;2871close$fd;2872if(defined$conf) {2873chomp$conf;2874}2875return$conf;2876}28772878sub git_get_project_description {2879my$path=shift;2880return git_get_file_or_project_config($path,'description');2881}28822883sub git_get_project_category {2884my$path=shift;2885return git_get_file_or_project_config($path,'category');2886}288728882889# supported formats:2890# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2891# - if its contents is a number, use it as tag weight,2892# - otherwise add a tag with weight 12893# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2894# the same value multiple times increases tag weight2895# * `gitweb.ctag' multi-valued repo config variable2896sub git_get_project_ctags {2897my$project=shift;2898my$ctags= {};28992900$git_dir="$projectroot/$project";2901if(opendir my$dh,"$git_dir/ctags") {2902my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2903foreachmy$tagfile(@files) {2904open my$ct,'<',$tagfile2905ornext;2906my$val= <$ct>;2907chomp$valif$val;2908close$ct;29092910(my$ctag=$tagfile) =~ s#.*/##;2911if($val=~/^\d+$/) {2912$ctags->{$ctag} =$val;2913}else{2914$ctags->{$ctag} =1;2915}2916}2917closedir$dh;29182919}elsif(open my$fh,'<',"$git_dir/ctags") {2920while(my$line= <$fh>) {2921chomp$line;2922$ctags->{$line}++if$line;2923}2924close$fh;29252926}else{2927my$taglist= config_to_multi(git_get_project_config('ctag'));2928foreachmy$tag(@$taglist) {2929$ctags->{$tag}++;2930}2931}29322933return$ctags;2934}29352936# return hash, where keys are content tags ('ctags'),2937# and values are sum of weights of given tag in every project2938sub git_gather_all_ctags {2939my$projects=shift;2940my$ctags= {};29412942foreachmy$p(@$projects) {2943foreachmy$ct(keys%{$p->{'ctags'}}) {2944$ctags->{$ct} +=$p->{'ctags'}->{$ct};2945}2946}29472948return$ctags;2949}29502951sub git_populate_project_tagcloud {2952my$ctags=shift;29532954# First, merge different-cased tags; tags vote on casing2955my%ctags_lc;2956foreach(keys%$ctags) {2957$ctags_lc{lc$_}->{count} +=$ctags->{$_};2958if(not$ctags_lc{lc$_}->{topcount}2959or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2960$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2961$ctags_lc{lc$_}->{topname} =$_;2962}2963}29642965my$cloud;2966my$matched=$input_params{'ctag'};2967if(eval{require HTML::TagCloud;1; }) {2968$cloud= HTML::TagCloud->new;2969foreachmy$ctag(sort keys%ctags_lc) {2970# Pad the title with spaces so that the cloud looks2971# less crammed.2972my$title= esc_html($ctags_lc{$ctag}->{topname});2973$title=~s/ / /g;2974$title=~s/^/ /g;2975$title=~s/$/ /g;2976if(defined$matched&&$matchedeq$ctag) {2977$title=qq(<span class="match">$title</span>);2978}2979$cloud->add($title, href(project=>undef, ctag=>$ctag),2980$ctags_lc{$ctag}->{count});2981}2982}else{2983$cloud= {};2984foreachmy$ctag(keys%ctags_lc) {2985my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2986if(defined$matched&&$matchedeq$ctag) {2987$title=qq(<span class="match">$title</span>);2988}2989$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};2990$cloud->{$ctag}{ctag} =2991$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);2992}2993}2994return$cloud;2995}29962997sub git_show_project_tagcloud {2998my($cloud,$count) =@_;2999if(ref$cloudeq'HTML::TagCloud') {3000return$cloud->html_and_css($count);3001}else{3002my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;3003return3004'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.3005join(', ',map{3006$cloud->{$_}->{'ctag'}3007}splice(@tags,0,$count)) .3008'</div>';3009}3010}30113012sub git_get_project_url_list {3013my$path=shift;30143015$git_dir="$projectroot/$path";3016open my$fd,'<',"$git_dir/cloneurl"3017orreturnwantarray?3018@{ config_to_multi(git_get_project_config('url')) } :3019 config_to_multi(git_get_project_config('url'));3020my@git_project_url_list=map{chomp;$_} <$fd>;3021close$fd;30223023returnwantarray?@git_project_url_list: \@git_project_url_list;3024}30253026sub git_get_projects_list {3027my$filter=shift||'';3028my$paranoid=shift;3029my@list;30303031if(-d $projects_list) {3032# search in directory3033my$dir=$projects_list;3034# remove the trailing "/"3035$dir=~s!/+$!!;3036my$pfxlen=length("$dir");3037my$pfxdepth= ($dir=~tr!/!!);3038# when filtering, search only given subdirectory3039if($filter&& !$paranoid) {3040$dir.="/$filter";3041$dir=~s!/+$!!;3042}30433044 File::Find::find({3045 follow_fast =>1,# follow symbolic links3046 follow_skip =>2,# ignore duplicates3047 dangling_symlinks =>0,# ignore dangling symlinks, silently3048 wanted =>sub{3049# global variables3050our$project_maxdepth;3051our$projectroot;3052# skip project-list toplevel, if we get it.3053return if(m!^[/.]$!);3054# only directories can be git repositories3055return unless(-d $_);3056# don't traverse too deep (Find is super slow on os x)3057# $project_maxdepth excludes depth of $projectroot3058if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {3059$File::Find::prune =1;3060return;3061}30623063my$path=substr($File::Find::name,$pfxlen+1);3064# paranoidly only filter here3065if($paranoid&&$filter&&$path!~m!^\Q$filter\E/!) {3066next;3067}3068# we check related file in $projectroot3069if(check_export_ok("$projectroot/$path")) {3070push@list, { path =>$path};3071$File::Find::prune =1;3072}3073},3074},"$dir");30753076}elsif(-f $projects_list) {3077# read from file(url-encoded):3078# 'git%2Fgit.git Linus+Torvalds'3079# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'3080# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'3081open my$fd,'<',$projects_listorreturn;3082 PROJECT:3083while(my$line= <$fd>) {3084chomp$line;3085my($path,$owner) =split' ',$line;3086$path= unescape($path);3087$owner= unescape($owner);3088if(!defined$path) {3089next;3090}3091# if $filter is rpovided, check if $path begins with $filter3092if($filter&&$path!~m!^\Q$filter\E/!) {3093next;3094}3095if(check_export_ok("$projectroot/$path")) {3096my$pr= {3097 path =>$path3098};3099if($owner) {3100$pr->{'owner'} = to_utf8($owner);3101}3102push@list,$pr;3103}3104}3105close$fd;3106}3107return@list;3108}31093110# written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)3111# as side effects it sets 'forks' field to list of forks for forked projects3112sub filter_forks_from_projects_list {3113my$projects=shift;31143115my%trie;# prefix tree of directories (path components)3116# generate trie out of those directories that might contain forks3117foreachmy$pr(@$projects) {3118my$path=$pr->{'path'};3119$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory3120next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'3121next unless($path);# skip '.git' repository: tests, git-instaweb3122next unless(-d "$projectroot/$path");# containing directory exists3123$pr->{'forks'} = [];# there can be 0 or more forks of project31243125# add to trie3126my@dirs=split('/',$path);3127# walk the trie, until either runs out of components or out of trie3128my$ref= \%trie;3129while(scalar@dirs&&3130exists($ref->{$dirs[0]})) {3131$ref=$ref->{shift@dirs};3132}3133# create rest of trie structure from rest of components3134foreachmy$dir(@dirs) {3135$ref=$ref->{$dir} = {};3136}3137# create end marker, store $pr as a data3138$ref->{''} =$prif(!exists$ref->{''});3139}31403141# filter out forks, by finding shortest prefix match for paths3142my@filtered;3143 PROJECT:3144foreachmy$pr(@$projects) {3145# trie lookup3146my$ref= \%trie;3147 DIR:3148foreachmy$dir(split('/',$pr->{'path'})) {3149if(exists$ref->{''}) {3150# found [shortest] prefix, is a fork - skip it3151push@{$ref->{''}{'forks'}},$pr;3152next PROJECT;3153}3154if(!exists$ref->{$dir}) {3155# not in trie, cannot have prefix, not a fork3156push@filtered,$pr;3157next PROJECT;3158}3159# If the dir is there, we just walk one step down the trie.3160$ref=$ref->{$dir};3161}3162# we ran out of trie3163# (shouldn't happen: it's either no match, or end marker)3164push@filtered,$pr;3165}31663167return@filtered;3168}31693170# note: fill_project_list_info must be run first,3171# for 'descr_long' and 'ctags' to be filled3172sub search_projects_list {3173my($projlist,%opts) =@_;3174my$tagfilter=$opts{'tagfilter'};3175my$search_re=$opts{'search_regexp'};31763177return@$projlist3178unless($tagfilter||$search_re);31793180# searching projects require filling to be run before it;3181 fill_project_list_info($projlist,3182$tagfilter?'ctags': (),3183$search_re? ('path','descr') : ());3184my@projects;3185 PROJECT:3186foreachmy$pr(@$projlist) {31873188if($tagfilter) {3189next unlessref($pr->{'ctags'})eq'HASH';3190next unless3191grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};3192}31933194if($search_re) {3195next unless3196$pr->{'path'} =~/$search_re/||3197$pr->{'descr_long'} =~/$search_re/;3198}31993200push@projects,$pr;3201}32023203return@projects;3204}32053206our$gitweb_project_owner=undef;3207sub git_get_project_list_from_file {32083209return if(defined$gitweb_project_owner);32103211$gitweb_project_owner= {};3212# read from file (url-encoded):3213# 'git%2Fgit.git Linus+Torvalds'3214# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'3215# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'3216if(-f $projects_list) {3217open(my$fd,'<',$projects_list);3218while(my$line= <$fd>) {3219chomp$line;3220my($pr,$ow) =split' ',$line;3221$pr= unescape($pr);3222$ow= unescape($ow);3223$gitweb_project_owner->{$pr} = to_utf8($ow);3224}3225close$fd;3226}3227}32283229sub git_get_project_owner {3230my$project=shift;3231my$owner;32323233returnundefunless$project;3234$git_dir="$projectroot/$project";32353236if(!defined$gitweb_project_owner) {3237 git_get_project_list_from_file();3238}32393240if(exists$gitweb_project_owner->{$project}) {3241$owner=$gitweb_project_owner->{$project};3242}3243if(!defined$owner){3244$owner= git_get_project_config('owner');3245}3246if(!defined$owner) {3247$owner= get_file_owner("$git_dir");3248}32493250return$owner;3251}32523253sub git_get_last_activity {3254my($path) =@_;3255my$fd;32563257$git_dir="$projectroot/$path";3258open($fd,"-|", git_cmd(),'for-each-ref',3259'--format=%(committer)',3260'--sort=-committerdate',3261'--count=1',3262map{"refs/$_"} get_branch_refs ())orreturn;3263my$most_recent= <$fd>;3264close$fdorreturn;3265if(defined$most_recent&&3266$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {3267my$timestamp=$1;3268my$age=time-$timestamp;3269return($age, age_string($age));3270}3271return(undef,undef);3272}32733274# Implementation note: when a single remote is wanted, we cannot use 'git3275# remote show -n' because that command always work (assuming it's a remote URL3276# if it's not defined), and we cannot use 'git remote show' because that would3277# try to make a network roundtrip. So the only way to find if that particular3278# remote is defined is to walk the list provided by 'git remote -v' and stop if3279# and when we find what we want.3280sub git_get_remotes_list {3281my$wanted=shift;3282my%remotes= ();32833284open my$fd,'-|', git_cmd(),'remote','-v';3285return unless$fd;3286while(my$remote= <$fd>) {3287chomp$remote;3288$remote=~s!\t(.*?)\s+\((\w+)\)$!!;3289next if$wantedand not$remoteeq$wanted;3290my($url,$key) = ($1,$2);32913292$remotes{$remote} ||= {'heads'=> () };3293$remotes{$remote}{$key} =$url;3294}3295close$fdorreturn;3296returnwantarray?%remotes: \%remotes;3297}32983299# Takes a hash of remotes as first parameter and fills it by adding the3300# available remote heads for each of the indicated remotes.3301sub fill_remote_heads {3302my$remotes=shift;3303my@heads=map{"remotes/$_"}keys%$remotes;3304my@remoteheads= git_get_heads_list(undef,@heads);3305foreachmy$remote(keys%$remotes) {3306$remotes->{$remote}{'heads'} = [grep{3307$_->{'name'} =~s!^$remote/!!3308}@remoteheads];3309}3310}33113312sub git_get_references {3313my$type=shift||"";3314my%refs;3315# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113316# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3317open my$fd,"-|", git_cmd(),"show-ref","--dereference",3318($type? ("--","refs/$type") : ())# use -- <pattern> if $type3319orreturn;33203321while(my$line= <$fd>) {3322chomp$line;3323if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3324if(defined$refs{$1}) {3325push@{$refs{$1}},$2;3326}else{3327$refs{$1} = [$2];3328}3329}3330}3331close$fdorreturn;3332return \%refs;3333}33343335sub git_get_rev_name_tags {3336my$hash=shift||returnundef;33373338open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3339orreturn;3340my$name_rev= <$fd>;3341close$fd;33423343if($name_rev=~ m|^$hash tags/(.*)$|) {3344return$1;3345}else{3346# catches also '$hash undefined' output3347returnundef;3348}3349}33503351## ----------------------------------------------------------------------3352## parse to hash functions33533354sub parse_date {3355my$epoch=shift;3356my$tz=shift||"-0000";33573358my%date;3359my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3360my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3361my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3362$date{'hour'} =$hour;3363$date{'minute'} =$min;3364$date{'mday'} =$mday;3365$date{'day'} =$days[$wday];3366$date{'month'} =$months[$mon];3367$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3368$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3369$date{'mday-time'} =sprintf"%d%s%02d:%02d",3370$mday,$months[$mon],$hour,$min;3371$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",33721900+$year,1+$mon,$mday,$hour,$min,$sec;33733374my($tz_sign,$tz_hour,$tz_min) =3375($tz=~m/^([-+])(\d\d)(\d\d)$/);3376$tz_sign= ($tz_signeq'-'? -1: +1);3377my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3378($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3379$date{'hour_local'} =$hour;3380$date{'minute_local'} =$min;3381$date{'tz_local'} =$tz;3382$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",33831900+$year,$mon+1,$mday,3384$hour,$min,$sec,$tz);3385return%date;3386}33873388sub parse_tag {3389my$tag_id=shift;3390my%tag;3391my@comment;33923393open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3394$tag{'id'} =$tag_id;3395while(my$line= <$fd>) {3396chomp$line;3397if($line=~m/^object ([0-9a-fA-F]{40})$/) {3398$tag{'object'} =$1;3399}elsif($line=~m/^type (.+)$/) {3400$tag{'type'} =$1;3401}elsif($line=~m/^tag (.+)$/) {3402$tag{'name'} =$1;3403}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3404$tag{'author'} =$1;3405$tag{'author_epoch'} =$2;3406$tag{'author_tz'} =$3;3407if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3408$tag{'author_name'} =$1;3409$tag{'author_email'} =$2;3410}else{3411$tag{'author_name'} =$tag{'author'};3412}3413}elsif($line=~m/--BEGIN/) {3414push@comment,$line;3415last;3416}elsif($lineeq"") {3417last;3418}3419}3420push@comment, <$fd>;3421$tag{'comment'} = \@comment;3422close$fdorreturn;3423if(!defined$tag{'name'}) {3424return3425};3426return%tag3427}34283429sub parse_commit_text {3430my($commit_text,$withparents) =@_;3431my@commit_lines=split'\n',$commit_text;3432my%co;34333434pop@commit_lines;# Remove '\0'34353436if(!@commit_lines) {3437return;3438}34393440my$header=shift@commit_lines;3441if($header!~m/^[0-9a-fA-F]{40}/) {3442return;3443}3444($co{'id'},my@parents) =split' ',$header;3445while(my$line=shift@commit_lines) {3446last if$lineeq"\n";3447if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3448$co{'tree'} =$1;3449}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3450push@parents,$1;3451}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3452$co{'author'} = to_utf8($1);3453$co{'author_epoch'} =$2;3454$co{'author_tz'} =$3;3455if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3456$co{'author_name'} =$1;3457$co{'author_email'} =$2;3458}else{3459$co{'author_name'} =$co{'author'};3460}3461}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3462$co{'committer'} = to_utf8($1);3463$co{'committer_epoch'} =$2;3464$co{'committer_tz'} =$3;3465if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3466$co{'committer_name'} =$1;3467$co{'committer_email'} =$2;3468}else{3469$co{'committer_name'} =$co{'committer'};3470}3471}3472}3473if(!defined$co{'tree'}) {3474return;3475};3476$co{'parents'} = \@parents;3477$co{'parent'} =$parents[0];34783479foreachmy$title(@commit_lines) {3480$title=~s/^ //;3481if($titlene"") {3482$co{'title'} = chop_str($title,80,5);3483# remove leading stuff of merges to make the interesting part visible3484if(length($title) >50) {3485$title=~s/^Automatic //;3486$title=~s/^merge (of|with) /Merge ... /i;3487if(length($title) >50) {3488$title=~s/(http|rsync):\/\///;3489}3490if(length($title) >50) {3491$title=~s/(master|www|rsync)\.//;3492}3493if(length($title) >50) {3494$title=~s/kernel.org:?//;3495}3496if(length($title) >50) {3497$title=~s/\/pub\/scm//;3498}3499}3500$co{'title_short'} = chop_str($title,50,5);3501last;3502}3503}3504if(!defined$co{'title'} ||$co{'title'}eq"") {3505$co{'title'} =$co{'title_short'} ='(no commit message)';3506}3507# remove added spaces3508foreachmy$line(@commit_lines) {3509$line=~s/^ //;3510}3511$co{'comment'} = \@commit_lines;35123513my$age=time-$co{'committer_epoch'};3514$co{'age'} =$age;3515$co{'age_string'} = age_string($age);3516my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3517if($age>60*60*24*7*2) {3518$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3519$co{'age_string_age'} =$co{'age_string'};3520}else{3521$co{'age_string_date'} =$co{'age_string'};3522$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3523}3524return%co;3525}35263527sub parse_commit {3528my($commit_id) =@_;3529my%co;35303531local$/="\0";35323533open my$fd,"-|", git_cmd(),"rev-list",3534"--parents",3535"--header",3536"--max-count=1",3537$commit_id,3538"--",3539or die_error(500,"Open git-rev-list failed");3540%co= parse_commit_text(<$fd>,1);3541close$fd;35423543return%co;3544}35453546sub parse_commits {3547my($commit_id,$maxcount,$skip,$filename,@args) =@_;3548my@cos;35493550$maxcount||=1;3551$skip||=0;35523553local$/="\0";35543555open my$fd,"-|", git_cmd(),"rev-list",3556"--header",3557@args,3558("--max-count=".$maxcount),3559("--skip=".$skip),3560@extra_options,3561$commit_id,3562"--",3563($filename? ($filename) : ())3564or die_error(500,"Open git-rev-list failed");3565while(my$line= <$fd>) {3566my%co= parse_commit_text($line);3567push@cos, \%co;3568}3569close$fd;35703571returnwantarray?@cos: \@cos;3572}35733574# parse line of git-diff-tree "raw" output3575sub parse_difftree_raw_line {3576my$line=shift;3577my%res;35783579# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3580# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3581if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3582$res{'from_mode'} =$1;3583$res{'to_mode'} =$2;3584$res{'from_id'} =$3;3585$res{'to_id'} =$4;3586$res{'status'} =$5;3587$res{'similarity'} =$6;3588if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3589($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3590}else{3591$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3592}3593}3594# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3595# combined diff (for merge commit)3596elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3597$res{'nparents'} =length($1);3598$res{'from_mode'} = [split(' ',$2) ];3599$res{'to_mode'} =pop@{$res{'from_mode'}};3600$res{'from_id'} = [split(' ',$3) ];3601$res{'to_id'} =pop@{$res{'from_id'}};3602$res{'status'} = [split('',$4) ];3603$res{'to_file'} = unquote($5);3604}3605# 'c512b523472485aef4fff9e57b229d9d243c967f'3606elsif($line=~m/^([0-9a-fA-F]{40})$/) {3607$res{'commit'} =$1;3608}36093610returnwantarray?%res: \%res;3611}36123613# wrapper: return parsed line of git-diff-tree "raw" output3614# (the argument might be raw line, or parsed info)3615sub parsed_difftree_line {3616my$line_or_ref=shift;36173618if(ref($line_or_ref)eq"HASH") {3619# pre-parsed (or generated by hand)3620return$line_or_ref;3621}else{3622return parse_difftree_raw_line($line_or_ref);3623}3624}36253626# parse line of git-ls-tree output3627sub parse_ls_tree_line {3628my$line=shift;3629my%opts=@_;3630my%res;36313632if($opts{'-l'}) {3633#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3634$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;36353636$res{'mode'} =$1;3637$res{'type'} =$2;3638$res{'hash'} =$3;3639$res{'size'} =$4;3640if($opts{'-z'}) {3641$res{'name'} =$5;3642}else{3643$res{'name'} = unquote($5);3644}3645}else{3646#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3647$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;36483649$res{'mode'} =$1;3650$res{'type'} =$2;3651$res{'hash'} =$3;3652if($opts{'-z'}) {3653$res{'name'} =$4;3654}else{3655$res{'name'} = unquote($4);3656}3657}36583659returnwantarray?%res: \%res;3660}36613662# generates _two_ hashes, references to which are passed as 2 and 3 argument3663sub parse_from_to_diffinfo {3664my($diffinfo,$from,$to,@parents) =@_;36653666if($diffinfo->{'nparents'}) {3667# combined diff3668$from->{'file'} = [];3669$from->{'href'} = [];3670 fill_from_file_info($diffinfo,@parents)3671unlessexists$diffinfo->{'from_file'};3672for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3673$from->{'file'}[$i] =3674defined$diffinfo->{'from_file'}[$i] ?3675$diffinfo->{'from_file'}[$i] :3676$diffinfo->{'to_file'};3677if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3678$from->{'href'}[$i] = href(action=>"blob",3679 hash_base=>$parents[$i],3680 hash=>$diffinfo->{'from_id'}[$i],3681 file_name=>$from->{'file'}[$i]);3682}else{3683$from->{'href'}[$i] =undef;3684}3685}3686}else{3687# ordinary (not combined) diff3688$from->{'file'} =$diffinfo->{'from_file'};3689if($diffinfo->{'status'}ne"A") {# not new (added) file3690$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3691 hash=>$diffinfo->{'from_id'},3692 file_name=>$from->{'file'});3693}else{3694delete$from->{'href'};3695}3696}36973698$to->{'file'} =$diffinfo->{'to_file'};3699if(!is_deleted($diffinfo)) {# file exists in result3700$to->{'href'} = href(action=>"blob", hash_base=>$hash,3701 hash=>$diffinfo->{'to_id'},3702 file_name=>$to->{'file'});3703}else{3704delete$to->{'href'};3705}3706}37073708## ......................................................................3709## parse to array of hashes functions37103711sub git_get_heads_list {3712my($limit,@classes) =@_;3713@classes= get_branch_refs()unless@classes;3714my@patterns=map{"refs/$_"}@classes;3715my@headslist;37163717open my$fd,'-|', git_cmd(),'for-each-ref',3718($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3719'--format=%(objectname) %(refname) %(subject)%00%(committer)',3720@patterns3721orreturn;3722while(my$line= <$fd>) {3723my%ref_item;37243725chomp$line;3726my($refinfo,$committerinfo) =split(/\0/,$line);3727my($hash,$name,$title) =split(' ',$refinfo,3);3728my($committer,$epoch,$tz) =3729($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3730$ref_item{'fullname'} =$name;3731my$strip_refs=join'|',map{quotemeta} get_branch_refs();3732$name=~s!^refs/($strip_refs|remotes)/!!;3733$ref_item{'name'} =$name;3734# for refs neither in 'heads' nor 'remotes' we want to3735# show their ref dir3736my$ref_dir= (defined$1) ?$1:'';3737if($ref_dirne''and$ref_dirne'heads'and$ref_dirne'remotes') {3738$ref_item{'name'} .=' ('.$ref_dir.')';3739}37403741$ref_item{'id'} =$hash;3742$ref_item{'title'} =$title||'(no commit message)';3743$ref_item{'epoch'} =$epoch;3744if($epoch) {3745$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3746}else{3747$ref_item{'age'} ="unknown";3748}37493750push@headslist, \%ref_item;3751}3752close$fd;37533754returnwantarray?@headslist: \@headslist;3755}37563757sub git_get_tags_list {3758my$limit=shift;3759my@tagslist;37603761open my$fd,'-|', git_cmd(),'for-each-ref',3762($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3763'--format=%(objectname) %(objecttype) %(refname) '.3764'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3765'refs/tags'3766orreturn;3767while(my$line= <$fd>) {3768my%ref_item;37693770chomp$line;3771my($refinfo,$creatorinfo) =split(/\0/,$line);3772my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3773my($creator,$epoch,$tz) =3774($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3775$ref_item{'fullname'} =$name;3776$name=~s!^refs/tags/!!;37773778$ref_item{'type'} =$type;3779$ref_item{'id'} =$id;3780$ref_item{'name'} =$name;3781if($typeeq"tag") {3782$ref_item{'subject'} =$title;3783$ref_item{'reftype'} =$reftype;3784$ref_item{'refid'} =$refid;3785}else{3786$ref_item{'reftype'} =$type;3787$ref_item{'refid'} =$id;3788}37893790if($typeeq"tag"||$typeeq"commit") {3791$ref_item{'epoch'} =$epoch;3792if($epoch) {3793$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3794}else{3795$ref_item{'age'} ="unknown";3796}3797}37983799push@tagslist, \%ref_item;3800}3801close$fd;38023803returnwantarray?@tagslist: \@tagslist;3804}38053806## ----------------------------------------------------------------------3807## filesystem-related functions38083809sub get_file_owner {3810my$path=shift;38113812my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3813my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3814if(!defined$gcos) {3815returnundef;3816}3817my$owner=$gcos;3818$owner=~s/[,;].*$//;3819return to_utf8($owner);3820}38213822# assume that file exists3823sub insert_file {3824my$filename=shift;38253826open my$fd,'<',$filename;3827print map{ to_utf8($_) } <$fd>;3828close$fd;3829}38303831## ......................................................................3832## mimetype related functions38333834sub mimetype_guess_file {3835my$filename=shift;3836my$mimemap=shift;3837-r $mimemaporreturnundef;38383839my%mimemap;3840open(my$mh,'<',$mimemap)orreturnundef;3841while(<$mh>) {3842next ifm/^#/;# skip comments3843my($mimetype,@exts) =split(/\s+/);3844foreachmy$ext(@exts) {3845$mimemap{$ext} =$mimetype;3846}3847}3848close($mh);38493850$filename=~/\.([^.]*)$/;3851return$mimemap{$1};3852}38533854sub mimetype_guess {3855my$filename=shift;3856my$mime;3857$filename=~/\./orreturnundef;38583859if($mimetypes_file) {3860my$file=$mimetypes_file;3861if($file!~m!^/!) {# if it is relative path3862# it is relative to project3863$file="$projectroot/$project/$file";3864}3865$mime= mimetype_guess_file($filename,$file);3866}3867$mime||= mimetype_guess_file($filename,'/etc/mime.types');3868return$mime;3869}38703871sub blob_mimetype {3872my$fd=shift;3873my$filename=shift;38743875if($filename) {3876my$mime= mimetype_guess($filename);3877$mimeandreturn$mime;3878}38793880# just in case3881return$default_blob_plain_mimetypeunless$fd;38823883if(-T $fd) {3884return'text/plain';3885}elsif(!$filename) {3886return'application/octet-stream';3887}elsif($filename=~m/\.png$/i) {3888return'image/png';3889}elsif($filename=~m/\.gif$/i) {3890return'image/gif';3891}elsif($filename=~m/\.jpe?g$/i) {3892return'image/jpeg';3893}else{3894return'application/octet-stream';3895}3896}38973898sub blob_contenttype {3899my($fd,$file_name,$type) =@_;39003901$type||= blob_mimetype($fd,$file_name);3902if($typeeq'text/plain'&&defined$default_text_plain_charset) {3903$type.="; charset=$default_text_plain_charset";3904}39053906return$type;3907}39083909# guess file syntax for syntax highlighting; return undef if no highlighting3910# the name of syntax can (in the future) depend on syntax highlighter used3911sub guess_file_syntax {3912my($highlight,$mimetype,$file_name) =@_;3913returnundefunless($highlight&&defined$file_name);3914my$basename= basename($file_name,'.in');3915return$highlight_basename{$basename}3916ifexists$highlight_basename{$basename};39173918$basename=~/\.([^.]*)$/;3919my$ext=$1orreturnundef;3920return$highlight_ext{$ext}3921ifexists$highlight_ext{$ext};39223923returnundef;3924}39253926# run highlighter and return FD of its output,3927# or return original FD if no highlighting3928sub run_highlighter {3929my($fd,$highlight,$syntax) =@_;3930return$fdunless($highlight&&defined$syntax);39313932close$fd;3933open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3934 quote_command($highlight_bin).3935" --replace-tabs=8 --fragment --syntax$syntax|"3936or die_error(500,"Couldn't open file or run syntax highlighter");3937return$fd;3938}39393940## ======================================================================3941## functions printing HTML: header, footer, error page39423943sub get_page_title {3944my$title= to_utf8($site_name);39453946unless(defined$project) {3947if(defined$project_filter) {3948$title.=" - projects in '". esc_path($project_filter) ."'";3949}3950return$title;3951}3952$title.=" - ". to_utf8($project);39533954return$titleunless(defined$action);3955$title.="/$action";# $action is US-ASCII (7bit ASCII)39563957return$titleunless(defined$file_name);3958$title.=" - ". esc_path($file_name);3959if($actioneq"tree"&&$file_name!~ m|/$|) {3960$title.="/";3961}39623963return$title;3964}39653966sub get_content_type_html {3967# require explicit support from the UA if we are to send the page as3968# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3969# we have to do this because MSIE sometimes globs '*/*', pretending to3970# support xhtml+xml but choking when it gets what it asked for.3971if(defined$cgi->http('HTTP_ACCEPT') &&3972$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3973$cgi->Accept('application/xhtml+xml') !=0) {3974return'application/xhtml+xml';3975}else{3976return'text/html';3977}3978}39793980sub print_feed_meta {3981if(defined$project) {3982my%href_params= get_feed_info();3983if(!exists$href_params{'-title'}) {3984$href_params{'-title'} ='log';3985}39863987foreachmy$format(qw(RSS Atom)) {3988my$type=lc($format);3989my%link_attr= (3990'-rel'=>'alternate',3991'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3992'-type'=>"application/$type+xml"3993);39943995$href_params{'extra_options'} =undef;3996$href_params{'action'} =$type;3997$link_attr{'-href'} = href(%href_params);3998print"<link ".3999"rel=\"$link_attr{'-rel'}\"".4000"title=\"$link_attr{'-title'}\"".4001"href=\"$link_attr{'-href'}\"".4002"type=\"$link_attr{'-type'}\"".4003"/>\n";40044005$href_params{'extra_options'} ='--no-merges';4006$link_attr{'-href'} = href(%href_params);4007$link_attr{'-title'} .=' (no merges)';4008print"<link ".4009"rel=\"$link_attr{'-rel'}\"".4010"title=\"$link_attr{'-title'}\"".4011"href=\"$link_attr{'-href'}\"".4012"type=\"$link_attr{'-type'}\"".4013"/>\n";4014}40154016}else{4017printf('<link rel="alternate" title="%sprojects list" '.4018'href="%s" type="text/plain; charset=utf-8" />'."\n",4019 esc_attr($site_name), href(project=>undef, action=>"project_index"));4020printf('<link rel="alternate" title="%sprojects feeds" '.4021'href="%s" type="text/x-opml" />'."\n",4022 esc_attr($site_name), href(project=>undef, action=>"opml"));4023}4024}40254026sub print_header_links {4027my$status=shift;40284029# print out each stylesheet that exist, providing backwards capability4030# for those people who defined $stylesheet in a config file4031if(defined$stylesheet) {4032print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";4033}else{4034foreachmy$stylesheet(@stylesheets) {4035next unless$stylesheet;4036print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";4037}4038}4039 print_feed_meta()4040if($statuseq'200 OK');4041if(defined$favicon) {4042printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);4043}4044}40454046sub print_nav_breadcrumbs_path {4047my$dirprefix=undef;4048while(my$part=shift) {4049$dirprefix.="/"ifdefined$dirprefix;4050$dirprefix.=$part;4051print$cgi->a({-href => href(project =>undef,4052 project_filter =>$dirprefix,4053 action =>"project_list")},4054 esc_html($part)) ." / ";4055}4056}40574058sub print_nav_breadcrumbs {4059my%opts=@_;40604061formy$crumb(@extra_breadcrumbs, [$home_link_str=>$home_link]) {4062print$cgi->a({-href => esc_url($crumb->[1])},$crumb->[0]) ." / ";4063}4064if(defined$project) {4065my@dirname=split'/',$project;4066my$projectbasename=pop@dirname;4067 print_nav_breadcrumbs_path(@dirname);4068print$cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));4069if(defined$action) {4070my$action_print=$action;4071if(defined$opts{-action_extra}) {4072$action_print=$cgi->a({-href => href(action=>$action)},4073$action);4074}4075print" /$action_print";4076}4077if(defined$opts{-action_extra}) {4078print" /$opts{-action_extra}";4079}4080print"\n";4081}elsif(defined$project_filter) {4082 print_nav_breadcrumbs_path(split'/',$project_filter);4083}4084}40854086sub print_search_form {4087if(!defined$searchtext) {4088$searchtext="";4089}4090my$search_hash;4091if(defined$hash_base) {4092$search_hash=$hash_base;4093}elsif(defined$hash) {4094$search_hash=$hash;4095}else{4096$search_hash="HEAD";4097}4098my$action=$my_uri;4099my$use_pathinfo= gitweb_check_feature('pathinfo');4100if($use_pathinfo) {4101$action.="/".esc_url($project);4102}4103print$cgi->startform(-method=>"get", -action =>$action) .4104"<div class=\"search\">\n".4105(!$use_pathinfo&&4106$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .4107$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".4108$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".4109$cgi->popup_menu(-name =>'st', -default=>'commit',4110-values=> ['commit','grep','author','committer','pickaxe']) .4111" ".$cgi->a({-href => href(action=>"search_help"),4112-title =>"search help"},"?") ." search:\n",4113$cgi->textfield(-name =>"s", -value =>$searchtext, -override =>1) ."\n".4114"<span title=\"Extended regular expression\">".4115$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',4116-checked =>$search_use_regexp) .4117"</span>".4118"</div>".4119$cgi->end_form() ."\n";4120}41214122sub git_header_html {4123my$status=shift||"200 OK";4124my$expires=shift;4125my%opts=@_;41264127my$title= get_page_title();4128my$content_type= get_content_type_html();4129print$cgi->header(-type=>$content_type, -charset =>'utf-8',4130-status=>$status, -expires =>$expires)4131unless($opts{'-no_http_header'});4132my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';4133print<<EOF;4134<?xml version="1.0" encoding="utf-8"?>4135<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4136<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">4137<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->4138<!-- git core binaries version$git_version-->4139<head>4140<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>4141<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>4142<meta name="robots" content="index, nofollow"/>4143<title>$title</title>4144EOF4145# the stylesheet, favicon etc urls won't work correctly with path_info4146# unless we set the appropriate base URL4147if($ENV{'PATH_INFO'}) {4148print"<base href=\"".esc_url($base_url)."\"/>\n";4149}4150 print_header_links($status);41514152if(defined$site_html_head_string) {4153print to_utf8($site_html_head_string);4154}41554156print"</head>\n".4157"<body>\n";41584159if(defined$site_header&& -f $site_header) {4160 insert_file($site_header);4161}41624163print"<div class=\"page_header\">\n";4164if(defined$logo) {4165print$cgi->a({-href => esc_url($logo_url),4166-title =>$logo_label},4167$cgi->img({-src => esc_url($logo),4168-width =>72, -height =>27,4169-alt =>"git",4170-class=>"logo"}));4171}4172 print_nav_breadcrumbs(%opts);4173print"</div>\n";41744175my$have_search= gitweb_check_feature('search');4176if(defined$project&&$have_search) {4177 print_search_form();4178}4179}41804181sub git_footer_html {4182my$feed_class='rss_logo';41834184print"<div class=\"page_footer\">\n";4185if(defined$project) {4186my$descr= git_get_project_description($project);4187if(defined$descr) {4188print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";4189}41904191my%href_params= get_feed_info();4192if(!%href_params) {4193$feed_class.=' generic';4194}4195$href_params{'-title'} ||='log';41964197foreachmy$format(qw(RSS Atom)) {4198$href_params{'action'} =lc($format);4199print$cgi->a({-href => href(%href_params),4200-title =>"$href_params{'-title'}$formatfeed",4201-class=>$feed_class},$format)."\n";4202}42034204}else{4205print$cgi->a({-href => href(project=>undef, action=>"opml",4206 project_filter =>$project_filter),4207-class=>$feed_class},"OPML") ." ";4208print$cgi->a({-href => href(project=>undef, action=>"project_index",4209 project_filter =>$project_filter),4210-class=>$feed_class},"TXT") ."\n";4211}4212print"</div>\n";# class="page_footer"42134214if(defined$t0&& gitweb_check_feature('timed')) {4215print"<div id=\"generating_info\">\n";4216print'This page took '.4217'<span id="generating_time" class="time_span">'.4218 tv_interval($t0, [ gettimeofday() ]).4219' seconds </span>'.4220' and '.4221'<span id="generating_cmd">'.4222$number_of_git_cmds.4223'</span> git commands '.4224" to generate.\n";4225print"</div>\n";# class="page_footer"4226}42274228if(defined$site_footer&& -f $site_footer) {4229 insert_file($site_footer);4230}42314232print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;4233if(defined$action&&4234$actioneq'blame_incremental') {4235print qq!<script type="text/javascript">\n!.4236 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.4237 qq!"!. href() .qq!");\n!.4238 qq!</script>\n!;4239}else{4240my($jstimezone,$tz_cookie,$datetime_class) =4241 gitweb_get_feature('javascript-timezone');42424243print qq!<script type="text/javascript">\n!.4244 qq!window.onload = function () {\n!;4245if(gitweb_check_feature('javascript-actions')) {4246print qq! fixLinks();\n!;4247}4248if($jstimezone&&$tz_cookie&&$datetime_class) {4249print qq! var tz_cookie = { name:'$tz_cookie', expires:14, path:'/'};\n!.# in days4250 qq! onloadTZSetup('$jstimezone', tz_cookie,'$datetime_class');\n!;4251}4252print qq!};\n!.4253 qq!</script>\n!;4254}42554256print"</body>\n".4257"</html>";4258}42594260# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])4261# Example: die_error(404, 'Hash not found')4262# By convention, use the following status codes (as defined in RFC 2616):4263# 400: Invalid or missing CGI parameters, or4264# requested object exists but has wrong type.4265# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on4266# this server or project.4267# 404: Requested object/revision/project doesn't exist.4268# 500: The server isn't configured properly, or4269# an internal error occurred (e.g. failed assertions caused by bugs), or4270# an unknown error occurred (e.g. the git binary died unexpectedly).4271# 503: The server is currently unavailable (because it is overloaded,4272# or down for maintenance). Generally, this is a temporary state.4273sub die_error {4274my$status=shift||500;4275my$error= esc_html(shift) ||"Internal Server Error";4276my$extra=shift;4277my%opts=@_;42784279my%http_responses= (4280400=>'400 Bad Request',4281403=>'403 Forbidden',4282404=>'404 Not Found',4283500=>'500 Internal Server Error',4284503=>'503 Service Unavailable',4285);4286 git_header_html($http_responses{$status},undef,%opts);4287print<<EOF;4288<div class="page_body">4289<br /><br />4290$status-$error4291<br />4292EOF4293if(defined$extra) {4294print"<hr />\n".4295"$extra\n";4296}4297print"</div>\n";42984299 git_footer_html();4300goto DONE_GITWEB4301unless($opts{'-error_handler'});4302}43034304## ----------------------------------------------------------------------4305## functions printing or outputting HTML: navigation43064307sub git_print_page_nav {4308my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;4309$extra=''if!defined$extra;# pager or formats43104311my@navs=qw(summary shortlog log commit commitdiff tree);4312if($suppress) {4313@navs=grep{$_ne$suppress}@navs;4314}43154316my%arg=map{$_=> {action=>$_} }@navs;4317if(defined$head) {4318for(qw(commit commitdiff)) {4319$arg{$_}{'hash'} =$head;4320}4321if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {4322for(qw(shortlog log)) {4323$arg{$_}{'hash'} =$head;4324}4325}4326}43274328$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;4329$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;43304331my@actions= gitweb_get_feature('actions');4332my%repl= (4333'%'=>'%',4334'n'=>$project,# project name4335'f'=>$git_dir,# project path within filesystem4336'h'=>$treehead||'',# current hash ('h' parameter)4337'b'=>$treebase||'',# hash base ('hb' parameter)4338);4339while(@actions) {4340my($label,$link,$pos) =splice(@actions,0,3);4341# insert4342@navs=map{$_eq$pos? ($_,$label) :$_}@navs;4343# munch munch4344$link=~s/%([%nfhb])/$repl{$1}/g;4345$arg{$label}{'_href'} =$link;4346}43474348print"<div class=\"page_nav\">\n".4349(join" | ",4350map{$_eq$current?4351$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4352}@navs);4353print"<br/>\n$extra<br/>\n".4354"</div>\n";4355}43564357# returns a submenu for the nagivation of the refs views (tags, heads,4358# remotes) with the current view disabled and the remotes view only4359# available if the feature is enabled4360sub format_ref_views {4361my($current) =@_;4362my@ref_views=qw{tags heads};4363push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4364returnjoin" | ",map{4365$_eq$current?$_:4366$cgi->a({-href => href(action=>$_)},$_)4367}@ref_views4368}43694370sub format_paging_nav {4371my($action,$page,$has_next_link) =@_;4372my$paging_nav;437343744375if($page>0) {4376$paging_nav.=4377$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4378" ⋅ ".4379$cgi->a({-href => href(-replay=>1, page=>$page-1),4380-accesskey =>"p", -title =>"Alt-p"},"prev");4381}else{4382$paging_nav.="first ⋅ prev";4383}43844385if($has_next_link) {4386$paging_nav.=" ⋅ ".4387$cgi->a({-href => href(-replay=>1, page=>$page+1),4388-accesskey =>"n", -title =>"Alt-n"},"next");4389}else{4390$paging_nav.=" ⋅ next";4391}43924393return$paging_nav;4394}43954396## ......................................................................4397## functions printing or outputting HTML: div43984399sub git_print_header_div {4400my($action,$title,$hash,$hash_base) =@_;4401my%args= ();44024403$args{'action'} =$action;4404$args{'hash'} =$hashif$hash;4405$args{'hash_base'} =$hash_baseif$hash_base;44064407print"<div class=\"header\">\n".4408$cgi->a({-href => href(%args), -class=>"title"},4409$title?$title:$action) .4410"\n</div>\n";4411}44124413sub format_repo_url {4414my($name,$url) =@_;4415return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4416}44174418# Group output by placing it in a DIV element and adding a header.4419# Options for start_div() can be provided by passing a hash reference as the4420# first parameter to the function.4421# Options to git_print_header_div() can be provided by passing an array4422# reference. This must follow the options to start_div if they are present.4423# The content can be a scalar, which is output as-is, a scalar reference, which4424# is output after html escaping, an IO handle passed either as *handle or4425# *handle{IO}, or a function reference. In the latter case all following4426# parameters will be taken as argument to the content function call.4427sub git_print_section {4428my($div_args,$header_args,$content);4429my$arg=shift;4430if(ref($arg)eq'HASH') {4431$div_args=$arg;4432$arg=shift;4433}4434if(ref($arg)eq'ARRAY') {4435$header_args=$arg;4436$arg=shift;4437}4438$content=$arg;44394440print$cgi->start_div($div_args);4441 git_print_header_div(@$header_args);44424443if(ref($content)eq'CODE') {4444$content->(@_);4445}elsif(ref($content)eq'SCALAR') {4446print esc_html($$content);4447}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4448print<$content>;4449}elsif(!ref($content) &&defined($content)) {4450print$content;4451}44524453print$cgi->end_div;4454}44554456sub format_timestamp_html {4457my$date=shift;4458my$strtime=$date->{'rfc2822'};44594460my(undef,undef,$datetime_class) =4461 gitweb_get_feature('javascript-timezone');4462if($datetime_class) {4463$strtime= qq!<span class="$datetime_class">$strtime</span>!;4464}44654466my$localtime_format='(%02d:%02d%s)';4467if($date->{'hour_local'} <6) {4468$localtime_format='(<span class="atnight">%02d:%02d</span>%s)';4469}4470$strtime.=' '.4471sprintf($localtime_format,4472$date->{'hour_local'},$date->{'minute_local'},$date->{'tz_local'});44734474return$strtime;4475}44764477# Outputs the author name and date in long form4478sub git_print_authorship {4479my$co=shift;4480my%opts=@_;4481my$tag=$opts{-tag} ||'div';4482my$author=$co->{'author_name'};44834484my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4485print"<$tagclass=\"author_date\">".4486 format_search_author($author,"author", esc_html($author)) .4487" [".format_timestamp_html(\%ad)."]".4488 git_get_avatar($co->{'author_email'}, -pad_before =>1) .4489"</$tag>\n";4490}44914492# Outputs table rows containing the full author or committer information,4493# in the format expected for 'commit' view (& similar).4494# Parameters are a commit hash reference, followed by the list of people4495# to output information for. If the list is empty it defaults to both4496# author and committer.4497sub git_print_authorship_rows {4498my$co=shift;4499# too bad we can't use @people = @_ || ('author', 'committer')4500my@people=@_;4501@people= ('author','committer')unless@people;4502foreachmy$who(@people) {4503my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4504print"<tr><td>$who</td><td>".4505 format_search_author($co->{"${who}_name"},$who,4506 esc_html($co->{"${who}_name"})) ." ".4507 format_search_author($co->{"${who}_email"},$who,4508 esc_html("<".$co->{"${who}_email"} .">")) .4509"</td><td rowspan=\"2\">".4510 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4511"</td></tr>\n".4512"<tr>".4513"<td></td><td>".4514 format_timestamp_html(\%wd) .4515"</td>".4516"</tr>\n";4517}4518}45194520sub git_print_page_path {4521my$name=shift;4522my$type=shift;4523my$hb=shift;452445254526print"<div class=\"page_path\">";4527print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4528-title =>'tree root'}, to_utf8("[$project]"));4529print" / ";4530if(defined$name) {4531my@dirname=split'/',$name;4532my$basename=pop@dirname;4533my$fullname='';45344535foreachmy$dir(@dirname) {4536$fullname.= ($fullname?'/':'') .$dir;4537print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4538 hash_base=>$hb),4539-title =>$fullname}, esc_path($dir));4540print" / ";4541}4542if(defined$type&&$typeeq'blob') {4543print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4544 hash_base=>$hb),4545-title =>$name}, esc_path($basename));4546}elsif(defined$type&&$typeeq'tree') {4547print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4548 hash_base=>$hb),4549-title =>$name}, esc_path($basename));4550print" / ";4551}else{4552print esc_path($basename);4553}4554}4555print"<br/></div>\n";4556}45574558sub git_print_log {4559my$log=shift;4560my%opts=@_;45614562if($opts{'-remove_title'}) {4563# remove title, i.e. first line of log4564shift@$log;4565}4566# remove leading empty lines4567while(defined$log->[0] &&$log->[0]eq"") {4568shift@$log;4569}45704571# print log4572my$skip_blank_line=0;4573foreachmy$line(@$log) {4574if($line=~m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {4575if(!$opts{'-remove_signoff'}) {4576print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4577$skip_blank_line=1;4578}4579next;4580}45814582if($line=~ m,\s*([a-z]*link): (https?://\S+),i) {4583if(!$opts{'-remove_signoff'}) {4584print"<span class=\"signoff\">". esc_html($1) .": ".4585"<a href=\"". esc_html($2) ."\">". esc_html($2) ."</a>".4586"</span><br/>\n";4587$skip_blank_line=1;4588}4589next;4590}45914592# print only one empty line4593# do not print empty line after signoff4594if($lineeq"") {4595next if($skip_blank_line);4596$skip_blank_line=1;4597}else{4598$skip_blank_line=0;4599}46004601print format_log_line_html($line) ."<br/>\n";4602}46034604if($opts{'-final_empty_line'}) {4605# end with single empty line4606print"<br/>\n"unless$skip_blank_line;4607}4608}46094610# return link target (what link points to)4611sub git_get_link_target {4612my$hash=shift;4613my$link_target;46144615# read link4616open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4617orreturn;4618{4619local$/=undef;4620$link_target= <$fd>;4621}4622close$fd4623orreturn;46244625return$link_target;4626}46274628# given link target, and the directory (basedir) the link is in,4629# return target of link relative to top directory (top tree);4630# return undef if it is not possible (including absolute links).4631sub normalize_link_target {4632my($link_target,$basedir) =@_;46334634# absolute symlinks (beginning with '/') cannot be normalized4635return if(substr($link_target,0,1)eq'/');46364637# normalize link target to path from top (root) tree (dir)4638my$path;4639if($basedir) {4640$path=$basedir.'/'.$link_target;4641}else{4642# we are in top (root) tree (dir)4643$path=$link_target;4644}46454646# remove //, /./, and /../4647my@path_parts;4648foreachmy$part(split('/',$path)) {4649# discard '.' and ''4650next if(!$part||$parteq'.');4651# handle '..'4652if($parteq'..') {4653if(@path_parts) {4654pop@path_parts;4655}else{4656# link leads outside repository (outside top dir)4657return;4658}4659}else{4660push@path_parts,$part;4661}4662}4663$path=join('/',@path_parts);46644665return$path;4666}46674668# print tree entry (row of git_tree), but without encompassing <tr> element4669sub git_print_tree_entry {4670my($t,$basedir,$hash_base,$have_blame) =@_;46714672my%base_key= ();4673$base_key{'hash_base'} =$hash_baseifdefined$hash_base;46744675# The format of a table row is: mode list link. Where mode is4676# the mode of the entry, list is the name of the entry, an href,4677# and link is the action links of the entry.46784679print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4680if(exists$t->{'size'}) {4681print"<td class=\"size\">$t->{'size'}</td>\n";4682}4683if($t->{'type'}eq"blob") {4684print"<td class=\"list\">".4685$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4686 file_name=>"$basedir$t->{'name'}",%base_key),4687-class=>"list"}, esc_path($t->{'name'}));4688if(S_ISLNK(oct$t->{'mode'})) {4689my$link_target= git_get_link_target($t->{'hash'});4690if($link_target) {4691my$norm_target= normalize_link_target($link_target,$basedir);4692if(defined$norm_target) {4693print" -> ".4694$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4695 file_name=>$norm_target),4696-title =>$norm_target}, esc_path($link_target));4697}else{4698print" -> ". esc_path($link_target);4699}4700}4701}4702print"</td>\n";4703print"<td class=\"link\">";4704print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4705 file_name=>"$basedir$t->{'name'}",%base_key)},4706"blob");4707if($have_blame) {4708print" | ".4709$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4710 file_name=>"$basedir$t->{'name'}",%base_key)},4711"blame");4712}4713if(defined$hash_base) {4714print" | ".4715$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4716 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4717"history");4718}4719print" | ".4720$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4721 file_name=>"$basedir$t->{'name'}")},4722"raw");4723print"</td>\n";47244725}elsif($t->{'type'}eq"tree") {4726print"<td class=\"list\">";4727print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4728 file_name=>"$basedir$t->{'name'}",4729%base_key)},4730 esc_path($t->{'name'}));4731print"</td>\n";4732print"<td class=\"link\">";4733print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4734 file_name=>"$basedir$t->{'name'}",4735%base_key)},4736"tree");4737if(defined$hash_base) {4738print" | ".4739$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4740 file_name=>"$basedir$t->{'name'}")},4741"history");4742}4743print"</td>\n";4744}else{4745# unknown object: we can only present history for it4746# (this includes 'commit' object, i.e. submodule support)4747print"<td class=\"list\">".4748 esc_path($t->{'name'}) .4749"</td>\n";4750print"<td class=\"link\">";4751if(defined$hash_base) {4752print$cgi->a({-href => href(action=>"history",4753 hash_base=>$hash_base,4754 file_name=>"$basedir$t->{'name'}")},4755"history");4756}4757print"</td>\n";4758}4759}47604761## ......................................................................4762## functions printing large fragments of HTML47634764# get pre-image filenames for merge (combined) diff4765sub fill_from_file_info {4766my($diff,@parents) =@_;47674768$diff->{'from_file'} = [ ];4769$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4770for(my$i=0;$i<$diff->{'nparents'};$i++) {4771if($diff->{'status'}[$i]eq'R'||4772$diff->{'status'}[$i]eq'C') {4773$diff->{'from_file'}[$i] =4774 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4775}4776}47774778return$diff;4779}47804781# is current raw difftree line of file deletion4782sub is_deleted {4783my$diffinfo=shift;47844785return$diffinfo->{'to_id'}eq('0' x 40);4786}47874788# does patch correspond to [previous] difftree raw line4789# $diffinfo - hashref of parsed raw diff format4790# $patchinfo - hashref of parsed patch diff format4791# (the same keys as in $diffinfo)4792sub is_patch_split {4793my($diffinfo,$patchinfo) =@_;47944795returndefined$diffinfo&&defined$patchinfo4796&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4797}479847994800sub git_difftree_body {4801my($difftree,$hash,@parents) =@_;4802my($parent) =$parents[0];4803my$have_blame= gitweb_check_feature('blame');4804print"<div class=\"list_head\">\n";4805if($#{$difftree} >10) {4806print(($#{$difftree} +1) ." files changed:\n");4807}4808print"</div>\n";48094810print"<table class=\"".4811(@parents>1?"combined ":"") .4812"diff_tree\">\n";48134814# header only for combined diff in 'commitdiff' view4815my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4816if($has_header) {4817# table header4818print"<thead><tr>\n".4819"<th></th><th></th>\n";# filename, patchN link4820for(my$i=0;$i<@parents;$i++) {4821my$par=$parents[$i];4822print"<th>".4823$cgi->a({-href => href(action=>"commitdiff",4824 hash=>$hash, hash_parent=>$par),4825-title =>'commitdiff to parent number '.4826($i+1) .': '.substr($par,0,7)},4827$i+1) .4828" </th>\n";4829}4830print"</tr></thead>\n<tbody>\n";4831}48324833my$alternate=1;4834my$patchno=0;4835foreachmy$line(@{$difftree}) {4836my$diff= parsed_difftree_line($line);48374838if($alternate) {4839print"<tr class=\"dark\">\n";4840}else{4841print"<tr class=\"light\">\n";4842}4843$alternate^=1;48444845if(exists$diff->{'nparents'}) {# combined diff48464847 fill_from_file_info($diff,@parents)4848unlessexists$diff->{'from_file'};48494850if(!is_deleted($diff)) {4851# file exists in the result (child) commit4852print"<td>".4853$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4854 file_name=>$diff->{'to_file'},4855 hash_base=>$hash),4856-class=>"list"}, esc_path($diff->{'to_file'})) .4857"</td>\n";4858}else{4859print"<td>".4860 esc_path($diff->{'to_file'}) .4861"</td>\n";4862}48634864if($actioneq'commitdiff') {4865# link to patch4866$patchno++;4867print"<td class=\"link\">".4868$cgi->a({-href => href(-anchor=>"patch$patchno")},4869"patch") .4870" | ".4871"</td>\n";4872}48734874my$has_history=0;4875my$not_deleted=0;4876for(my$i=0;$i<$diff->{'nparents'};$i++) {4877my$hash_parent=$parents[$i];4878my$from_hash=$diff->{'from_id'}[$i];4879my$from_path=$diff->{'from_file'}[$i];4880my$status=$diff->{'status'}[$i];48814882$has_history||= ($statusne'A');4883$not_deleted||= ($statusne'D');48844885if($statuseq'A') {4886print"<td class=\"link\"align=\"right\"> | </td>\n";4887}elsif($statuseq'D') {4888print"<td class=\"link\">".4889$cgi->a({-href => href(action=>"blob",4890 hash_base=>$hash,4891 hash=>$from_hash,4892 file_name=>$from_path)},4893"blob". ($i+1)) .4894" | </td>\n";4895}else{4896if($diff->{'to_id'}eq$from_hash) {4897print"<td class=\"link nochange\">";4898}else{4899print"<td class=\"link\">";4900}4901print$cgi->a({-href => href(action=>"blobdiff",4902 hash=>$diff->{'to_id'},4903 hash_parent=>$from_hash,4904 hash_base=>$hash,4905 hash_parent_base=>$hash_parent,4906 file_name=>$diff->{'to_file'},4907 file_parent=>$from_path)},4908"diff". ($i+1)) .4909" | </td>\n";4910}4911}49124913print"<td class=\"link\">";4914if($not_deleted) {4915print$cgi->a({-href => href(action=>"blob",4916 hash=>$diff->{'to_id'},4917 file_name=>$diff->{'to_file'},4918 hash_base=>$hash)},4919"blob");4920print" | "if($has_history);4921}4922if($has_history) {4923print$cgi->a({-href => href(action=>"history",4924 file_name=>$diff->{'to_file'},4925 hash_base=>$hash)},4926"history");4927}4928print"</td>\n";49294930print"</tr>\n";4931next;# instead of 'else' clause, to avoid extra indent4932}4933# else ordinary diff49344935my($to_mode_oct,$to_mode_str,$to_file_type);4936my($from_mode_oct,$from_mode_str,$from_file_type);4937if($diff->{'to_mode'}ne('0' x 6)) {4938$to_mode_oct=oct$diff->{'to_mode'};4939if(S_ISREG($to_mode_oct)) {# only for regular file4940$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4941}4942$to_file_type= file_type($diff->{'to_mode'});4943}4944if($diff->{'from_mode'}ne('0' x 6)) {4945$from_mode_oct=oct$diff->{'from_mode'};4946if(S_ISREG($from_mode_oct)) {# only for regular file4947$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4948}4949$from_file_type= file_type($diff->{'from_mode'});4950}49514952if($diff->{'status'}eq"A") {# created4953my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4954$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4955$mode_chng.="]</span>";4956print"<td>";4957print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4958 hash_base=>$hash, file_name=>$diff->{'file'}),4959-class=>"list"}, esc_path($diff->{'file'}));4960print"</td>\n";4961print"<td>$mode_chng</td>\n";4962print"<td class=\"link\">";4963if($actioneq'commitdiff') {4964# link to patch4965$patchno++;4966print$cgi->a({-href => href(-anchor=>"patch$patchno")},4967"patch") .4968" | ";4969}4970print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4971 hash_base=>$hash, file_name=>$diff->{'file'})},4972"blob");4973print"</td>\n";49744975}elsif($diff->{'status'}eq"D") {# deleted4976my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4977print"<td>";4978print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4979 hash_base=>$parent, file_name=>$diff->{'file'}),4980-class=>"list"}, esc_path($diff->{'file'}));4981print"</td>\n";4982print"<td>$mode_chng</td>\n";4983print"<td class=\"link\">";4984if($actioneq'commitdiff') {4985# link to patch4986$patchno++;4987print$cgi->a({-href => href(-anchor=>"patch$patchno")},4988"patch") .4989" | ";4990}4991print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4992 hash_base=>$parent, file_name=>$diff->{'file'})},4993"blob") ." | ";4994if($have_blame) {4995print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4996 file_name=>$diff->{'file'})},4997"blame") ." | ";4998}4999print$cgi->a({-href => href(action=>"history", hash_base=>$parent,5000 file_name=>$diff->{'file'})},5001"history");5002print"</td>\n";50035004}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed5005my$mode_chnge="";5006if($diff->{'from_mode'} !=$diff->{'to_mode'}) {5007$mode_chnge="<span class=\"file_status mode_chnge\">[changed";5008if($from_file_typene$to_file_type) {5009$mode_chnge.=" from$from_file_typeto$to_file_type";5010}5011if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {5012if($from_mode_str&&$to_mode_str) {5013$mode_chnge.=" mode:$from_mode_str->$to_mode_str";5014}elsif($to_mode_str) {5015$mode_chnge.=" mode:$to_mode_str";5016}5017}5018$mode_chnge.="]</span>\n";5019}5020print"<td>";5021print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},5022 hash_base=>$hash, file_name=>$diff->{'file'}),5023-class=>"list"}, esc_path($diff->{'file'}));5024print"</td>\n";5025print"<td>$mode_chnge</td>\n";5026print"<td class=\"link\">";5027if($actioneq'commitdiff') {5028# link to patch5029$patchno++;5030print$cgi->a({-href => href(-anchor=>"patch$patchno")},5031"patch") .5032" | ";5033}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {5034# "commit" view and modified file (not onlu mode changed)5035print$cgi->a({-href => href(action=>"blobdiff",5036 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},5037 hash_base=>$hash, hash_parent_base=>$parent,5038 file_name=>$diff->{'file'})},5039"diff") .5040" | ";5041}5042print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},5043 hash_base=>$hash, file_name=>$diff->{'file'})},5044"blob") ." | ";5045if($have_blame) {5046print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,5047 file_name=>$diff->{'file'})},5048"blame") ." | ";5049}5050print$cgi->a({-href => href(action=>"history", hash_base=>$hash,5051 file_name=>$diff->{'file'})},5052"history");5053print"</td>\n";50545055}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied5056my%status_name= ('R'=>'moved','C'=>'copied');5057my$nstatus=$status_name{$diff->{'status'}};5058my$mode_chng="";5059if($diff->{'from_mode'} !=$diff->{'to_mode'}) {5060# mode also for directories, so we cannot use $to_mode_str5061$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);5062}5063print"<td>".5064$cgi->a({-href => href(action=>"blob", hash_base=>$hash,5065 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),5066-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".5067"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".5068$cgi->a({-href => href(action=>"blob", hash_base=>$parent,5069 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),5070-class=>"list"}, esc_path($diff->{'from_file'})) .5071" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".5072"<td class=\"link\">";5073if($actioneq'commitdiff') {5074# link to patch5075$patchno++;5076print$cgi->a({-href => href(-anchor=>"patch$patchno")},5077"patch") .5078" | ";5079}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {5080# "commit" view and modified file (not only pure rename or copy)5081print$cgi->a({-href => href(action=>"blobdiff",5082 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},5083 hash_base=>$hash, hash_parent_base=>$parent,5084 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},5085"diff") .5086" | ";5087}5088print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},5089 hash_base=>$parent, file_name=>$diff->{'to_file'})},5090"blob") ." | ";5091if($have_blame) {5092print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,5093 file_name=>$diff->{'to_file'})},5094"blame") ." | ";5095}5096print$cgi->a({-href => href(action=>"history", hash_base=>$hash,5097 file_name=>$diff->{'to_file'})},5098"history");5099print"</td>\n";51005101}# we should not encounter Unmerged (U) or Unknown (X) status5102print"</tr>\n";5103}5104print"</tbody>"if$has_header;5105print"</table>\n";5106}51075108# Print context lines and then rem/add lines in a side-by-side manner.5109sub print_sidebyside_diff_lines {5110my($ctx,$rem,$add) =@_;51115112# print context block before add/rem block5113if(@$ctx) {5114print join'',5115'<div class="chunk_block ctx">',5116'<div class="old">',5117@$ctx,5118'</div>',5119'<div class="new">',5120@$ctx,5121'</div>',5122'</div>';5123}51245125if(!@$add) {5126# pure removal5127print join'',5128'<div class="chunk_block rem">',5129'<div class="old">',5130@$rem,5131'</div>',5132'</div>';5133}elsif(!@$rem) {5134# pure addition5135print join'',5136'<div class="chunk_block add">',5137'<div class="new">',5138@$add,5139'</div>',5140'</div>';5141}else{5142print join'',5143'<div class="chunk_block chg">',5144'<div class="old">',5145@$rem,5146'</div>',5147'<div class="new">',5148@$add,5149'</div>',5150'</div>';5151}5152}51535154# Print context lines and then rem/add lines in inline manner.5155sub print_inline_diff_lines {5156my($ctx,$rem,$add) =@_;51575158print@$ctx,@$rem,@$add;5159}51605161# Format removed and added line, mark changed part and HTML-format them.5162# Implementation is based on contrib/diff-highlight5163sub format_rem_add_lines_pair {5164my($rem,$add,$num_parents) =@_;51655166# We need to untabify lines before split()'ing them;5167# otherwise offsets would be invalid.5168chomp$rem;5169chomp$add;5170$rem= untabify($rem);5171$add= untabify($add);51725173my@rem=split(//,$rem);5174my@add=split(//,$add);5175my($esc_rem,$esc_add);5176# Ignore leading +/- characters for each parent.5177my($prefix_len,$suffix_len) = ($num_parents,0);5178my($prefix_has_nonspace,$suffix_has_nonspace);51795180my$shorter= (@rem<@add) ?@rem:@add;5181while($prefix_len<$shorter) {5182last if($rem[$prefix_len]ne$add[$prefix_len]);51835184$prefix_has_nonspace=1if($rem[$prefix_len] !~/\s/);5185$prefix_len++;5186}51875188while($prefix_len+$suffix_len<$shorter) {5189last if($rem[-1-$suffix_len]ne$add[-1-$suffix_len]);51905191$suffix_has_nonspace=1if($rem[-1-$suffix_len] !~/\s/);5192$suffix_len++;5193}51945195# Mark lines that are different from each other, but have some common5196# part that isn't whitespace. If lines are completely different, don't5197# mark them because that would make output unreadable, especially if5198# diff consists of multiple lines.5199if($prefix_has_nonspace||$suffix_has_nonspace) {5200$esc_rem= esc_html_hl_regions($rem,'marked',5201[$prefix_len,@rem-$suffix_len], -nbsp=>1);5202$esc_add= esc_html_hl_regions($add,'marked',5203[$prefix_len,@add-$suffix_len], -nbsp=>1);5204}else{5205$esc_rem= esc_html($rem, -nbsp=>1);5206$esc_add= esc_html($add, -nbsp=>1);5207}52085209return format_diff_line(\$esc_rem,'rem'),5210 format_diff_line(\$esc_add,'add');5211}52125213# HTML-format diff context, removed and added lines.5214sub format_ctx_rem_add_lines {5215my($ctx,$rem,$add,$num_parents) =@_;5216my(@new_ctx,@new_rem,@new_add);5217my$can_highlight=0;5218my$is_combined= ($num_parents>1);52195220# Highlight if every removed line has a corresponding added line.5221if(@$add>0&&@$add==@$rem) {5222$can_highlight=1;52235224# Highlight lines in combined diff only if the chunk contains5225# diff between the same version, e.g.5226#5227# - a5228# - b5229# + c5230# + d5231#5232# Otherwise the highlightling would be confusing.5233if($is_combined) {5234for(my$i=0;$i<@$add;$i++) {5235my$prefix_rem=substr($rem->[$i],0,$num_parents);5236my$prefix_add=substr($add->[$i],0,$num_parents);52375238$prefix_rem=~s/-/+/g;52395240if($prefix_remne$prefix_add) {5241$can_highlight=0;5242last;5243}5244}5245}5246}52475248if($can_highlight) {5249for(my$i=0;$i<@$add;$i++) {5250my($line_rem,$line_add) = format_rem_add_lines_pair(5251$rem->[$i],$add->[$i],$num_parents);5252push@new_rem,$line_rem;5253push@new_add,$line_add;5254}5255}else{5256@new_rem=map{ format_diff_line($_,'rem') }@$rem;5257@new_add=map{ format_diff_line($_,'add') }@$add;5258}52595260@new_ctx=map{ format_diff_line($_,'ctx') }@$ctx;52615262return(\@new_ctx, \@new_rem, \@new_add);5263}52645265# Print context lines and then rem/add lines.5266sub print_diff_lines {5267my($ctx,$rem,$add,$diff_style,$num_parents) =@_;5268my$is_combined=$num_parents>1;52695270($ctx,$rem,$add) = format_ctx_rem_add_lines($ctx,$rem,$add,5271$num_parents);52725273if($diff_styleeq'sidebyside'&& !$is_combined) {5274 print_sidebyside_diff_lines($ctx,$rem,$add);5275}else{5276# default 'inline' style and unknown styles5277 print_inline_diff_lines($ctx,$rem,$add);5278}5279}52805281sub print_diff_chunk {5282my($diff_style,$num_parents,$from,$to,@chunk) =@_;5283my(@ctx,@rem,@add);52845285# The class of the previous line.5286my$prev_class='';52875288return unless@chunk;52895290# incomplete last line might be among removed or added lines,5291# or both, or among context lines: find which5292for(my$i=1;$i<@chunk;$i++) {5293if($chunk[$i][0]eq'incomplete') {5294$chunk[$i][0] =$chunk[$i-1][0];5295}5296}52975298# guardian5299push@chunk, ["",""];53005301foreachmy$line_info(@chunk) {5302my($class,$line) =@$line_info;53035304# print chunk headers5305if($class&&$classeq'chunk_header') {5306print format_diff_line($line,$class,$from,$to);5307next;5308}53095310## print from accumulator when have some add/rem lines or end5311# of chunk (flush context lines), or when have add and rem5312# lines and new block is reached (otherwise add/rem lines could5313# be reordered)5314if(!$class|| ((@rem||@add) &&$classeq'ctx') ||5315(@rem&&@add&&$classne$prev_class)) {5316 print_diff_lines(\@ctx, \@rem, \@add,5317$diff_style,$num_parents);5318@ctx=@rem=@add= ();5319}53205321## adding lines to accumulator5322# guardian value5323last unless$line;5324# rem, add or change5325if($classeq'rem') {5326push@rem,$line;5327}elsif($classeq'add') {5328push@add,$line;5329}5330# context line5331if($classeq'ctx') {5332push@ctx,$line;5333}53345335$prev_class=$class;5336}5337}53385339sub git_patchset_body {5340my($fd,$diff_style,$difftree,$hash,@hash_parents) =@_;5341my($hash_parent) =$hash_parents[0];53425343my$is_combined= (@hash_parents>1);5344my$patch_idx=0;5345my$patch_number=0;5346my$patch_line;5347my$diffinfo;5348my$to_name;5349my(%from,%to);5350my@chunk;# for side-by-side diff53515352print"<div class=\"patchset\">\n";53535354# skip to first patch5355while($patch_line= <$fd>) {5356chomp$patch_line;53575358last if($patch_line=~m/^diff /);5359}53605361 PATCH:5362while($patch_line) {53635364# parse "git diff" header line5365if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {5366# $1 is from_name, which we do not use5367$to_name= unquote($2);5368$to_name=~s!^b/!!;5369}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {5370# $1 is 'cc' or 'combined', which we do not use5371$to_name= unquote($2);5372}else{5373$to_name=undef;5374}53755376# check if current patch belong to current raw line5377# and parse raw git-diff line if needed5378if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {5379# this is continuation of a split patch5380print"<div class=\"patch cont\">\n";5381}else{5382# advance raw git-diff output if needed5383$patch_idx++ifdefined$diffinfo;53845385# read and prepare patch information5386$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);53875388# compact combined diff output can have some patches skipped5389# find which patch (using pathname of result) we are at now;5390if($is_combined) {5391while($to_namene$diffinfo->{'to_file'}) {5392print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5393 format_diff_cc_simplified($diffinfo,@hash_parents) .5394"</div>\n";# class="patch"53955396$patch_idx++;5397$patch_number++;53985399last if$patch_idx>$#$difftree;5400$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);5401}5402}54035404# modifies %from, %to hashes5405 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);54065407# this is first patch for raw difftree line with $patch_idx index5408# we index @$difftree array from 0, but number patches from 15409print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";5410}54115412# git diff header5413#assert($patch_line =~ m/^diff /) if DEBUG;5414#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed5415$patch_number++;5416# print "git diff" header5417print format_git_diff_header_line($patch_line,$diffinfo,5418 \%from, \%to);54195420# print extended diff header5421print"<div class=\"diff extended_header\">\n";5422 EXTENDED_HEADER:5423while($patch_line= <$fd>) {5424chomp$patch_line;54255426last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);54275428print format_extended_diff_header_line($patch_line,$diffinfo,5429 \%from, \%to);5430}5431print"</div>\n";# class="diff extended_header"54325433# from-file/to-file diff header5434if(!$patch_line) {5435print"</div>\n";# class="patch"5436last PATCH;5437}5438next PATCH if($patch_line=~m/^diff /);5439#assert($patch_line =~ m/^---/) if DEBUG;54405441my$last_patch_line=$patch_line;5442$patch_line= <$fd>;5443chomp$patch_line;5444#assert($patch_line =~ m/^\+\+\+/) if DEBUG;54455446print format_diff_from_to_header($last_patch_line,$patch_line,5447$diffinfo, \%from, \%to,5448@hash_parents);54495450# the patch itself5451 LINE:5452while($patch_line= <$fd>) {5453chomp$patch_line;54545455next PATCH if($patch_line=~m/^diff /);54565457my$class= diff_line_class($patch_line, \%from, \%to);54585459if($classeq'chunk_header') {5460 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5461@chunk= ();5462}54635464push@chunk, [$class,$patch_line];5465}54665467}continue{5468if(@chunk) {5469 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5470@chunk= ();5471}5472print"</div>\n";# class="patch"5473}54745475# for compact combined (--cc) format, with chunk and patch simplification5476# the patchset might be empty, but there might be unprocessed raw lines5477for(++$patch_idxif$patch_number>0;5478$patch_idx<@$difftree;5479++$patch_idx) {5480# read and prepare patch information5481$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);54825483# generate anchor for "patch" links in difftree / whatchanged part5484print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5485 format_diff_cc_simplified($diffinfo,@hash_parents) .5486"</div>\n";# class="patch"54875488$patch_number++;5489}54905491if($patch_number==0) {5492if(@hash_parents>1) {5493print"<div class=\"diff nodifferences\">Trivial merge</div>\n";5494}else{5495print"<div class=\"diff nodifferences\">No differences found</div>\n";5496}5497}54985499print"</div>\n";# class="patchset"5500}55015502# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55035504sub git_project_search_form {5505my($searchtext,$search_use_regexp) =@_;55065507my$limit='';5508if($project_filter) {5509$limit=" in '$project_filter/'";5510}55115512print"<div class=\"projsearch\">\n";5513print$cgi->startform(-method=>'get', -action =>$my_uri) .5514$cgi->hidden(-name =>'a', -value =>'project_list') ."\n";5515print$cgi->hidden(-name =>'pf', -value =>$project_filter)."\n"5516if(defined$project_filter);5517print$cgi->textfield(-name =>'s', -value =>$searchtext,5518-title =>"Search project by name and description$limit",5519-size =>60) ."\n".5520"<span title=\"Extended regular expression\">".5521$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',5522-checked =>$search_use_regexp) .5523"</span>\n".5524$cgi->submit(-name =>'btnS', -value =>'Search') .5525$cgi->end_form() ."\n".5526$cgi->a({-href => href(project =>undef, searchtext =>undef,5527 project_filter =>$project_filter)},5528 esc_html("List all projects$limit")) ."<br />\n";5529print"</div>\n";5530}55315532# entry for given @keys needs filling if at least one of keys in list5533# is not present in %$project_info5534sub project_info_needs_filling {5535my($project_info,@keys) =@_;55365537# return List::MoreUtils::any { !exists $project_info->{$_} } @keys;5538foreachmy$key(@keys) {5539if(!exists$project_info->{$key}) {5540return1;5541}5542}5543return;5544}55455546# fills project list info (age, description, owner, category, forks, etc.)5547# for each project in the list, removing invalid projects from5548# returned list, or fill only specified info.5549#5550# Invalid projects are removed from the returned list if and only if you5551# ask 'age' or 'age_string' to be filled, because they are the only fields5552# that run unconditionally git command that requires repository, and5553# therefore do always check if project repository is invalid.5554#5555# USAGE:5556# * fill_project_list_info(\@project_list, 'descr_long', 'ctags')5557# ensures that 'descr_long' and 'ctags' fields are filled5558# * @project_list = fill_project_list_info(\@project_list)5559# ensures that all fields are filled (and invalid projects removed)5560#5561# NOTE: modifies $projlist, but does not remove entries from it5562sub fill_project_list_info {5563my($projlist,@wanted_keys) =@_;5564my@projects;5565my$filter_set=sub{return@_; };5566if(@wanted_keys) {5567my%wanted_keys=map{$_=>1}@wanted_keys;5568$filter_set=sub{returngrep{$wanted_keys{$_} }@_; };5569}55705571my$show_ctags= gitweb_check_feature('ctags');5572 PROJECT:5573foreachmy$pr(@$projlist) {5574if(project_info_needs_filling($pr,$filter_set->('age','age_string'))) {5575my(@activity) = git_get_last_activity($pr->{'path'});5576unless(@activity) {5577next PROJECT;5578}5579($pr->{'age'},$pr->{'age_string'}) =@activity;5580}5581if(project_info_needs_filling($pr,$filter_set->('descr','descr_long'))) {5582my$descr= git_get_project_description($pr->{'path'}) ||"";5583$descr= to_utf8($descr);5584$pr->{'descr_long'} =$descr;5585$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);5586}5587if(project_info_needs_filling($pr,$filter_set->('owner'))) {5588$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";5589}5590if($show_ctags&&5591 project_info_needs_filling($pr,$filter_set->('ctags'))) {5592$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});5593}5594if($projects_list_group_categories&&5595 project_info_needs_filling($pr,$filter_set->('category'))) {5596my$cat= git_get_project_category($pr->{'path'}) ||5597$project_list_default_category;5598$pr->{'category'} = to_utf8($cat);5599}56005601push@projects,$pr;5602}56035604return@projects;5605}56065607sub sort_projects_list {5608my($projlist,$order) =@_;56095610sub order_str {5611my$key=shift;5612return sub{$a->{$key}cmp$b->{$key} };5613}56145615sub order_num_then_undef {5616my$key=shift;5617return sub{5618defined$a->{$key} ?5619(defined$b->{$key} ?$a->{$key} <=>$b->{$key} : -1) :5620(defined$b->{$key} ?1:0)5621};5622}56235624my%orderings= (5625 project => order_str('path'),5626 descr => order_str('descr_long'),5627 owner => order_str('owner'),5628 age => order_num_then_undef('age'),5629);56305631my$ordering=$orderings{$order};5632returndefined$ordering?sort$ordering @$projlist:@$projlist;5633}56345635# returns a hash of categories, containing the list of project5636# belonging to each category5637sub build_projlist_by_category {5638my($projlist,$from,$to) =@_;5639my%categories;56405641$from=0unlessdefined$from;5642$to=$#$projlistif(!defined$to||$#$projlist<$to);56435644for(my$i=$from;$i<=$to;$i++) {5645my$pr=$projlist->[$i];5646push@{$categories{$pr->{'category'} }},$pr;5647}56485649returnwantarray?%categories: \%categories;5650}56515652# print 'sort by' <th> element, generating 'sort by $name' replay link5653# if that order is not selected5654sub print_sort_th {5655print format_sort_th(@_);5656}56575658sub format_sort_th {5659my($name,$order,$header) =@_;5660my$sort_th="";5661$header||=ucfirst($name);56625663if($ordereq$name) {5664$sort_th.="<th>$header</th>\n";5665}else{5666$sort_th.="<th>".5667$cgi->a({-href => href(-replay=>1, order=>$name),5668-class=>"header"},$header) .5669"</th>\n";5670}56715672return$sort_th;5673}56745675sub git_project_list_rows {5676my($projlist,$from,$to,$check_forks) =@_;56775678$from=0unlessdefined$from;5679$to=$#$projlistif(!defined$to||$#$projlist<$to);56805681my$alternate=1;5682for(my$i=$from;$i<=$to;$i++) {5683my$pr=$projlist->[$i];56845685if($alternate) {5686print"<tr class=\"dark\">\n";5687}else{5688print"<tr class=\"light\">\n";5689}5690$alternate^=1;56915692if($check_forks) {5693print"<td>";5694if($pr->{'forks'}) {5695my$nforks=scalar@{$pr->{'forks'}};5696if($nforks>0) {5697print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5698-title =>"$nforksforks"},"+");5699}else{5700print$cgi->span({-title =>"$nforksforks"},"+");5701}5702}5703print"</td>\n";5704}5705print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5706-class=>"list"},5707 esc_html_match_hl($pr->{'path'},$search_regexp)) .5708"</td>\n".5709"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5710-class=>"list",5711-title =>$pr->{'descr_long'}},5712$search_regexp5713? esc_html_match_hl_chopped($pr->{'descr_long'},5714$pr->{'descr'},$search_regexp)5715: esc_html($pr->{'descr'})) .5716"</td>\n";5717unless($omit_owner) {5718print"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5719}5720unless($omit_age_column) {5721print"<td class=\"". age_class($pr->{'age'}) ."\">".5722(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n";5723}5724print"<td class=\"link\">".5725$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5726$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5727$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5728$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5729($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5730"</td>\n".5731"</tr>\n";5732}5733}57345735sub git_project_list_body {5736# actually uses global variable $project5737my($projlist,$order,$from,$to,$extra,$no_header) =@_;5738my@projects=@$projlist;57395740my$check_forks= gitweb_check_feature('forks');5741my$show_ctags= gitweb_check_feature('ctags');5742my$tagfilter=$show_ctags?$input_params{'ctag'} :undef;5743$check_forks=undef5744if($tagfilter||$search_regexp);57455746# filtering out forks before filling info allows to do less work5747@projects= filter_forks_from_projects_list(\@projects)5748if($check_forks);5749# search_projects_list pre-fills required info5750@projects= search_projects_list(\@projects,5751'search_regexp'=>$search_regexp,5752'tagfilter'=>$tagfilter)5753if($tagfilter||$search_regexp);5754# fill the rest5755my@all_fields= ('descr','descr_long','ctags','category');5756push@all_fields, ('age','age_string')unless($omit_age_column);5757push@all_fields,'owner'unless($omit_owner);5758@projects= fill_project_list_info(\@projects,@all_fields);57595760$order||=$default_projects_order;5761$from=0unlessdefined$from;5762$to=$#projectsif(!defined$to||$#projects<$to);57635764# short circuit5765if($from>$to) {5766print"<center>\n".5767"<b>No such projects found</b><br />\n".5768"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5769"</center>\n<br />\n";5770return;5771}57725773@projects= sort_projects_list(\@projects,$order);57745775if($show_ctags) {5776my$ctags= git_gather_all_ctags(\@projects);5777my$cloud= git_populate_project_tagcloud($ctags);5778print git_show_project_tagcloud($cloud,64);5779}57805781print"<table class=\"project_list\">\n";5782unless($no_header) {5783print"<tr>\n";5784if($check_forks) {5785print"<th></th>\n";5786}5787 print_sort_th('project',$order,'Project');5788 print_sort_th('descr',$order,'Description');5789 print_sort_th('owner',$order,'Owner')unless$omit_owner;5790 print_sort_th('age',$order,'Last Change')unless$omit_age_column;5791print"<th></th>\n".# for links5792"</tr>\n";5793}57945795if($projects_list_group_categories) {5796# only display categories with projects in the $from-$to window5797@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5798my%categories= build_projlist_by_category(\@projects,$from,$to);5799foreachmy$cat(sort keys%categories) {5800unless($cateq"") {5801print"<tr>\n";5802if($check_forks) {5803print"<td></td>\n";5804}5805print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5806print"</tr>\n";5807}58085809 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5810}5811}else{5812 git_project_list_rows(\@projects,$from,$to,$check_forks);5813}58145815if(defined$extra) {5816print"<tr>\n";5817if($check_forks) {5818print"<td></td>\n";5819}5820print"<td colspan=\"5\">$extra</td>\n".5821"</tr>\n";5822}5823print"</table>\n";5824}58255826sub git_log_body {5827# uses global variable $project5828my($commitlist,$from,$to,$refs,$extra) =@_;58295830$from=0unlessdefined$from;5831$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);58325833for(my$i=0;$i<=$to;$i++) {5834my%co= %{$commitlist->[$i]};5835next if!%co;5836my$commit=$co{'id'};5837my$ref= format_ref_marker($refs,$commit);5838 git_print_header_div('commit',5839"<span class=\"age\">$co{'age_string'}</span>".5840 esc_html($co{'title'}) .$ref,5841$commit);5842print"<div class=\"title_text\">\n".5843"<div class=\"log_link\">\n".5844$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5845" | ".5846$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5847" | ".5848$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5849"<br/>\n".5850"</div>\n";5851 git_print_authorship(\%co, -tag =>'span');5852print"<br/>\n</div>\n";58535854print"<div class=\"log_body\">\n";5855 git_print_log($co{'comment'}, -final_empty_line=>1);5856print"</div>\n";5857}5858if($extra) {5859print"<div class=\"page_nav\">\n";5860print"$extra\n";5861print"</div>\n";5862}5863}58645865sub git_shortlog_body {5866# uses global variable $project5867my($commitlist,$from,$to,$refs,$extra) =@_;58685869$from=0unlessdefined$from;5870$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);58715872print"<table class=\"shortlog\">\n";5873my$alternate=1;5874for(my$i=$from;$i<=$to;$i++) {5875my%co= %{$commitlist->[$i]};5876my$commit=$co{'id'};5877my$ref= format_ref_marker($refs,$commit);5878if($alternate) {5879print"<tr class=\"dark\">\n";5880}else{5881print"<tr class=\"light\">\n";5882}5883$alternate^=1;5884# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5885print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5886 format_author_html('td', \%co,10) ."<td>";5887print format_subject_html($co{'title'},$co{'title_short'},5888 href(action=>"commit", hash=>$commit),$ref);5889print"</td>\n".5890"<td class=\"link\">".5891$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5892$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5893$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5894my$snapshot_links= format_snapshot_links($commit);5895if(defined$snapshot_links) {5896print" | ".$snapshot_links;5897}5898print"</td>\n".5899"</tr>\n";5900}5901if(defined$extra) {5902print"<tr>\n".5903"<td colspan=\"4\">$extra</td>\n".5904"</tr>\n";5905}5906print"</table>\n";5907}59085909sub git_history_body {5910# Warning: assumes constant type (blob or tree) during history5911my($commitlist,$from,$to,$refs,$extra,5912$file_name,$file_hash,$ftype) =@_;59135914$from=0unlessdefined$from;5915$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});59165917print"<table class=\"history\">\n";5918my$alternate=1;5919for(my$i=$from;$i<=$to;$i++) {5920my%co= %{$commitlist->[$i]};5921if(!%co) {5922next;5923}5924my$commit=$co{'id'};59255926my$ref= format_ref_marker($refs,$commit);59275928if($alternate) {5929print"<tr class=\"dark\">\n";5930}else{5931print"<tr class=\"light\">\n";5932}5933$alternate^=1;5934print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5935# shortlog: format_author_html('td', \%co, 10)5936 format_author_html('td', \%co,15,3) ."<td>";5937# originally git_history used chop_str($co{'title'}, 50)5938print format_subject_html($co{'title'},$co{'title_short'},5939 href(action=>"commit", hash=>$commit),$ref);5940print"</td>\n".5941"<td class=\"link\">".5942$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5943$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");59445945if($ftypeeq'blob') {5946my$blob_current=$file_hash;5947my$blob_parent= git_get_hash_by_path($commit,$file_name);5948if(defined$blob_current&&defined$blob_parent&&5949$blob_currentne$blob_parent) {5950print" | ".5951$cgi->a({-href => href(action=>"blobdiff",5952 hash=>$blob_current, hash_parent=>$blob_parent,5953 hash_base=>$hash_base, hash_parent_base=>$commit,5954 file_name=>$file_name)},5955"diff to current");5956}5957}5958print"</td>\n".5959"</tr>\n";5960}5961if(defined$extra) {5962print"<tr>\n".5963"<td colspan=\"4\">$extra</td>\n".5964"</tr>\n";5965}5966print"</table>\n";5967}59685969sub git_tags_body {5970# uses global variable $project5971my($taglist,$from,$to,$extra) =@_;5972$from=0unlessdefined$from;5973$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);59745975print"<table class=\"tags\">\n";5976my$alternate=1;5977for(my$i=$from;$i<=$to;$i++) {5978my$entry=$taglist->[$i];5979my%tag=%$entry;5980my$comment=$tag{'subject'};5981my$comment_short;5982if(defined$comment) {5983$comment_short= chop_str($comment,30,5);5984}5985if($alternate) {5986print"<tr class=\"dark\">\n";5987}else{5988print"<tr class=\"light\">\n";5989}5990$alternate^=1;5991if(defined$tag{'age'}) {5992print"<td><i>$tag{'age'}</i></td>\n";5993}else{5994print"<td></td>\n";5995}5996print"<td>".5997$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5998-class=>"list name"}, esc_html($tag{'name'})) .5999"</td>\n".6000"<td>";6001if(defined$comment) {6002print format_subject_html($comment,$comment_short,6003 href(action=>"tag", hash=>$tag{'id'}));6004}6005print"</td>\n".6006"<td class=\"selflink\">";6007if($tag{'type'}eq"tag") {6008print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");6009}else{6010print" ";6011}6012print"</td>\n".6013"<td class=\"link\">"." | ".6014$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});6015if($tag{'reftype'}eq"commit") {6016print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .6017" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");6018}elsif($tag{'reftype'}eq"blob") {6019print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");6020}6021print"</td>\n".6022"</tr>";6023}6024if(defined$extra) {6025print"<tr>\n".6026"<td colspan=\"5\">$extra</td>\n".6027"</tr>\n";6028}6029print"</table>\n";6030}60316032sub git_heads_body {6033# uses global variable $project6034my($headlist,$head_at,$from,$to,$extra) =@_;6035$from=0unlessdefined$from;6036$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);60376038print"<table class=\"heads\">\n";6039my$alternate=1;6040for(my$i=$from;$i<=$to;$i++) {6041my$entry=$headlist->[$i];6042my%ref=%$entry;6043my$curr=defined$head_at&&$ref{'id'}eq$head_at;6044if($alternate) {6045print"<tr class=\"dark\">\n";6046}else{6047print"<tr class=\"light\">\n";6048}6049$alternate^=1;6050print"<td><i>$ref{'age'}</i></td>\n".6051($curr?"<td class=\"current_head\">":"<td>") .6052$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),6053-class=>"list name"},esc_html($ref{'name'})) .6054"</td>\n".6055"<td class=\"link\">".6056$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".6057$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".6058$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .6059"</td>\n".6060"</tr>";6061}6062if(defined$extra) {6063print"<tr>\n".6064"<td colspan=\"3\">$extra</td>\n".6065"</tr>\n";6066}6067print"</table>\n";6068}60696070# Display a single remote block6071sub git_remote_block {6072my($remote,$rdata,$limit,$head) =@_;60736074my$heads=$rdata->{'heads'};6075my$fetch=$rdata->{'fetch'};6076my$push=$rdata->{'push'};60776078my$urls_table="<table class=\"projects_list\">\n";60796080if(defined$fetch) {6081if($fetcheq$push) {6082$urls_table.= format_repo_url("URL",$fetch);6083}else{6084$urls_table.= format_repo_url("Fetch URL",$fetch);6085$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;6086}6087}elsif(defined$push) {6088$urls_table.= format_repo_url("Push URL",$push);6089}else{6090$urls_table.= format_repo_url("","No remote URL");6091}60926093$urls_table.="</table>\n";60946095my$dots;6096if(defined$limit&&$limit<@$heads) {6097$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");6098}60996100print$urls_table;6101 git_heads_body($heads,$head,0,$limit,$dots);6102}61036104# Display a list of remote names with the respective fetch and push URLs6105sub git_remotes_list {6106my($remotedata,$limit) =@_;6107print"<table class=\"heads\">\n";6108my$alternate=1;6109my@remotes=sort keys%$remotedata;61106111my$limited=$limit&&$limit<@remotes;61126113$#remotes=$limit-1if$limited;61146115while(my$remote=shift@remotes) {6116my$rdata=$remotedata->{$remote};6117my$fetch=$rdata->{'fetch'};6118my$push=$rdata->{'push'};6119if($alternate) {6120print"<tr class=\"dark\">\n";6121}else{6122print"<tr class=\"light\">\n";6123}6124$alternate^=1;6125print"<td>".6126$cgi->a({-href=> href(action=>'remotes', hash=>$remote),6127-class=>"list name"},esc_html($remote)) .6128"</td>";6129print"<td class=\"link\">".6130(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .6131" | ".6132(defined$push?$cgi->a({-href=>$push},"push") :"push") .6133"</td>";61346135print"</tr>\n";6136}61376138if($limited) {6139print"<tr>\n".6140"<td colspan=\"3\">".6141$cgi->a({-href => href(action=>"remotes")},"...") .6142"</td>\n"."</tr>\n";6143}61446145print"</table>";6146}61476148# Display remote heads grouped by remote, unless there are too many6149# remotes, in which case we only display the remote names6150sub git_remotes_body {6151my($remotedata,$limit,$head) =@_;6152if($limitand$limit<keys%$remotedata) {6153 git_remotes_list($remotedata,$limit);6154}else{6155 fill_remote_heads($remotedata);6156while(my($remote,$rdata) =each%$remotedata) {6157 git_print_section({-class=>"remote", -id=>$remote},6158["remotes",$remote,$remote],sub{6159 git_remote_block($remote,$rdata,$limit,$head);6160});6161}6162}6163}61646165sub git_search_message {6166my%co=@_;61676168my$greptype;6169if($searchtypeeq'commit') {6170$greptype="--grep=";6171}elsif($searchtypeeq'author') {6172$greptype="--author=";6173}elsif($searchtypeeq'committer') {6174$greptype="--committer=";6175}6176$greptype.=$searchtext;6177my@commitlist= parse_commits($hash,101, (100*$page),undef,6178$greptype,'--regexp-ignore-case',6179$search_use_regexp?'--extended-regexp':'--fixed-strings');61806181my$paging_nav='';6182if($page>0) {6183$paging_nav.=6184$cgi->a({-href => href(-replay=>1, page=>undef)},6185"first") .6186" ⋅ ".6187$cgi->a({-href => href(-replay=>1, page=>$page-1),6188-accesskey =>"p", -title =>"Alt-p"},"prev");6189}else{6190$paging_nav.="first ⋅ prev";6191}6192my$next_link='';6193if($#commitlist>=100) {6194$next_link=6195$cgi->a({-href => href(-replay=>1, page=>$page+1),6196-accesskey =>"n", -title =>"Alt-n"},"next");6197$paging_nav.=" ⋅$next_link";6198}else{6199$paging_nav.=" ⋅ next";6200}62016202 git_header_html();62036204 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);6205 git_print_header_div('commit', esc_html($co{'title'}),$hash);6206if($page==0&& !@commitlist) {6207print"<p>No match.</p>\n";6208}else{6209 git_search_grep_body(\@commitlist,0,99,$next_link);6210}62116212 git_footer_html();6213}62146215sub git_search_changes {6216my%co=@_;62176218local$/="\n";6219open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,6220'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",6221($search_use_regexp?'--pickaxe-regex': ())6222or die_error(500,"Open git-log failed");62236224 git_header_html();62256226 git_print_page_nav('','',$hash,$co{'tree'},$hash);6227 git_print_header_div('commit', esc_html($co{'title'}),$hash);62286229print"<table class=\"pickaxe search\">\n";6230my$alternate=1;6231undef%co;6232my@files;6233while(my$line= <$fd>) {6234chomp$line;6235next unless$line;62366237my%set= parse_difftree_raw_line($line);6238if(defined$set{'commit'}) {6239# finish previous commit6240if(%co) {6241print"</td>\n".6242"<td class=\"link\">".6243$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6244"commit") .6245" | ".6246$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6247 hash_base=>$co{'id'})},6248"tree") .6249"</td>\n".6250"</tr>\n";6251}62526253if($alternate) {6254print"<tr class=\"dark\">\n";6255}else{6256print"<tr class=\"light\">\n";6257}6258$alternate^=1;6259%co= parse_commit($set{'commit'});6260my$author= chop_and_escape_str($co{'author_name'},15,5);6261print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6262"<td><i>$author</i></td>\n".6263"<td>".6264$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6265-class=>"list subject"},6266 chop_and_escape_str($co{'title'},50) ."<br/>");6267}elsif(defined$set{'to_id'}) {6268next if($set{'to_id'} =~m/^0{40}$/);62696270print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},6271 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),6272-class=>"list"},6273"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .6274"<br/>\n";6275}6276}6277close$fd;62786279# finish last commit (warning: repetition!)6280if(%co) {6281print"</td>\n".6282"<td class=\"link\">".6283$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6284"commit") .6285" | ".6286$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6287 hash_base=>$co{'id'})},6288"tree") .6289"</td>\n".6290"</tr>\n";6291}62926293print"</table>\n";62946295 git_footer_html();6296}62976298sub git_search_files {6299my%co=@_;63006301local$/="\n";6302open my$fd,"-|", git_cmd(),'grep','-n','-z',6303$search_use_regexp? ('-E','-i') :'-F',6304$searchtext,$co{'tree'}6305or die_error(500,"Open git-grep failed");63066307 git_header_html();63086309 git_print_page_nav('','',$hash,$co{'tree'},$hash);6310 git_print_header_div('commit', esc_html($co{'title'}),$hash);63116312print"<table class=\"grep_search\">\n";6313my$alternate=1;6314my$matches=0;6315my$lastfile='';6316my$file_href;6317while(my$line= <$fd>) {6318chomp$line;6319my($file,$lno,$ltext,$binary);6320last if($matches++>1000);6321if($line=~/^Binary file (.+) matches$/) {6322$file=$1;6323$binary=1;6324}else{6325($file,$lno,$ltext) =split(/\0/,$line,3);6326$file=~s/^$co{'tree'}://;6327}6328if($filene$lastfile) {6329$lastfileand print"</td></tr>\n";6330if($alternate++) {6331print"<tr class=\"dark\">\n";6332}else{6333print"<tr class=\"light\">\n";6334}6335$file_href= href(action=>"blob", hash_base=>$co{'id'},6336 file_name=>$file);6337print"<td class=\"list\">".6338$cgi->a({-href =>$file_href, -class=>"list"}, esc_path($file));6339print"</td><td>\n";6340$lastfile=$file;6341}6342if($binary) {6343print"<div class=\"binary\">Binary file</div>\n";6344}else{6345$ltext= untabify($ltext);6346if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6347$ltext= esc_html($1, -nbsp=>1);6348$ltext.='<span class="match">';6349$ltext.= esc_html($2, -nbsp=>1);6350$ltext.='</span>';6351$ltext.= esc_html($3, -nbsp=>1);6352}else{6353$ltext= esc_html($ltext, -nbsp=>1);6354}6355print"<div class=\"pre\">".6356$cgi->a({-href =>$file_href.'#l'.$lno,6357-class=>"linenr"},sprintf('%4i',$lno)) .6358' '.$ltext."</div>\n";6359}6360}6361if($lastfile) {6362print"</td></tr>\n";6363if($matches>1000) {6364print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6365}6366}else{6367print"<div class=\"diff nodifferences\">No matches found</div>\n";6368}6369close$fd;63706371print"</table>\n";63726373 git_footer_html();6374}63756376sub git_search_grep_body {6377my($commitlist,$from,$to,$extra) =@_;6378$from=0unlessdefined$from;6379$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);63806381print"<table class=\"commit_search\">\n";6382my$alternate=1;6383for(my$i=$from;$i<=$to;$i++) {6384my%co= %{$commitlist->[$i]};6385if(!%co) {6386next;6387}6388my$commit=$co{'id'};6389if($alternate) {6390print"<tr class=\"dark\">\n";6391}else{6392print"<tr class=\"light\">\n";6393}6394$alternate^=1;6395print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6396 format_author_html('td', \%co,15,5) .6397"<td>".6398$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6399-class=>"list subject"},6400 chop_and_escape_str($co{'title'},50) ."<br/>");6401my$comment=$co{'comment'};6402foreachmy$line(@$comment) {6403if($line=~m/^(.*?)($search_regexp)(.*)$/i) {6404my($lead,$match,$trail) = ($1,$2,$3);6405$match= chop_str($match,70,5,'center');6406my$contextlen=int((80-length($match))/2);6407$contextlen=30if($contextlen>30);6408$lead= chop_str($lead,$contextlen,10,'left');6409$trail= chop_str($trail,$contextlen,10,'right');64106411$lead= esc_html($lead);6412$match= esc_html($match);6413$trail= esc_html($trail);64146415print"$lead<span class=\"match\">$match</span>$trail<br />";6416}6417}6418print"</td>\n".6419"<td class=\"link\">".6420$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6421" | ".6422$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .6423" | ".6424$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6425print"</td>\n".6426"</tr>\n";6427}6428if(defined$extra) {6429print"<tr>\n".6430"<td colspan=\"3\">$extra</td>\n".6431"</tr>\n";6432}6433print"</table>\n";6434}64356436## ======================================================================6437## ======================================================================6438## actions64396440sub git_project_list {6441my$order=$input_params{'order'};6442if(defined$order&&$order!~m/none|project|descr|owner|age/) {6443 die_error(400,"Unknown order parameter");6444}64456446my@list= git_get_projects_list($project_filter,$strict_export);6447if(!@list) {6448 die_error(404,"No projects found");6449}64506451 git_header_html();6452if(defined$home_text&& -f $home_text) {6453print"<div class=\"index_include\">\n";6454 insert_file($home_text);6455print"</div>\n";6456}64576458 git_project_search_form($searchtext,$search_use_regexp);6459 git_project_list_body(\@list,$order);6460 git_footer_html();6461}64626463sub git_forks {6464my$order=$input_params{'order'};6465if(defined$order&&$order!~m/none|project|descr|owner|age/) {6466 die_error(400,"Unknown order parameter");6467}64686469my$filter=$project;6470$filter=~s/\.git$//;6471my@list= git_get_projects_list($filter);6472if(!@list) {6473 die_error(404,"No forks found");6474}64756476 git_header_html();6477 git_print_page_nav('','');6478 git_print_header_div('summary',"$projectforks");6479 git_project_list_body(\@list,$order);6480 git_footer_html();6481}64826483sub git_project_index {6484my@projects= git_get_projects_list($project_filter,$strict_export);6485if(!@projects) {6486 die_error(404,"No projects found");6487}64886489print$cgi->header(6490-type =>'text/plain',6491-charset =>'utf-8',6492-content_disposition =>'inline; filename="index.aux"');64936494foreachmy$pr(@projects) {6495if(!exists$pr->{'owner'}) {6496$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");6497}64986499my($path,$owner) = ($pr->{'path'},$pr->{'owner'});6500# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '6501$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6502$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6503$path=~s/ /\+/g;6504$owner=~s/ /\+/g;65056506print"$path$owner\n";6507}6508}65096510sub git_summary {6511my$descr= git_get_project_description($project) ||"none";6512my%co= parse_commit("HEAD");6513my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();6514my$head=$co{'id'};6515my$remote_heads= gitweb_check_feature('remote_heads');65166517my$owner= git_get_project_owner($project);65186519my$refs= git_get_references();6520# These get_*_list functions return one more to allow us to see if6521# there are more ...6522my@taglist= git_get_tags_list(16);6523my@headlist= git_get_heads_list(16);6524my%remotedata=$remote_heads? git_get_remotes_list() : ();6525my@forklist;6526my$check_forks= gitweb_check_feature('forks');65276528if($check_forks) {6529# find forks of a project6530my$filter=$project;6531$filter=~s/\.git$//;6532@forklist= git_get_projects_list($filter);6533# filter out forks of forks6534@forklist= filter_forks_from_projects_list(\@forklist)6535if(@forklist);6536}65376538 git_header_html();6539 git_print_page_nav('summary','',$head);65406541print"<div class=\"title\"> </div>\n";6542print"<table class=\"projects_list\">\n".6543"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n";6544if($ownerand not$omit_owner) {6545print"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";6546}6547if(defined$cd{'rfc2822'}) {6548print"<tr id=\"metadata_lchange\"><td>last change</td>".6549"<td>".format_timestamp_html(\%cd)."</td></tr>\n";6550}65516552# use per project git URL list in $projectroot/$project/cloneurl6553# or make project git URL from git base URL and project name6554my$url_tag="URL";6555my@url_list= git_get_project_url_list($project);6556@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;6557foreachmy$git_url(@url_list) {6558next unless$git_url;6559print format_repo_url($url_tag,$git_url);6560$url_tag="";6561}65626563# Tag cloud6564my$show_ctags= gitweb_check_feature('ctags');6565if($show_ctags) {6566my$ctags= git_get_project_ctags($project);6567if(%$ctags) {6568# without ability to add tags, don't show if there are none6569my$cloud= git_populate_project_tagcloud($ctags);6570print"<tr id=\"metadata_ctags\">".6571"<td>content tags</td>".6572"<td>".git_show_project_tagcloud($cloud,48)."</td>".6573"</tr>\n";6574}6575}65766577print"</table>\n";65786579# If XSS prevention is on, we don't include README.html.6580# TODO: Allow a readme in some safe format.6581if(!$prevent_xss&& -s "$projectroot/$project/README.html") {6582print"<div class=\"title\">readme</div>\n".6583"<div class=\"readme\">\n";6584 insert_file("$projectroot/$project/README.html");6585print"\n</div>\n";# class="readme"6586}65876588# we need to request one more than 16 (0..15) to check if6589# those 16 are all6590my@commitlist=$head? parse_commits($head,17) : ();6591if(@commitlist) {6592 git_print_header_div('shortlog');6593 git_shortlog_body(\@commitlist,0,15,$refs,6594$#commitlist<=15?undef:6595$cgi->a({-href => href(action=>"shortlog")},"..."));6596}65976598if(@taglist) {6599 git_print_header_div('tags');6600 git_tags_body(\@taglist,0,15,6601$#taglist<=15?undef:6602$cgi->a({-href => href(action=>"tags")},"..."));6603}66046605if(@headlist) {6606 git_print_header_div('heads');6607 git_heads_body(\@headlist,$head,0,15,6608$#headlist<=15?undef:6609$cgi->a({-href => href(action=>"heads")},"..."));6610}66116612if(%remotedata) {6613 git_print_header_div('remotes');6614 git_remotes_body(\%remotedata,15,$head);6615}66166617if(@forklist) {6618 git_print_header_div('forks');6619 git_project_list_body(\@forklist,'age',0,15,6620$#forklist<=15?undef:6621$cgi->a({-href => href(action=>"forks")},"..."),6622'no_header');6623}66246625 git_footer_html();6626}66276628sub git_tag {6629my%tag= parse_tag($hash);66306631if(!%tag) {6632 die_error(404,"Unknown tag object");6633}66346635my$head= git_get_head_hash($project);6636 git_header_html();6637 git_print_page_nav('','',$head,undef,$head);6638 git_print_header_div('commit', esc_html($tag{'name'}),$hash);6639print"<div class=\"title_text\">\n".6640"<table class=\"object_header\">\n".6641"<tr>\n".6642"<td>object</td>\n".6643"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6644$tag{'object'}) ."</td>\n".6645"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6646$tag{'type'}) ."</td>\n".6647"</tr>\n";6648if(defined($tag{'author'})) {6649 git_print_authorship_rows(\%tag,'author');6650}6651print"</table>\n\n".6652"</div>\n";6653print"<div class=\"page_body\">";6654my$comment=$tag{'comment'};6655foreachmy$line(@$comment) {6656chomp$line;6657print esc_html($line, -nbsp=>1) ."<br/>\n";6658}6659print"</div>\n";6660 git_footer_html();6661}66626663sub git_blame_common {6664my$format=shift||'porcelain';6665if($formateq'porcelain'&&$input_params{'javascript'}) {6666$format='incremental';6667$action='blame_incremental';# for page title etc6668}66696670# permissions6671 gitweb_check_feature('blame')6672or die_error(403,"Blame view not allowed");66736674# error checking6675 die_error(400,"No file name given")unless$file_name;6676$hash_base||= git_get_head_hash($project);6677 die_error(404,"Couldn't find base commit")unless$hash_base;6678my%co= parse_commit($hash_base)6679or die_error(404,"Commit not found");6680my$ftype="blob";6681if(!defined$hash) {6682$hash= git_get_hash_by_path($hash_base,$file_name,"blob")6683or die_error(404,"Error looking up file");6684}else{6685$ftype= git_get_type($hash);6686if($ftype!~"blob") {6687 die_error(400,"Object is not a blob");6688}6689}66906691my$fd;6692if($formateq'incremental') {6693# get file contents (as base)6694open$fd,"-|", git_cmd(),'cat-file','blob',$hash6695or die_error(500,"Open git-cat-file failed");6696}elsif($formateq'data') {6697# run git-blame --incremental6698open$fd,"-|", git_cmd(),"blame","--incremental",6699$hash_base,"--",$file_name6700or die_error(500,"Open git-blame --incremental failed");6701}else{6702# run git-blame --porcelain6703open$fd,"-|", git_cmd(),"blame",'-p',6704$hash_base,'--',$file_name6705or die_error(500,"Open git-blame --porcelain failed");6706}6707binmode$fd,':utf8';67086709# incremental blame data returns early6710if($formateq'data') {6711print$cgi->header(6712-type=>"text/plain", -charset =>"utf-8",6713-status=>"200 OK");6714local$| =1;# output autoflush6715while(my$line= <$fd>) {6716print to_utf8($line);6717}6718close$fd6719or print"ERROR$!\n";67206721print'END';6722if(defined$t0&& gitweb_check_feature('timed')) {6723print' '.6724 tv_interval($t0, [ gettimeofday() ]).6725' '.$number_of_git_cmds;6726}6727print"\n";67286729return;6730}67316732# page header6733 git_header_html();6734my$formats_nav=6735$cgi->a({-href => href(action=>"blob", -replay=>1)},6736"blob") .6737" | ";6738if($formateq'incremental') {6739$formats_nav.=6740$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},6741"blame") ." (non-incremental)";6742}else{6743$formats_nav.=6744$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},6745"blame") ." (incremental)";6746}6747$formats_nav.=6748" | ".6749$cgi->a({-href => href(action=>"history", -replay=>1)},6750"history") .6751" | ".6752$cgi->a({-href => href(action=>$action, file_name=>$file_name)},6753"HEAD");6754 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6755 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6756 git_print_page_path($file_name,$ftype,$hash_base);67576758# page body6759if($formateq'incremental') {6760print"<noscript>\n<div class=\"error\"><center><b>\n".6761"This page requires JavaScript to run.\nUse ".6762$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},6763'this page').6764" instead.\n".6765"</b></center></div>\n</noscript>\n";67666767print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;6768}67696770print qq!<div class="page_body">\n!;6771print qq!<div id="progress_info">.../ ...</div>\n!6772if($formateq'incremental');6773print qq!<table id="blame_table"class="blame" width="100%">\n!.6774#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.6775 qq!<thead>\n!.6776 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.6777 qq!</thead>\n!.6778 qq!<tbody>\n!;67796780my@rev_color=qw(light dark);6781my$num_colors=scalar(@rev_color);6782my$current_color=0;67836784if($formateq'incremental') {6785my$color_class=$rev_color[$current_color];67866787#contents of a file6788my$linenr=0;6789 LINE:6790while(my$line= <$fd>) {6791chomp$line;6792$linenr++;67936794print qq!<tr id="l$linenr"class="$color_class">!.6795 qq!<td class="sha1"><a href=""> </a></td>!.6796 qq!<td class="linenr">!.6797 qq!<a class="linenr" href="">$linenr</a></td>!;6798print qq!<td class="pre">! . esc_html($line) ."</td>\n";6799print qq!</tr>\n!;6800}68016802}else{# porcelain, i.e. ordinary blame6803my%metainfo= ();# saves information about commits68046805# blame data6806 LINE:6807while(my$line= <$fd>) {6808chomp$line;6809# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]6810# no <lines in group> for subsequent lines in group of lines6811my($full_rev,$orig_lineno,$lineno,$group_size) =6812($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);6813if(!exists$metainfo{$full_rev}) {6814$metainfo{$full_rev} = {'nprevious'=>0};6815}6816my$meta=$metainfo{$full_rev};6817my$data;6818while($data= <$fd>) {6819chomp$data;6820last if($data=~s/^\t//);# contents of line6821if($data=~/^(\S+)(?: (.*))?$/) {6822$meta->{$1} =$2unlessexists$meta->{$1};6823}6824if($data=~/^previous /) {6825$meta->{'nprevious'}++;6826}6827}6828my$short_rev=substr($full_rev,0,8);6829my$author=$meta->{'author'};6830my%date=6831 parse_date($meta->{'author-time'},$meta->{'author-tz'});6832my$date=$date{'iso-tz'};6833if($group_size) {6834$current_color= ($current_color+1) %$num_colors;6835}6836my$tr_class=$rev_color[$current_color];6837$tr_class.=' boundary'if(exists$meta->{'boundary'});6838$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);6839$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);6840print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";6841if($group_size) {6842print"<td class=\"sha1\"";6843print" title=\"". esc_html($author) .",$date\"";6844print" rowspan=\"$group_size\""if($group_size>1);6845print">";6846print$cgi->a({-href => href(action=>"commit",6847 hash=>$full_rev,6848 file_name=>$file_name)},6849 esc_html($short_rev));6850if($group_size>=2) {6851my@author_initials= ($author=~/\b([[:upper:]])\B/g);6852if(@author_initials) {6853print"<br />".6854 esc_html(join('',@author_initials));6855# or join('.', ...)6856}6857}6858print"</td>\n";6859}6860# 'previous' <sha1 of parent commit> <filename at commit>6861if(exists$meta->{'previous'} &&6862$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {6863$meta->{'parent'} =$1;6864$meta->{'file_parent'} = unquote($2);6865}6866my$linenr_commit=6867exists($meta->{'parent'}) ?6868$meta->{'parent'} :$full_rev;6869my$linenr_filename=6870exists($meta->{'file_parent'}) ?6871$meta->{'file_parent'} : unquote($meta->{'filename'});6872my$blamed= href(action =>'blame',6873 file_name =>$linenr_filename,6874 hash_base =>$linenr_commit);6875print"<td class=\"linenr\">";6876print$cgi->a({ -href =>"$blamed#l$orig_lineno",6877-class=>"linenr"},6878 esc_html($lineno));6879print"</td>";6880print"<td class=\"pre\">". esc_html($data) ."</td>\n";6881print"</tr>\n";6882}# end while68836884}68856886# footer6887print"</tbody>\n".6888"</table>\n";# class="blame"6889print"</div>\n";# class="blame_body"6890close$fd6891or print"Reading blob failed\n";68926893 git_footer_html();6894}68956896sub git_blame {6897 git_blame_common();6898}68996900sub git_blame_incremental {6901 git_blame_common('incremental');6902}69036904sub git_blame_data {6905 git_blame_common('data');6906}69076908sub git_tags {6909my$head= git_get_head_hash($project);6910 git_header_html();6911 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6912 git_print_header_div('summary',$project);69136914my@tagslist= git_get_tags_list();6915if(@tagslist) {6916 git_tags_body(\@tagslist);6917}6918 git_footer_html();6919}69206921sub git_heads {6922my$head= git_get_head_hash($project);6923 git_header_html();6924 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6925 git_print_header_div('summary',$project);69266927my@headslist= git_get_heads_list();6928if(@headslist) {6929 git_heads_body(\@headslist,$head);6930}6931 git_footer_html();6932}69336934# used both for single remote view and for list of all the remotes6935sub git_remotes {6936 gitweb_check_feature('remote_heads')6937or die_error(403,"Remote heads view is disabled");69386939my$head= git_get_head_hash($project);6940my$remote=$input_params{'hash'};69416942my$remotedata= git_get_remotes_list($remote);6943 die_error(500,"Unable to get remote information")unlessdefined$remotedata;69446945unless(%$remotedata) {6946 die_error(404,defined$remote?6947"Remote$remotenot found":6948"No remotes found");6949}69506951 git_header_html(undef,undef, -action_extra =>$remote);6952 git_print_page_nav('','',$head,undef,$head,6953 format_ref_views($remote?'':'remotes'));69546955 fill_remote_heads($remotedata);6956if(defined$remote) {6957 git_print_header_div('remotes',"$remoteremote for$project");6958 git_remote_block($remote,$remotedata->{$remote},undef,$head);6959}else{6960 git_print_header_div('summary',"$projectremotes");6961 git_remotes_body($remotedata,undef,$head);6962}69636964 git_footer_html();6965}69666967sub git_blob_plain {6968my$type=shift;6969my$expires;69706971if(!defined$hash) {6972if(defined$file_name) {6973my$base=$hash_base|| git_get_head_hash($project);6974$hash= git_get_hash_by_path($base,$file_name,"blob")6975or die_error(404,"Cannot find file");6976}else{6977 die_error(400,"No file name defined");6978}6979}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6980# blobs defined by non-textual hash id's can be cached6981$expires="+1d";6982}69836984open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6985or die_error(500,"Open git-cat-file blob '$hash' failed");69866987# content-type (can include charset)6988$type= blob_contenttype($fd,$file_name,$type);69896990# "save as" filename, even when no $file_name is given6991my$save_as="$hash";6992if(defined$file_name) {6993$save_as=$file_name;6994}elsif($type=~m/^text\//) {6995$save_as.='.txt';6996}69976998# With XSS prevention on, blobs of all types except a few known safe6999# ones are served with "Content-Disposition: attachment" to make sure7000# they don't run in our security domain. For certain image types,7001# blob view writes an <img> tag referring to blob_plain view, and we7002# want to be sure not to break that by serving the image as an7003# attachment (though Firefox 3 doesn't seem to care).7004my$sandbox=$prevent_xss&&7005$type!~m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;70067007# serve text/* as text/plain7008if($prevent_xss&&7009($type=~m!^text/[a-z]+\b(.*)$!||7010($type=~m!^[a-z]+/[a-z]\+xml\b(.*)$!&& -T $fd))) {7011my$rest=$1;7012$rest=defined$rest?$rest:'';7013$type="text/plain$rest";7014}70157016print$cgi->header(7017-type =>$type,7018-expires =>$expires,7019-content_disposition =>7020($sandbox?'attachment':'inline')7021.'; filename="'.$save_as.'"');7022local$/=undef;7023binmode STDOUT,':raw';7024print<$fd>;7025binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi7026close$fd;7027}70287029sub git_blob {7030my$expires;70317032if(!defined$hash) {7033if(defined$file_name) {7034my$base=$hash_base|| git_get_head_hash($project);7035$hash= git_get_hash_by_path($base,$file_name,"blob")7036or die_error(404,"Cannot find file");7037}else{7038 die_error(400,"No file name defined");7039}7040}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {7041# blobs defined by non-textual hash id's can be cached7042$expires="+1d";7043}70447045my$have_blame= gitweb_check_feature('blame');7046open my$fd,"-|", git_cmd(),"cat-file","blob",$hash7047or die_error(500,"Couldn't cat$file_name,$hash");7048my$mimetype= blob_mimetype($fd,$file_name);7049# use 'blob_plain' (aka 'raw') view for files that cannot be displayed7050if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {7051close$fd;7052return git_blob_plain($mimetype);7053}7054# we can have blame only for text/* mimetype7055$have_blame&&= ($mimetype=~m!^text/!);70567057my$highlight= gitweb_check_feature('highlight');7058my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);7059$fd= run_highlighter($fd,$highlight,$syntax)7060if$syntax;70617062 git_header_html(undef,$expires);7063my$formats_nav='';7064if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7065if(defined$file_name) {7066if($have_blame) {7067$formats_nav.=7068$cgi->a({-href => href(action=>"blame", -replay=>1)},7069"blame") .7070" | ";7071}7072$formats_nav.=7073$cgi->a({-href => href(action=>"history", -replay=>1)},7074"history") .7075" | ".7076$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},7077"raw") .7078" | ".7079$cgi->a({-href => href(action=>"blob",7080 hash_base=>"HEAD", file_name=>$file_name)},7081"HEAD");7082}else{7083$formats_nav.=7084$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},7085"raw");7086}7087 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7088 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7089}else{7090print"<div class=\"page_nav\">\n".7091"<br/><br/></div>\n".7092"<div class=\"title\">".esc_html($hash)."</div>\n";7093}7094 git_print_page_path($file_name,"blob",$hash_base);7095print"<div class=\"page_body\">\n";7096if($mimetype=~m!^image/!) {7097print qq!<img type="!.esc_attr($mimetype).qq!"!;7098if($file_name) {7099print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;7100}7101print qq! src="! .7102 href(action=>"blob_plain", hash=>$hash,7103 hash_base=>$hash_base, file_name=>$file_name) .7104 qq!"/>\n!;7105}else{7106my$nr;7107while(my$line= <$fd>) {7108chomp$line;7109$nr++;7110$line= untabify($line);7111printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,7112$nr, esc_attr(href(-replay =>1)),$nr,$nr,7113$syntax? sanitize($line) : esc_html($line, -nbsp=>1);7114}7115}7116close$fd7117or print"Reading blob failed.\n";7118print"</div>";7119 git_footer_html();7120}71217122sub git_tree {7123if(!defined$hash_base) {7124$hash_base="HEAD";7125}7126if(!defined$hash) {7127if(defined$file_name) {7128$hash= git_get_hash_by_path($hash_base,$file_name,"tree");7129}else{7130$hash=$hash_base;7131}7132}7133 die_error(404,"No such tree")unlessdefined($hash);71347135my$show_sizes= gitweb_check_feature('show-sizes');7136my$have_blame= gitweb_check_feature('blame');71377138my@entries= ();7139{7140local$/="\0";7141open my$fd,"-|", git_cmd(),"ls-tree",'-z',7142($show_sizes?'-l': ()),@extra_options,$hash7143or die_error(500,"Open git-ls-tree failed");7144@entries=map{chomp;$_} <$fd>;7145close$fd7146or die_error(404,"Reading tree failed");7147}71487149my$refs= git_get_references();7150my$ref= format_ref_marker($refs,$hash_base);7151 git_header_html();7152my$basedir='';7153if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7154my@views_nav= ();7155if(defined$file_name) {7156push@views_nav,7157$cgi->a({-href => href(action=>"history", -replay=>1)},7158"history"),7159$cgi->a({-href => href(action=>"tree",7160 hash_base=>"HEAD", file_name=>$file_name)},7161"HEAD"),7162}7163my$snapshot_links= format_snapshot_links($hash);7164if(defined$snapshot_links) {7165# FIXME: Should be available when we have no hash base as well.7166push@views_nav,$snapshot_links;7167}7168 git_print_page_nav('tree','',$hash_base,undef,undef,7169join(' | ',@views_nav));7170 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);7171}else{7172undef$hash_base;7173print"<div class=\"page_nav\">\n";7174print"<br/><br/></div>\n";7175print"<div class=\"title\">".esc_html($hash)."</div>\n";7176}7177if(defined$file_name) {7178$basedir=$file_name;7179if($basedirne''&&substr($basedir, -1)ne'/') {7180$basedir.='/';7181}7182 git_print_page_path($file_name,'tree',$hash_base);7183}7184print"<div class=\"page_body\">\n";7185print"<table class=\"tree\">\n";7186my$alternate=1;7187# '..' (top directory) link if possible7188if(defined$hash_base&&7189defined$file_name&&$file_name=~m![^/]+$!) {7190if($alternate) {7191print"<tr class=\"dark\">\n";7192}else{7193print"<tr class=\"light\">\n";7194}7195$alternate^=1;71967197my$up=$file_name;7198$up=~s!/?[^/]+$!!;7199undef$upunless$up;7200# based on git_print_tree_entry7201print'<td class="mode">'. mode_str('040000') ."</td>\n";7202print'<td class="size"> </td>'."\n"if$show_sizes;7203print'<td class="list">';7204print$cgi->a({-href => href(action=>"tree",7205 hash_base=>$hash_base,7206 file_name=>$up)},7207"..");7208print"</td>\n";7209print"<td class=\"link\"></td>\n";72107211print"</tr>\n";7212}7213foreachmy$line(@entries) {7214my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);72157216if($alternate) {7217print"<tr class=\"dark\">\n";7218}else{7219print"<tr class=\"light\">\n";7220}7221$alternate^=1;72227223 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);72247225print"</tr>\n";7226}7227print"</table>\n".7228"</div>";7229 git_footer_html();7230}72317232sub sanitize_for_filename {7233my$name=shift;72347235$name=~s!/!-!g;7236$name=~s/[^[:alnum:]_.-]//g;72377238return$name;7239}72407241sub snapshot_name {7242my($project,$hash) =@_;72437244# path/to/project.git -> project7245# path/to/project/.git -> project7246my$name= to_utf8($project);7247$name=~ s,([^/])/*\.git$,$1,;7248$name= sanitize_for_filename(basename($name));72497250my$ver=$hash;7251if($hash=~/^[0-9a-fA-F]+$/) {7252# shorten SHA-1 hash7253my$full_hash= git_get_full_hash($project,$hash);7254if($full_hash=~/^$hash/&&length($hash) >7) {7255$ver= git_get_short_hash($project,$hash);7256}7257}elsif($hash=~m!^refs/tags/(.*)$!) {7258# tags don't need shortened SHA-1 hash7259$ver=$1;7260}else{7261# branches and other need shortened SHA-1 hash7262my$strip_refs=join'|',map{quotemeta} get_branch_refs();7263if($hash=~m!^refs/($strip_refs|remotes)/(.*)$!) {7264my$ref_dir= (defined$1) ?$1:'';7265$ver=$2;72667267$ref_dir= sanitize_for_filename($ref_dir);7268# for refs neither in heads nor remotes we want to7269# add a ref dir to archive name7270if($ref_dirne''and$ref_dirne'heads'and$ref_dirne'remotes') {7271$ver=$ref_dir.'-'.$ver;7272}7273}7274$ver.='-'. git_get_short_hash($project,$hash);7275}7276# special case of sanitization for filename - we change7277# slashes to dots instead of dashes7278# in case of hierarchical branch names7279$ver=~s!/!.!g;7280$ver=~s/[^[:alnum:]_.-]//g;72817282# name = project-version_string7283$name="$name-$ver";72847285returnwantarray? ($name,$name) :$name;7286}72877288sub exit_if_unmodified_since {7289my($latest_epoch) =@_;7290our$cgi;72917292my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7293if(defined$if_modified) {7294my$since;7295if(eval{require HTTP::Date;1; }) {7296$since= HTTP::Date::str2time($if_modified);7297}elsif(eval{require Time::ParseDate;1; }) {7298$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7299}7300if(defined$since&&$latest_epoch<=$since) {7301my%latest_date= parse_date($latest_epoch);7302print$cgi->header(7303-last_modified =>$latest_date{'rfc2822'},7304-status =>'304 Not Modified');7305goto DONE_GITWEB;7306}7307}7308}73097310sub git_snapshot {7311my$format=$input_params{'snapshot_format'};7312if(!@snapshot_fmts) {7313 die_error(403,"Snapshots not allowed");7314}7315# default to first supported snapshot format7316$format||=$snapshot_fmts[0];7317if($format!~m/^[a-z0-9]+$/) {7318 die_error(400,"Invalid snapshot format parameter");7319}elsif(!exists($known_snapshot_formats{$format})) {7320 die_error(400,"Unknown snapshot format");7321}elsif($known_snapshot_formats{$format}{'disabled'}) {7322 die_error(403,"Snapshot format not allowed");7323}elsif(!grep($_eq$format,@snapshot_fmts)) {7324 die_error(403,"Unsupported snapshot format");7325}73267327my$type= git_get_type("$hash^{}");7328if(!$type) {7329 die_error(404,'Object does not exist');7330}elsif($typeeq'blob') {7331 die_error(400,'Object is not a tree-ish');7332}73337334my($name,$prefix) = snapshot_name($project,$hash);7335my$filename="$name$known_snapshot_formats{$format}{'suffix'}";73367337my%co= parse_commit($hash);7338 exit_if_unmodified_since($co{'committer_epoch'})if%co;73397340my$cmd= quote_command(7341 git_cmd(),'archive',7342"--format=$known_snapshot_formats{$format}{'format'}",7343"--prefix=$prefix/",$hash);7344if(exists$known_snapshot_formats{$format}{'compressor'}) {7345$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});7346}73477348$filename=~s/(["\\])/\\$1/g;7349my%latest_date;7350if(%co) {7351%latest_date= parse_date($co{'committer_epoch'},$co{'committer_tz'});7352}73537354print$cgi->header(7355-type =>$known_snapshot_formats{$format}{'type'},7356-content_disposition =>'inline; filename="'.$filename.'"',7357%co? (-last_modified =>$latest_date{'rfc2822'}) : (),7358-status =>'200 OK');73597360open my$fd,"-|",$cmd7361or die_error(500,"Execute git-archive failed");7362binmode STDOUT,':raw';7363print<$fd>;7364binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi7365close$fd;7366}73677368sub git_log_generic {7369my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;73707371my$head= git_get_head_hash($project);7372if(!defined$base) {7373$base=$head;7374}7375if(!defined$page) {7376$page=0;7377}7378my$refs= git_get_references();73797380my$commit_hash=$base;7381if(defined$parent) {7382$commit_hash="$parent..$base";7383}7384my@commitlist=7385 parse_commits($commit_hash,101, (100*$page),7386defined$file_name? ($file_name,"--full-history") : ());73877388my$ftype;7389if(!defined$file_hash&&defined$file_name) {7390# some commits could have deleted file in question,7391# and not have it in tree, but one of them has to have it7392for(my$i=0;$i<@commitlist;$i++) {7393$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);7394last ifdefined$file_hash;7395}7396}7397if(defined$file_hash) {7398$ftype= git_get_type($file_hash);7399}7400if(defined$file_name&& !defined$ftype) {7401 die_error(500,"Unknown type of object");7402}7403my%co;7404if(defined$file_name) {7405%co= parse_commit($base)7406or die_error(404,"Unknown commit object");7407}740874097410my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);7411my$next_link='';7412if($#commitlist>=100) {7413$next_link=7414$cgi->a({-href => href(-replay=>1, page=>$page+1),7415-accesskey =>"n", -title =>"Alt-n"},"next");7416}7417my$patch_max= gitweb_get_feature('patches');7418if($patch_max&& !defined$file_name) {7419if($patch_max<0||@commitlist<=$patch_max) {7420$paging_nav.=" ⋅ ".7421$cgi->a({-href => href(action=>"patches", -replay=>1)},7422"patches");7423}7424}74257426 git_header_html();7427 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);7428if(defined$file_name) {7429 git_print_header_div('commit', esc_html($co{'title'}),$base);7430}else{7431 git_print_header_div('summary',$project)7432}7433 git_print_page_path($file_name,$ftype,$hash_base)7434if(defined$file_name);74357436$body_subr->(\@commitlist,0,99,$refs,$next_link,7437$file_name,$file_hash,$ftype);74387439 git_footer_html();7440}74417442sub git_log {7443 git_log_generic('log', \&git_log_body,7444$hash,$hash_parent);7445}74467447sub git_commit {7448$hash||=$hash_base||"HEAD";7449my%co= parse_commit($hash)7450or die_error(404,"Unknown commit object");74517452my$parent=$co{'parent'};7453my$parents=$co{'parents'};# listref74547455# we need to prepare $formats_nav before any parameter munging7456my$formats_nav;7457if(!defined$parent) {7458# --root commitdiff7459$formats_nav.='(initial)';7460}elsif(@$parents==1) {7461# single parent commit7462$formats_nav.=7463'(parent: '.7464$cgi->a({-href => href(action=>"commit",7465 hash=>$parent)},7466 esc_html(substr($parent,0,7))) .7467')';7468}else{7469# merge commit7470$formats_nav.=7471'(merge: '.7472join(' ',map{7473$cgi->a({-href => href(action=>"commit",7474 hash=>$_)},7475 esc_html(substr($_,0,7)));7476}@$parents) .7477')';7478}7479if(gitweb_check_feature('patches') &&@$parents<=1) {7480$formats_nav.=" | ".7481$cgi->a({-href => href(action=>"patch", -replay=>1)},7482"patch");7483}74847485if(!defined$parent) {7486$parent="--root";7487}7488my@difftree;7489open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",7490@diff_opts,7491(@$parents<=1?$parent:'-c'),7492$hash,"--"7493or die_error(500,"Open git-diff-tree failed");7494@difftree=map{chomp;$_} <$fd>;7495close$fdor die_error(404,"Reading git-diff-tree failed");74967497# non-textual hash id's can be cached7498my$expires;7499if($hash=~m/^[0-9a-fA-F]{40}$/) {7500$expires="+1d";7501}7502my$refs= git_get_references();7503my$ref= format_ref_marker($refs,$co{'id'});75047505 git_header_html(undef,$expires);7506 git_print_page_nav('commit','',7507$hash,$co{'tree'},$hash,7508$formats_nav);75097510if(defined$co{'parent'}) {7511 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);7512}else{7513 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);7514}7515print"<div class=\"title_text\">\n".7516"<table class=\"object_header\">\n";7517 git_print_authorship_rows(\%co);7518print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";7519print"<tr>".7520"<td>tree</td>".7521"<td class=\"sha1\">".7522$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),7523class=>"list"},$co{'tree'}) .7524"</td>".7525"<td class=\"link\">".7526$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},7527"tree");7528my$snapshot_links= format_snapshot_links($hash);7529if(defined$snapshot_links) {7530print" | ".$snapshot_links;7531}7532print"</td>".7533"</tr>\n";75347535foreachmy$par(@$parents) {7536print"<tr>".7537"<td>parent</td>".7538"<td class=\"sha1\">".7539$cgi->a({-href => href(action=>"commit", hash=>$par),7540class=>"list"},$par) .7541"</td>".7542"<td class=\"link\">".7543$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .7544" | ".7545$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .7546"</td>".7547"</tr>\n";7548}7549print"</table>".7550"</div>\n";75517552print"<div class=\"page_body\">\n";7553 git_print_log($co{'comment'});7554print"</div>\n";75557556 git_difftree_body(\@difftree,$hash,@$parents);75577558 git_footer_html();7559}75607561sub git_object {7562# object is defined by:7563# - hash or hash_base alone7564# - hash_base and file_name7565my$type;75667567# - hash or hash_base alone7568if($hash|| ($hash_base&& !defined$file_name)) {7569my$object_id=$hash||$hash_base;75707571open my$fd,"-|", quote_command(7572 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'7573or die_error(404,"Object does not exist");7574$type= <$fd>;7575chomp$type;7576close$fd7577or die_error(404,"Object does not exist");75787579# - hash_base and file_name7580}elsif($hash_base&&defined$file_name) {7581$file_name=~ s,/+$,,;75827583system(git_cmd(),"cat-file",'-e',$hash_base) ==07584or die_error(404,"Base object does not exist");75857586# here errors should not happen7587open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name7588or die_error(500,"Open git-ls-tree failed");7589my$line= <$fd>;7590close$fd;75917592#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'7593unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {7594 die_error(404,"File or directory for given base does not exist");7595}7596$type=$2;7597$hash=$3;7598}else{7599 die_error(400,"Not enough information to find object");7600}76017602print$cgi->redirect(-uri => href(action=>$type, -full=>1,7603 hash=>$hash, hash_base=>$hash_base,7604 file_name=>$file_name),7605-status =>'302 Found');7606}76077608sub git_blobdiff {7609my$format=shift||'html';7610my$diff_style=$input_params{'diff_style'} ||'inline';76117612my$fd;7613my@difftree;7614my%diffinfo;7615my$expires;76167617# preparing $fd and %diffinfo for git_patchset_body7618# new style URI7619if(defined$hash_base&&defined$hash_parent_base) {7620if(defined$file_name) {7621# read raw output7622open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7623$hash_parent_base,$hash_base,7624"--", (defined$file_parent?$file_parent: ()),$file_name7625or die_error(500,"Open git-diff-tree failed");7626@difftree=map{chomp;$_} <$fd>;7627close$fd7628or die_error(404,"Reading git-diff-tree failed");7629@difftree7630or die_error(404,"Blob diff not found");76317632}elsif(defined$hash&&7633$hash=~/[0-9a-fA-F]{40}/) {7634# try to find filename from $hash76357636# read filtered raw output7637open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7638$hash_parent_base,$hash_base,"--"7639or die_error(500,"Open git-diff-tree failed");7640@difftree=7641# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'7642# $hash == to_id7643grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}7644map{chomp;$_} <$fd>;7645close$fd7646or die_error(404,"Reading git-diff-tree failed");7647@difftree7648or die_error(404,"Blob diff not found");76497650}else{7651 die_error(400,"Missing one of the blob diff parameters");7652}76537654if(@difftree>1) {7655 die_error(400,"Ambiguous blob diff specification");7656}76577658%diffinfo= parse_difftree_raw_line($difftree[0]);7659$file_parent||=$diffinfo{'from_file'} ||$file_name;7660$file_name||=$diffinfo{'to_file'};76617662$hash_parent||=$diffinfo{'from_id'};7663$hash||=$diffinfo{'to_id'};76647665# non-textual hash id's can be cached7666if($hash_base=~m/^[0-9a-fA-F]{40}$/&&7667$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {7668$expires='+1d';7669}76707671# open patch output7672open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7673'-p', ($formateq'html'?"--full-index": ()),7674$hash_parent_base,$hash_base,7675"--", (defined$file_parent?$file_parent: ()),$file_name7676or die_error(500,"Open git-diff-tree failed");7677}76787679# old/legacy style URI -- not generated anymore since 1.4.3.7680if(!%diffinfo) {7681 die_error('404 Not Found',"Missing one of the blob diff parameters")7682}76837684# header7685if($formateq'html') {7686my$formats_nav=7687$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},7688"raw");7689$formats_nav.= diff_style_nav($diff_style);7690 git_header_html(undef,$expires);7691if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7692 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7693 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7694}else{7695print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";7696print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";7697}7698if(defined$file_name) {7699 git_print_page_path($file_name,"blob",$hash_base);7700}else{7701print"<div class=\"page_path\"></div>\n";7702}77037704}elsif($formateq'plain') {7705print$cgi->header(7706-type =>'text/plain',7707-charset =>'utf-8',7708-expires =>$expires,7709-content_disposition =>'inline; filename="'."$file_name".'.patch"');77107711print"X-Git-Url: ".$cgi->self_url() ."\n\n";77127713}else{7714 die_error(400,"Unknown blobdiff format");7715}77167717# patch7718if($formateq'html') {7719print"<div class=\"page_body\">\n";77207721 git_patchset_body($fd,$diff_style,7722[ \%diffinfo],$hash_base,$hash_parent_base);7723close$fd;77247725print"</div>\n";# class="page_body"7726 git_footer_html();77277728}else{7729while(my$line= <$fd>) {7730$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;7731$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;77327733print$line;77347735last if$line=~m!^\+\+\+!;7736}7737local$/=undef;7738print<$fd>;7739close$fd;7740}7741}77427743sub git_blobdiff_plain {7744 git_blobdiff('plain');7745}77467747# assumes that it is added as later part of already existing navigation,7748# so it returns "| foo | bar" rather than just "foo | bar"7749sub diff_style_nav {7750my($diff_style,$is_combined) =@_;7751$diff_style||='inline';77527753return""if($is_combined);77547755my@styles= (inline =>'inline','sidebyside'=>'side by side');7756my%styles=@styles;7757@styles=7758@styles[map{$_*2}0..$#styles/2];77597760returnjoin'',7761map{" | ".$_}7762map{7763$_eq$diff_style?$styles{$_} :7764$cgi->a({-href => href(-replay=>1, diff_style =>$_)},$styles{$_})7765}@styles;7766}77677768sub git_commitdiff {7769my%params=@_;7770my$format=$params{-format} ||'html';7771my$diff_style=$input_params{'diff_style'} ||'inline';77727773my($patch_max) = gitweb_get_feature('patches');7774if($formateq'patch') {7775 die_error(403,"Patch view not allowed")unless$patch_max;7776}77777778$hash||=$hash_base||"HEAD";7779my%co= parse_commit($hash)7780or die_error(404,"Unknown commit object");77817782# choose format for commitdiff for merge7783if(!defined$hash_parent&& @{$co{'parents'}} >1) {7784$hash_parent='--cc';7785}7786# we need to prepare $formats_nav before almost any parameter munging7787my$formats_nav;7788if($formateq'html') {7789$formats_nav=7790$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},7791"raw");7792if($patch_max&& @{$co{'parents'}} <=1) {7793$formats_nav.=" | ".7794$cgi->a({-href => href(action=>"patch", -replay=>1)},7795"patch");7796}7797$formats_nav.= diff_style_nav($diff_style, @{$co{'parents'}} >1);77987799if(defined$hash_parent&&7800$hash_parentne'-c'&&$hash_parentne'--cc') {7801# commitdiff with two commits given7802my$hash_parent_short=$hash_parent;7803if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {7804$hash_parent_short=substr($hash_parent,0,7);7805}7806$formats_nav.=7807' (from';7808for(my$i=0;$i< @{$co{'parents'}};$i++) {7809if($co{'parents'}[$i]eq$hash_parent) {7810$formats_nav.=' parent '. ($i+1);7811last;7812}7813}7814$formats_nav.=': '.7815$cgi->a({-href => href(-replay=>1,7816 hash=>$hash_parent, hash_base=>undef)},7817 esc_html($hash_parent_short)) .7818')';7819}elsif(!$co{'parent'}) {7820# --root commitdiff7821$formats_nav.=' (initial)';7822}elsif(scalar@{$co{'parents'}} ==1) {7823# single parent commit7824$formats_nav.=7825' (parent: '.7826$cgi->a({-href => href(-replay=>1,7827 hash=>$co{'parent'}, hash_base=>undef)},7828 esc_html(substr($co{'parent'},0,7))) .7829')';7830}else{7831# merge commit7832if($hash_parenteq'--cc') {7833$formats_nav.=' | '.7834$cgi->a({-href => href(-replay=>1,7835 hash=>$hash, hash_parent=>'-c')},7836'combined');7837}else{# $hash_parent eq '-c'7838$formats_nav.=' | '.7839$cgi->a({-href => href(-replay=>1,7840 hash=>$hash, hash_parent=>'--cc')},7841'compact');7842}7843$formats_nav.=7844' (merge: '.7845join(' ',map{7846$cgi->a({-href => href(-replay=>1,7847 hash=>$_, hash_base=>undef)},7848 esc_html(substr($_,0,7)));7849} @{$co{'parents'}} ) .7850')';7851}7852}78537854my$hash_parent_param=$hash_parent;7855if(!defined$hash_parent_param) {7856# --cc for multiple parents, --root for parentless7857$hash_parent_param=7858@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';7859}78607861# read commitdiff7862my$fd;7863my@difftree;7864if($formateq'html') {7865open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7866"--no-commit-id","--patch-with-raw","--full-index",7867$hash_parent_param,$hash,"--"7868or die_error(500,"Open git-diff-tree failed");78697870while(my$line= <$fd>) {7871chomp$line;7872# empty line ends raw part of diff-tree output7873last unless$line;7874push@difftree,scalar parse_difftree_raw_line($line);7875}78767877}elsif($formateq'plain') {7878open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7879'-p',$hash_parent_param,$hash,"--"7880or die_error(500,"Open git-diff-tree failed");7881}elsif($formateq'patch') {7882# For commit ranges, we limit the output to the number of7883# patches specified in the 'patches' feature.7884# For single commits, we limit the output to a single patch,7885# diverging from the git-format-patch default.7886my@commit_spec= ();7887if($hash_parent) {7888if($patch_max>0) {7889push@commit_spec,"-$patch_max";7890}7891push@commit_spec,'-n',"$hash_parent..$hash";7892}else{7893if($params{-single}) {7894push@commit_spec,'-1';7895}else{7896if($patch_max>0) {7897push@commit_spec,"-$patch_max";7898}7899push@commit_spec,"-n";7900}7901push@commit_spec,'--root',$hash;7902}7903open$fd,"-|", git_cmd(),"format-patch",@diff_opts,7904'--encoding=utf8','--stdout',@commit_spec7905or die_error(500,"Open git-format-patch failed");7906}else{7907 die_error(400,"Unknown commitdiff format");7908}79097910# non-textual hash id's can be cached7911my$expires;7912if($hash=~m/^[0-9a-fA-F]{40}$/) {7913$expires="+1d";7914}79157916# write commit message7917if($formateq'html') {7918my$refs= git_get_references();7919my$ref= format_ref_marker($refs,$co{'id'});79207921 git_header_html(undef,$expires);7922 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);7923 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);7924print"<div class=\"title_text\">\n".7925"<table class=\"object_header\">\n";7926 git_print_authorship_rows(\%co);7927print"</table>".7928"</div>\n";7929print"<div class=\"page_body\">\n";7930if(@{$co{'comment'}} >1) {7931print"<div class=\"log\">\n";7932 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);7933print"</div>\n";# class="log"7934}79357936}elsif($formateq'plain') {7937my$refs= git_get_references("tags");7938my$tagname= git_get_rev_name_tags($hash);7939my$filename= basename($project) ."-$hash.patch";79407941print$cgi->header(7942-type =>'text/plain',7943-charset =>'utf-8',7944-expires =>$expires,7945-content_disposition =>'inline; filename="'."$filename".'"');7946my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});7947print"From: ". to_utf8($co{'author'}) ."\n";7948print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";7949print"Subject: ". to_utf8($co{'title'}) ."\n";79507951print"X-Git-Tag:$tagname\n"if$tagname;7952print"X-Git-Url: ".$cgi->self_url() ."\n\n";79537954foreachmy$line(@{$co{'comment'}}) {7955print to_utf8($line) ."\n";7956}7957print"---\n\n";7958}elsif($formateq'patch') {7959my$filename= basename($project) ."-$hash.patch";79607961print$cgi->header(7962-type =>'text/plain',7963-charset =>'utf-8',7964-expires =>$expires,7965-content_disposition =>'inline; filename="'."$filename".'"');7966}79677968# write patch7969if($formateq'html') {7970my$use_parents= !defined$hash_parent||7971$hash_parenteq'-c'||$hash_parenteq'--cc';7972 git_difftree_body(\@difftree,$hash,7973$use_parents? @{$co{'parents'}} :$hash_parent);7974print"<br/>\n";79757976 git_patchset_body($fd,$diff_style,7977 \@difftree,$hash,7978$use_parents? @{$co{'parents'}} :$hash_parent);7979close$fd;7980print"</div>\n";# class="page_body"7981 git_footer_html();79827983}elsif($formateq'plain') {7984local$/=undef;7985print<$fd>;7986close$fd7987or print"Reading git-diff-tree failed\n";7988}elsif($formateq'patch') {7989local$/=undef;7990print<$fd>;7991close$fd7992or print"Reading git-format-patch failed\n";7993}7994}79957996sub git_commitdiff_plain {7997 git_commitdiff(-format =>'plain');7998}79998000# format-patch-style patches8001sub git_patch {8002 git_commitdiff(-format =>'patch', -single =>1);8003}80048005sub git_patches {8006 git_commitdiff(-format =>'patch');8007}80088009sub git_history {8010 git_log_generic('history', \&git_history_body,8011$hash_base,$hash_parent_base,8012$file_name,$hash);8013}80148015sub git_search {8016$searchtype||='commit';80178018# check if appropriate features are enabled8019 gitweb_check_feature('search')8020or die_error(403,"Search is disabled");8021if($searchtypeeq'pickaxe') {8022# pickaxe may take all resources of your box and run for several minutes8023# with every query - so decide by yourself how public you make this feature8024 gitweb_check_feature('pickaxe')8025or die_error(403,"Pickaxe search is disabled");8026}8027if($searchtypeeq'grep') {8028# grep search might be potentially CPU-intensive, too8029 gitweb_check_feature('grep')8030or die_error(403,"Grep search is disabled");8031}80328033if(!defined$searchtext) {8034 die_error(400,"Text field is empty");8035}8036if(!defined$hash) {8037$hash= git_get_head_hash($project);8038}8039my%co= parse_commit($hash);8040if(!%co) {8041 die_error(404,"Unknown commit object");8042}8043if(!defined$page) {8044$page=0;8045}80468047if($searchtypeeq'commit'||8048$searchtypeeq'author'||8049$searchtypeeq'committer') {8050 git_search_message(%co);8051}elsif($searchtypeeq'pickaxe') {8052 git_search_changes(%co);8053}elsif($searchtypeeq'grep') {8054 git_search_files(%co);8055}else{8056 die_error(400,"Unknown search type");8057}8058}80598060sub git_search_help {8061 git_header_html();8062 git_print_page_nav('','',$hash,$hash,$hash);8063print<<EOT;8064<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without8065regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,8066the pattern entered is recognized as the POSIX extended8067<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case8068insensitive).</p>8069<dl>8070<dt><b>commit</b></dt>8071<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>8072EOT8073my$have_grep= gitweb_check_feature('grep');8074if($have_grep) {8075print<<EOT;8076<dt><b>grep</b></dt>8077<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing8078 a different one) are searched for the given pattern. On large trees, this search can take8079a while and put some strain on the server, so please use it with some consideration. Note that8080due to git-grep peculiarity, currently if regexp mode is turned off, the matches are8081case-sensitive.</dd>8082EOT8083}8084print<<EOT;8085<dt><b>author</b></dt>8086<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>8087<dt><b>committer</b></dt>8088<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>8089EOT8090my$have_pickaxe= gitweb_check_feature('pickaxe');8091if($have_pickaxe) {8092print<<EOT;8093<dt><b>pickaxe</b></dt>8094<dd>All commits that caused the string to appear or disappear from any file (changes that8095added, removed or "modified" the string) will be listed. This search can take a while and8096takes a lot of strain on the server, so please use it wisely. Note that since you may be8097interested even in changes just changing the case as well, this search is case sensitive.</dd>8098EOT8099}8100print"</dl>\n";8101 git_footer_html();8102}81038104sub git_shortlog {8105 git_log_generic('shortlog', \&git_shortlog_body,8106$hash,$hash_parent);8107}81088109## ......................................................................8110## feeds (RSS, Atom; OPML)81118112sub git_feed {8113my$format=shift||'atom';8114my$have_blame= gitweb_check_feature('blame');81158116# Atom: http://www.atomenabled.org/developers/syndication/8117# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ8118if($formatne'rss'&&$formatne'atom') {8119 die_error(400,"Unknown web feed format");8120}81218122# log/feed of current (HEAD) branch, log of given branch, history of file/directory8123my$head=$hash||'HEAD';8124my@commitlist= parse_commits($head,150,0,$file_name);81258126my%latest_commit;8127my%latest_date;8128my$content_type="application/$format+xml";8129if(defined$cgi->http('HTTP_ACCEPT') &&8130$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {8131# browser (feed reader) prefers text/xml8132$content_type='text/xml';8133}8134if(defined($commitlist[0])) {8135%latest_commit= %{$commitlist[0]};8136my$latest_epoch=$latest_commit{'committer_epoch'};8137 exit_if_unmodified_since($latest_epoch);8138%latest_date= parse_date($latest_epoch,$latest_commit{'committer_tz'});8139}8140print$cgi->header(8141-type =>$content_type,8142-charset =>'utf-8',8143%latest_date? (-last_modified =>$latest_date{'rfc2822'}) : (),8144-status =>'200 OK');81458146# Optimization: skip generating the body if client asks only8147# for Last-Modified date.8148return if($cgi->request_method()eq'HEAD');81498150# header variables8151my$title="$site_name-$project/$action";8152my$feed_type='log';8153if(defined$hash) {8154$title.=" - '$hash'";8155$feed_type='branch log';8156if(defined$file_name) {8157$title.=" ::$file_name";8158$feed_type='history';8159}8160}elsif(defined$file_name) {8161$title.=" -$file_name";8162$feed_type='history';8163}8164$title.="$feed_type";8165$title= esc_html($title);8166my$descr= git_get_project_description($project);8167if(defined$descr) {8168$descr= esc_html($descr);8169}else{8170$descr="$project".8171($formateq'rss'?'RSS':'Atom') .8172" feed";8173}8174my$owner= git_get_project_owner($project);8175$owner= esc_html($owner);81768177#header8178my$alt_url;8179if(defined$file_name) {8180$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);8181}elsif(defined$hash) {8182$alt_url= href(-full=>1, action=>"log", hash=>$hash);8183}else{8184$alt_url= href(-full=>1, action=>"summary");8185}8186print qq!<?xml version="1.0" encoding="utf-8"?>\n!;8187if($formateq'rss') {8188print<<XML;8189<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">8190<channel>8191XML8192print"<title>$title</title>\n".8193"<link>$alt_url</link>\n".8194"<description>$descr</description>\n".8195"<language>en</language>\n".8196# project owner is responsible for 'editorial' content8197"<managingEditor>$owner</managingEditor>\n";8198if(defined$logo||defined$favicon) {8199# prefer the logo to the favicon, since RSS8200# doesn't allow both8201my$img= esc_url($logo||$favicon);8202print"<image>\n".8203"<url>$img</url>\n".8204"<title>$title</title>\n".8205"<link>$alt_url</link>\n".8206"</image>\n";8207}8208if(%latest_date) {8209print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";8210print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";8211}8212print"<generator>gitweb v.$version/$git_version</generator>\n";8213}elsif($formateq'atom') {8214print<<XML;8215<feed xmlns="http://www.w3.org/2005/Atom">8216XML8217print"<title>$title</title>\n".8218"<subtitle>$descr</subtitle>\n".8219'<link rel="alternate" type="text/html" href="'.8220$alt_url.'" />'."\n".8221'<link rel="self" type="'.$content_type.'" href="'.8222$cgi->self_url() .'" />'."\n".8223"<id>". href(-full=>1) ."</id>\n".8224# use project owner for feed author8225"<author><name>$owner</name></author>\n";8226if(defined$favicon) {8227print"<icon>". esc_url($favicon) ."</icon>\n";8228}8229if(defined$logo) {8230# not twice as wide as tall: 72 x 27 pixels8231print"<logo>". esc_url($logo) ."</logo>\n";8232}8233if(!%latest_date) {8234# dummy date to keep the feed valid until commits trickle in:8235print"<updated>1970-01-01T00:00:00Z</updated>\n";8236}else{8237print"<updated>$latest_date{'iso-8601'}</updated>\n";8238}8239print"<generator version='$version/$git_version'>gitweb</generator>\n";8240}82418242# contents8243for(my$i=0;$i<=$#commitlist;$i++) {8244my%co= %{$commitlist[$i]};8245my$commit=$co{'id'};8246# we read 150, we always show 30 and the ones more recent than 48 hours8247if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {8248last;8249}8250my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});82518252# get list of changed files8253open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,8254$co{'parent'} ||"--root",8255$co{'id'},"--", (defined$file_name?$file_name: ())8256ornext;8257my@difftree=map{chomp;$_} <$fd>;8258close$fd8259ornext;82608261# print element (entry, item)8262my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);8263if($formateq'rss') {8264print"<item>\n".8265"<title>". esc_html($co{'title'}) ."</title>\n".8266"<author>". esc_html($co{'author'}) ."</author>\n".8267"<pubDate>$cd{'rfc2822'}</pubDate>\n".8268"<guid isPermaLink=\"true\">$co_url</guid>\n".8269"<link>$co_url</link>\n".8270"<description>". esc_html($co{'title'}) ."</description>\n".8271"<content:encoded>".8272"<![CDATA[\n";8273}elsif($formateq'atom') {8274print"<entry>\n".8275"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".8276"<updated>$cd{'iso-8601'}</updated>\n".8277"<author>\n".8278" <name>". esc_html($co{'author_name'}) ."</name>\n";8279if($co{'author_email'}) {8280print" <email>". esc_html($co{'author_email'}) ."</email>\n";8281}8282print"</author>\n".8283# use committer for contributor8284"<contributor>\n".8285" <name>". esc_html($co{'committer_name'}) ."</name>\n";8286if($co{'committer_email'}) {8287print" <email>". esc_html($co{'committer_email'}) ."</email>\n";8288}8289print"</contributor>\n".8290"<published>$cd{'iso-8601'}</published>\n".8291"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".8292"<id>$co_url</id>\n".8293"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".8294"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";8295}8296my$comment=$co{'comment'};8297print"<pre>\n";8298foreachmy$line(@$comment) {8299$line= esc_html($line);8300print"$line\n";8301}8302print"</pre><ul>\n";8303foreachmy$difftree_line(@difftree) {8304my%difftree= parse_difftree_raw_line($difftree_line);8305next if!$difftree{'from_id'};83068307my$file=$difftree{'file'} ||$difftree{'to_file'};83088309print"<li>".8310"[".8311$cgi->a({-href => href(-full=>1, action=>"blobdiff",8312 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},8313 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},8314 file_name=>$file, file_parent=>$difftree{'from_file'}),8315-title =>"diff"},'D');8316if($have_blame) {8317print$cgi->a({-href => href(-full=>1, action=>"blame",8318 file_name=>$file, hash_base=>$commit),8319-title =>"blame"},'B');8320}8321# if this is not a feed of a file history8322if(!defined$file_name||$file_namene$file) {8323print$cgi->a({-href => href(-full=>1, action=>"history",8324 file_name=>$file, hash=>$commit),8325-title =>"history"},'H');8326}8327$file= esc_path($file);8328print"] ".8329"$file</li>\n";8330}8331if($formateq'rss') {8332print"</ul>]]>\n".8333"</content:encoded>\n".8334"</item>\n";8335}elsif($formateq'atom') {8336print"</ul>\n</div>\n".8337"</content>\n".8338"</entry>\n";8339}8340}83418342# end of feed8343if($formateq'rss') {8344print"</channel>\n</rss>\n";8345}elsif($formateq'atom') {8346print"</feed>\n";8347}8348}83498350sub git_rss {8351 git_feed('rss');8352}83538354sub git_atom {8355 git_feed('atom');8356}83578358sub git_opml {8359my@list= git_get_projects_list($project_filter,$strict_export);8360if(!@list) {8361 die_error(404,"No projects found");8362}83638364print$cgi->header(8365-type =>'text/xml',8366-charset =>'utf-8',8367-content_disposition =>'inline; filename="opml.xml"');83688369my$title= esc_html($site_name);8370my$filter=" within subdirectory ";8371if(defined$project_filter) {8372$filter.= esc_html($project_filter);8373}else{8374$filter="";8375}8376print<<XML;8377<?xml version="1.0" encoding="utf-8"?>8378<opml version="1.0">8379<head>8380 <title>$titleOPML Export$filter</title>8381</head>8382<body>8383<outline text="git RSS feeds">8384XML83858386foreachmy$pr(@list) {8387my%proj=%$pr;8388my$head= git_get_head_hash($proj{'path'});8389if(!defined$head) {8390next;8391}8392$git_dir="$projectroot/$proj{'path'}";8393my%co= parse_commit($head);8394if(!%co) {8395next;8396}83978398my$path= esc_html(chop_str($proj{'path'},25,5));8399my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);8400my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);8401print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";8402}8403print<<XML;8404</outline>8405</body>8406</opml>8407XML8408}