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)/!!;37333734$ref_item{'name'} =$name;3735$ref_item{'id'} =$hash;3736$ref_item{'title'} =$title||'(no commit message)';3737$ref_item{'epoch'} =$epoch;3738if($epoch) {3739$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3740}else{3741$ref_item{'age'} ="unknown";3742}37433744push@headslist, \%ref_item;3745}3746close$fd;37473748returnwantarray?@headslist: \@headslist;3749}37503751sub git_get_tags_list {3752my$limit=shift;3753my@tagslist;37543755open my$fd,'-|', git_cmd(),'for-each-ref',3756($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3757'--format=%(objectname) %(objecttype) %(refname) '.3758'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3759'refs/tags'3760orreturn;3761while(my$line= <$fd>) {3762my%ref_item;37633764chomp$line;3765my($refinfo,$creatorinfo) =split(/\0/,$line);3766my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3767my($creator,$epoch,$tz) =3768($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3769$ref_item{'fullname'} =$name;3770$name=~s!^refs/tags/!!;37713772$ref_item{'type'} =$type;3773$ref_item{'id'} =$id;3774$ref_item{'name'} =$name;3775if($typeeq"tag") {3776$ref_item{'subject'} =$title;3777$ref_item{'reftype'} =$reftype;3778$ref_item{'refid'} =$refid;3779}else{3780$ref_item{'reftype'} =$type;3781$ref_item{'refid'} =$id;3782}37833784if($typeeq"tag"||$typeeq"commit") {3785$ref_item{'epoch'} =$epoch;3786if($epoch) {3787$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3788}else{3789$ref_item{'age'} ="unknown";3790}3791}37923793push@tagslist, \%ref_item;3794}3795close$fd;37963797returnwantarray?@tagslist: \@tagslist;3798}37993800## ----------------------------------------------------------------------3801## filesystem-related functions38023803sub get_file_owner {3804my$path=shift;38053806my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3807my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3808if(!defined$gcos) {3809returnundef;3810}3811my$owner=$gcos;3812$owner=~s/[,;].*$//;3813return to_utf8($owner);3814}38153816# assume that file exists3817sub insert_file {3818my$filename=shift;38193820open my$fd,'<',$filename;3821print map{ to_utf8($_) } <$fd>;3822close$fd;3823}38243825## ......................................................................3826## mimetype related functions38273828sub mimetype_guess_file {3829my$filename=shift;3830my$mimemap=shift;3831-r $mimemaporreturnundef;38323833my%mimemap;3834open(my$mh,'<',$mimemap)orreturnundef;3835while(<$mh>) {3836next ifm/^#/;# skip comments3837my($mimetype,@exts) =split(/\s+/);3838foreachmy$ext(@exts) {3839$mimemap{$ext} =$mimetype;3840}3841}3842close($mh);38433844$filename=~/\.([^.]*)$/;3845return$mimemap{$1};3846}38473848sub mimetype_guess {3849my$filename=shift;3850my$mime;3851$filename=~/\./orreturnundef;38523853if($mimetypes_file) {3854my$file=$mimetypes_file;3855if($file!~m!^/!) {# if it is relative path3856# it is relative to project3857$file="$projectroot/$project/$file";3858}3859$mime= mimetype_guess_file($filename,$file);3860}3861$mime||= mimetype_guess_file($filename,'/etc/mime.types');3862return$mime;3863}38643865sub blob_mimetype {3866my$fd=shift;3867my$filename=shift;38683869if($filename) {3870my$mime= mimetype_guess($filename);3871$mimeandreturn$mime;3872}38733874# just in case3875return$default_blob_plain_mimetypeunless$fd;38763877if(-T $fd) {3878return'text/plain';3879}elsif(!$filename) {3880return'application/octet-stream';3881}elsif($filename=~m/\.png$/i) {3882return'image/png';3883}elsif($filename=~m/\.gif$/i) {3884return'image/gif';3885}elsif($filename=~m/\.jpe?g$/i) {3886return'image/jpeg';3887}else{3888return'application/octet-stream';3889}3890}38913892sub blob_contenttype {3893my($fd,$file_name,$type) =@_;38943895$type||= blob_mimetype($fd,$file_name);3896if($typeeq'text/plain'&&defined$default_text_plain_charset) {3897$type.="; charset=$default_text_plain_charset";3898}38993900return$type;3901}39023903# guess file syntax for syntax highlighting; return undef if no highlighting3904# the name of syntax can (in the future) depend on syntax highlighter used3905sub guess_file_syntax {3906my($highlight,$mimetype,$file_name) =@_;3907returnundefunless($highlight&&defined$file_name);3908my$basename= basename($file_name,'.in');3909return$highlight_basename{$basename}3910ifexists$highlight_basename{$basename};39113912$basename=~/\.([^.]*)$/;3913my$ext=$1orreturnundef;3914return$highlight_ext{$ext}3915ifexists$highlight_ext{$ext};39163917returnundef;3918}39193920# run highlighter and return FD of its output,3921# or return original FD if no highlighting3922sub run_highlighter {3923my($fd,$highlight,$syntax) =@_;3924return$fdunless($highlight&&defined$syntax);39253926close$fd;3927open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3928 quote_command($highlight_bin).3929" --replace-tabs=8 --fragment --syntax$syntax|"3930or die_error(500,"Couldn't open file or run syntax highlighter");3931return$fd;3932}39333934## ======================================================================3935## functions printing HTML: header, footer, error page39363937sub get_page_title {3938my$title= to_utf8($site_name);39393940unless(defined$project) {3941if(defined$project_filter) {3942$title.=" - projects in '". esc_path($project_filter) ."'";3943}3944return$title;3945}3946$title.=" - ". to_utf8($project);39473948return$titleunless(defined$action);3949$title.="/$action";# $action is US-ASCII (7bit ASCII)39503951return$titleunless(defined$file_name);3952$title.=" - ". esc_path($file_name);3953if($actioneq"tree"&&$file_name!~ m|/$|) {3954$title.="/";3955}39563957return$title;3958}39593960sub get_content_type_html {3961# require explicit support from the UA if we are to send the page as3962# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3963# we have to do this because MSIE sometimes globs '*/*', pretending to3964# support xhtml+xml but choking when it gets what it asked for.3965if(defined$cgi->http('HTTP_ACCEPT') &&3966$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3967$cgi->Accept('application/xhtml+xml') !=0) {3968return'application/xhtml+xml';3969}else{3970return'text/html';3971}3972}39733974sub print_feed_meta {3975if(defined$project) {3976my%href_params= get_feed_info();3977if(!exists$href_params{'-title'}) {3978$href_params{'-title'} ='log';3979}39803981foreachmy$format(qw(RSS Atom)) {3982my$type=lc($format);3983my%link_attr= (3984'-rel'=>'alternate',3985'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3986'-type'=>"application/$type+xml"3987);39883989$href_params{'extra_options'} =undef;3990$href_params{'action'} =$type;3991$link_attr{'-href'} = href(%href_params);3992print"<link ".3993"rel=\"$link_attr{'-rel'}\"".3994"title=\"$link_attr{'-title'}\"".3995"href=\"$link_attr{'-href'}\"".3996"type=\"$link_attr{'-type'}\"".3997"/>\n";39983999$href_params{'extra_options'} ='--no-merges';4000$link_attr{'-href'} = href(%href_params);4001$link_attr{'-title'} .=' (no merges)';4002print"<link ".4003"rel=\"$link_attr{'-rel'}\"".4004"title=\"$link_attr{'-title'}\"".4005"href=\"$link_attr{'-href'}\"".4006"type=\"$link_attr{'-type'}\"".4007"/>\n";4008}40094010}else{4011printf('<link rel="alternate" title="%sprojects list" '.4012'href="%s" type="text/plain; charset=utf-8" />'."\n",4013 esc_attr($site_name), href(project=>undef, action=>"project_index"));4014printf('<link rel="alternate" title="%sprojects feeds" '.4015'href="%s" type="text/x-opml" />'."\n",4016 esc_attr($site_name), href(project=>undef, action=>"opml"));4017}4018}40194020sub print_header_links {4021my$status=shift;40224023# print out each stylesheet that exist, providing backwards capability4024# for those people who defined $stylesheet in a config file4025if(defined$stylesheet) {4026print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";4027}else{4028foreachmy$stylesheet(@stylesheets) {4029next unless$stylesheet;4030print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";4031}4032}4033 print_feed_meta()4034if($statuseq'200 OK');4035if(defined$favicon) {4036printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);4037}4038}40394040sub print_nav_breadcrumbs_path {4041my$dirprefix=undef;4042while(my$part=shift) {4043$dirprefix.="/"ifdefined$dirprefix;4044$dirprefix.=$part;4045print$cgi->a({-href => href(project =>undef,4046 project_filter =>$dirprefix,4047 action =>"project_list")},4048 esc_html($part)) ." / ";4049}4050}40514052sub print_nav_breadcrumbs {4053my%opts=@_;40544055formy$crumb(@extra_breadcrumbs, [$home_link_str=>$home_link]) {4056print$cgi->a({-href => esc_url($crumb->[1])},$crumb->[0]) ." / ";4057}4058if(defined$project) {4059my@dirname=split'/',$project;4060my$projectbasename=pop@dirname;4061 print_nav_breadcrumbs_path(@dirname);4062print$cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));4063if(defined$action) {4064my$action_print=$action;4065if(defined$opts{-action_extra}) {4066$action_print=$cgi->a({-href => href(action=>$action)},4067$action);4068}4069print" /$action_print";4070}4071if(defined$opts{-action_extra}) {4072print" /$opts{-action_extra}";4073}4074print"\n";4075}elsif(defined$project_filter) {4076 print_nav_breadcrumbs_path(split'/',$project_filter);4077}4078}40794080sub print_search_form {4081if(!defined$searchtext) {4082$searchtext="";4083}4084my$search_hash;4085if(defined$hash_base) {4086$search_hash=$hash_base;4087}elsif(defined$hash) {4088$search_hash=$hash;4089}else{4090$search_hash="HEAD";4091}4092my$action=$my_uri;4093my$use_pathinfo= gitweb_check_feature('pathinfo');4094if($use_pathinfo) {4095$action.="/".esc_url($project);4096}4097print$cgi->startform(-method=>"get", -action =>$action) .4098"<div class=\"search\">\n".4099(!$use_pathinfo&&4100$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .4101$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".4102$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".4103$cgi->popup_menu(-name =>'st', -default=>'commit',4104-values=> ['commit','grep','author','committer','pickaxe']) .4105" ".$cgi->a({-href => href(action=>"search_help"),4106-title =>"search help"},"?") ." search:\n",4107$cgi->textfield(-name =>"s", -value =>$searchtext, -override =>1) ."\n".4108"<span title=\"Extended regular expression\">".4109$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',4110-checked =>$search_use_regexp) .4111"</span>".4112"</div>".4113$cgi->end_form() ."\n";4114}41154116sub git_header_html {4117my$status=shift||"200 OK";4118my$expires=shift;4119my%opts=@_;41204121my$title= get_page_title();4122my$content_type= get_content_type_html();4123print$cgi->header(-type=>$content_type, -charset =>'utf-8',4124-status=>$status, -expires =>$expires)4125unless($opts{'-no_http_header'});4126my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';4127print<<EOF;4128<?xml version="1.0" encoding="utf-8"?>4129<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4130<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">4131<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->4132<!-- git core binaries version$git_version-->4133<head>4134<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>4135<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>4136<meta name="robots" content="index, nofollow"/>4137<title>$title</title>4138EOF4139# the stylesheet, favicon etc urls won't work correctly with path_info4140# unless we set the appropriate base URL4141if($ENV{'PATH_INFO'}) {4142print"<base href=\"".esc_url($base_url)."\"/>\n";4143}4144 print_header_links($status);41454146if(defined$site_html_head_string) {4147print to_utf8($site_html_head_string);4148}41494150print"</head>\n".4151"<body>\n";41524153if(defined$site_header&& -f $site_header) {4154 insert_file($site_header);4155}41564157print"<div class=\"page_header\">\n";4158if(defined$logo) {4159print$cgi->a({-href => esc_url($logo_url),4160-title =>$logo_label},4161$cgi->img({-src => esc_url($logo),4162-width =>72, -height =>27,4163-alt =>"git",4164-class=>"logo"}));4165}4166 print_nav_breadcrumbs(%opts);4167print"</div>\n";41684169my$have_search= gitweb_check_feature('search');4170if(defined$project&&$have_search) {4171 print_search_form();4172}4173}41744175sub git_footer_html {4176my$feed_class='rss_logo';41774178print"<div class=\"page_footer\">\n";4179if(defined$project) {4180my$descr= git_get_project_description($project);4181if(defined$descr) {4182print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";4183}41844185my%href_params= get_feed_info();4186if(!%href_params) {4187$feed_class.=' generic';4188}4189$href_params{'-title'} ||='log';41904191foreachmy$format(qw(RSS Atom)) {4192$href_params{'action'} =lc($format);4193print$cgi->a({-href => href(%href_params),4194-title =>"$href_params{'-title'}$formatfeed",4195-class=>$feed_class},$format)."\n";4196}41974198}else{4199print$cgi->a({-href => href(project=>undef, action=>"opml",4200 project_filter =>$project_filter),4201-class=>$feed_class},"OPML") ." ";4202print$cgi->a({-href => href(project=>undef, action=>"project_index",4203 project_filter =>$project_filter),4204-class=>$feed_class},"TXT") ."\n";4205}4206print"</div>\n";# class="page_footer"42074208if(defined$t0&& gitweb_check_feature('timed')) {4209print"<div id=\"generating_info\">\n";4210print'This page took '.4211'<span id="generating_time" class="time_span">'.4212 tv_interval($t0, [ gettimeofday() ]).4213' seconds </span>'.4214' and '.4215'<span id="generating_cmd">'.4216$number_of_git_cmds.4217'</span> git commands '.4218" to generate.\n";4219print"</div>\n";# class="page_footer"4220}42214222if(defined$site_footer&& -f $site_footer) {4223 insert_file($site_footer);4224}42254226print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;4227if(defined$action&&4228$actioneq'blame_incremental') {4229print qq!<script type="text/javascript">\n!.4230 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.4231 qq!"!. href() .qq!");\n!.4232 qq!</script>\n!;4233}else{4234my($jstimezone,$tz_cookie,$datetime_class) =4235 gitweb_get_feature('javascript-timezone');42364237print qq!<script type="text/javascript">\n!.4238 qq!window.onload = function () {\n!;4239if(gitweb_check_feature('javascript-actions')) {4240print qq! fixLinks();\n!;4241}4242if($jstimezone&&$tz_cookie&&$datetime_class) {4243print qq! var tz_cookie = { name:'$tz_cookie', expires:14, path:'/'};\n!.# in days4244 qq! onloadTZSetup('$jstimezone', tz_cookie,'$datetime_class');\n!;4245}4246print qq!};\n!.4247 qq!</script>\n!;4248}42494250print"</body>\n".4251"</html>";4252}42534254# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])4255# Example: die_error(404, 'Hash not found')4256# By convention, use the following status codes (as defined in RFC 2616):4257# 400: Invalid or missing CGI parameters, or4258# requested object exists but has wrong type.4259# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on4260# this server or project.4261# 404: Requested object/revision/project doesn't exist.4262# 500: The server isn't configured properly, or4263# an internal error occurred (e.g. failed assertions caused by bugs), or4264# an unknown error occurred (e.g. the git binary died unexpectedly).4265# 503: The server is currently unavailable (because it is overloaded,4266# or down for maintenance). Generally, this is a temporary state.4267sub die_error {4268my$status=shift||500;4269my$error= esc_html(shift) ||"Internal Server Error";4270my$extra=shift;4271my%opts=@_;42724273my%http_responses= (4274400=>'400 Bad Request',4275403=>'403 Forbidden',4276404=>'404 Not Found',4277500=>'500 Internal Server Error',4278503=>'503 Service Unavailable',4279);4280 git_header_html($http_responses{$status},undef,%opts);4281print<<EOF;4282<div class="page_body">4283<br /><br />4284$status-$error4285<br />4286EOF4287if(defined$extra) {4288print"<hr />\n".4289"$extra\n";4290}4291print"</div>\n";42924293 git_footer_html();4294goto DONE_GITWEB4295unless($opts{'-error_handler'});4296}42974298## ----------------------------------------------------------------------4299## functions printing or outputting HTML: navigation43004301sub git_print_page_nav {4302my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;4303$extra=''if!defined$extra;# pager or formats43044305my@navs=qw(summary shortlog log commit commitdiff tree);4306if($suppress) {4307@navs=grep{$_ne$suppress}@navs;4308}43094310my%arg=map{$_=> {action=>$_} }@navs;4311if(defined$head) {4312for(qw(commit commitdiff)) {4313$arg{$_}{'hash'} =$head;4314}4315if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {4316for(qw(shortlog log)) {4317$arg{$_}{'hash'} =$head;4318}4319}4320}43214322$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;4323$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;43244325my@actions= gitweb_get_feature('actions');4326my%repl= (4327'%'=>'%',4328'n'=>$project,# project name4329'f'=>$git_dir,# project path within filesystem4330'h'=>$treehead||'',# current hash ('h' parameter)4331'b'=>$treebase||'',# hash base ('hb' parameter)4332);4333while(@actions) {4334my($label,$link,$pos) =splice(@actions,0,3);4335# insert4336@navs=map{$_eq$pos? ($_,$label) :$_}@navs;4337# munch munch4338$link=~s/%([%nfhb])/$repl{$1}/g;4339$arg{$label}{'_href'} =$link;4340}43414342print"<div class=\"page_nav\">\n".4343(join" | ",4344map{$_eq$current?4345$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4346}@navs);4347print"<br/>\n$extra<br/>\n".4348"</div>\n";4349}43504351# returns a submenu for the nagivation of the refs views (tags, heads,4352# remotes) with the current view disabled and the remotes view only4353# available if the feature is enabled4354sub format_ref_views {4355my($current) =@_;4356my@ref_views=qw{tags heads};4357push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4358returnjoin" | ",map{4359$_eq$current?$_:4360$cgi->a({-href => href(action=>$_)},$_)4361}@ref_views4362}43634364sub format_paging_nav {4365my($action,$page,$has_next_link) =@_;4366my$paging_nav;436743684369if($page>0) {4370$paging_nav.=4371$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4372" ⋅ ".4373$cgi->a({-href => href(-replay=>1, page=>$page-1),4374-accesskey =>"p", -title =>"Alt-p"},"prev");4375}else{4376$paging_nav.="first ⋅ prev";4377}43784379if($has_next_link) {4380$paging_nav.=" ⋅ ".4381$cgi->a({-href => href(-replay=>1, page=>$page+1),4382-accesskey =>"n", -title =>"Alt-n"},"next");4383}else{4384$paging_nav.=" ⋅ next";4385}43864387return$paging_nav;4388}43894390## ......................................................................4391## functions printing or outputting HTML: div43924393sub git_print_header_div {4394my($action,$title,$hash,$hash_base) =@_;4395my%args= ();43964397$args{'action'} =$action;4398$args{'hash'} =$hashif$hash;4399$args{'hash_base'} =$hash_baseif$hash_base;44004401print"<div class=\"header\">\n".4402$cgi->a({-href => href(%args), -class=>"title"},4403$title?$title:$action) .4404"\n</div>\n";4405}44064407sub format_repo_url {4408my($name,$url) =@_;4409return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4410}44114412# Group output by placing it in a DIV element and adding a header.4413# Options for start_div() can be provided by passing a hash reference as the4414# first parameter to the function.4415# Options to git_print_header_div() can be provided by passing an array4416# reference. This must follow the options to start_div if they are present.4417# The content can be a scalar, which is output as-is, a scalar reference, which4418# is output after html escaping, an IO handle passed either as *handle or4419# *handle{IO}, or a function reference. In the latter case all following4420# parameters will be taken as argument to the content function call.4421sub git_print_section {4422my($div_args,$header_args,$content);4423my$arg=shift;4424if(ref($arg)eq'HASH') {4425$div_args=$arg;4426$arg=shift;4427}4428if(ref($arg)eq'ARRAY') {4429$header_args=$arg;4430$arg=shift;4431}4432$content=$arg;44334434print$cgi->start_div($div_args);4435 git_print_header_div(@$header_args);44364437if(ref($content)eq'CODE') {4438$content->(@_);4439}elsif(ref($content)eq'SCALAR') {4440print esc_html($$content);4441}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4442print<$content>;4443}elsif(!ref($content) &&defined($content)) {4444print$content;4445}44464447print$cgi->end_div;4448}44494450sub format_timestamp_html {4451my$date=shift;4452my$strtime=$date->{'rfc2822'};44534454my(undef,undef,$datetime_class) =4455 gitweb_get_feature('javascript-timezone');4456if($datetime_class) {4457$strtime= qq!<span class="$datetime_class">$strtime</span>!;4458}44594460my$localtime_format='(%02d:%02d%s)';4461if($date->{'hour_local'} <6) {4462$localtime_format='(<span class="atnight">%02d:%02d</span>%s)';4463}4464$strtime.=' '.4465sprintf($localtime_format,4466$date->{'hour_local'},$date->{'minute_local'},$date->{'tz_local'});44674468return$strtime;4469}44704471# Outputs the author name and date in long form4472sub git_print_authorship {4473my$co=shift;4474my%opts=@_;4475my$tag=$opts{-tag} ||'div';4476my$author=$co->{'author_name'};44774478my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4479print"<$tagclass=\"author_date\">".4480 format_search_author($author,"author", esc_html($author)) .4481" [".format_timestamp_html(\%ad)."]".4482 git_get_avatar($co->{'author_email'}, -pad_before =>1) .4483"</$tag>\n";4484}44854486# Outputs table rows containing the full author or committer information,4487# in the format expected for 'commit' view (& similar).4488# Parameters are a commit hash reference, followed by the list of people4489# to output information for. If the list is empty it defaults to both4490# author and committer.4491sub git_print_authorship_rows {4492my$co=shift;4493# too bad we can't use @people = @_ || ('author', 'committer')4494my@people=@_;4495@people= ('author','committer')unless@people;4496foreachmy$who(@people) {4497my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4498print"<tr><td>$who</td><td>".4499 format_search_author($co->{"${who}_name"},$who,4500 esc_html($co->{"${who}_name"})) ." ".4501 format_search_author($co->{"${who}_email"},$who,4502 esc_html("<".$co->{"${who}_email"} .">")) .4503"</td><td rowspan=\"2\">".4504 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4505"</td></tr>\n".4506"<tr>".4507"<td></td><td>".4508 format_timestamp_html(\%wd) .4509"</td>".4510"</tr>\n";4511}4512}45134514sub git_print_page_path {4515my$name=shift;4516my$type=shift;4517my$hb=shift;451845194520print"<div class=\"page_path\">";4521print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4522-title =>'tree root'}, to_utf8("[$project]"));4523print" / ";4524if(defined$name) {4525my@dirname=split'/',$name;4526my$basename=pop@dirname;4527my$fullname='';45284529foreachmy$dir(@dirname) {4530$fullname.= ($fullname?'/':'') .$dir;4531print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4532 hash_base=>$hb),4533-title =>$fullname}, esc_path($dir));4534print" / ";4535}4536if(defined$type&&$typeeq'blob') {4537print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4538 hash_base=>$hb),4539-title =>$name}, esc_path($basename));4540}elsif(defined$type&&$typeeq'tree') {4541print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4542 hash_base=>$hb),4543-title =>$name}, esc_path($basename));4544print" / ";4545}else{4546print esc_path($basename);4547}4548}4549print"<br/></div>\n";4550}45514552sub git_print_log {4553my$log=shift;4554my%opts=@_;45554556if($opts{'-remove_title'}) {4557# remove title, i.e. first line of log4558shift@$log;4559}4560# remove leading empty lines4561while(defined$log->[0] &&$log->[0]eq"") {4562shift@$log;4563}45644565# print log4566my$skip_blank_line=0;4567foreachmy$line(@$log) {4568if($line=~m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {4569if(!$opts{'-remove_signoff'}) {4570print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4571$skip_blank_line=1;4572}4573next;4574}45754576if($line=~ m,\s*([a-z]*link): (https?://\S+),i) {4577if(!$opts{'-remove_signoff'}) {4578print"<span class=\"signoff\">". esc_html($1) .": ".4579"<a href=\"". esc_html($2) ."\">". esc_html($2) ."</a>".4580"</span><br/>\n";4581$skip_blank_line=1;4582}4583next;4584}45854586# print only one empty line4587# do not print empty line after signoff4588if($lineeq"") {4589next if($skip_blank_line);4590$skip_blank_line=1;4591}else{4592$skip_blank_line=0;4593}45944595print format_log_line_html($line) ."<br/>\n";4596}45974598if($opts{'-final_empty_line'}) {4599# end with single empty line4600print"<br/>\n"unless$skip_blank_line;4601}4602}46034604# return link target (what link points to)4605sub git_get_link_target {4606my$hash=shift;4607my$link_target;46084609# read link4610open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4611orreturn;4612{4613local$/=undef;4614$link_target= <$fd>;4615}4616close$fd4617orreturn;46184619return$link_target;4620}46214622# given link target, and the directory (basedir) the link is in,4623# return target of link relative to top directory (top tree);4624# return undef if it is not possible (including absolute links).4625sub normalize_link_target {4626my($link_target,$basedir) =@_;46274628# absolute symlinks (beginning with '/') cannot be normalized4629return if(substr($link_target,0,1)eq'/');46304631# normalize link target to path from top (root) tree (dir)4632my$path;4633if($basedir) {4634$path=$basedir.'/'.$link_target;4635}else{4636# we are in top (root) tree (dir)4637$path=$link_target;4638}46394640# remove //, /./, and /../4641my@path_parts;4642foreachmy$part(split('/',$path)) {4643# discard '.' and ''4644next if(!$part||$parteq'.');4645# handle '..'4646if($parteq'..') {4647if(@path_parts) {4648pop@path_parts;4649}else{4650# link leads outside repository (outside top dir)4651return;4652}4653}else{4654push@path_parts,$part;4655}4656}4657$path=join('/',@path_parts);46584659return$path;4660}46614662# print tree entry (row of git_tree), but without encompassing <tr> element4663sub git_print_tree_entry {4664my($t,$basedir,$hash_base,$have_blame) =@_;46654666my%base_key= ();4667$base_key{'hash_base'} =$hash_baseifdefined$hash_base;46684669# The format of a table row is: mode list link. Where mode is4670# the mode of the entry, list is the name of the entry, an href,4671# and link is the action links of the entry.46724673print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4674if(exists$t->{'size'}) {4675print"<td class=\"size\">$t->{'size'}</td>\n";4676}4677if($t->{'type'}eq"blob") {4678print"<td class=\"list\">".4679$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4680 file_name=>"$basedir$t->{'name'}",%base_key),4681-class=>"list"}, esc_path($t->{'name'}));4682if(S_ISLNK(oct$t->{'mode'})) {4683my$link_target= git_get_link_target($t->{'hash'});4684if($link_target) {4685my$norm_target= normalize_link_target($link_target,$basedir);4686if(defined$norm_target) {4687print" -> ".4688$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4689 file_name=>$norm_target),4690-title =>$norm_target}, esc_path($link_target));4691}else{4692print" -> ". esc_path($link_target);4693}4694}4695}4696print"</td>\n";4697print"<td class=\"link\">";4698print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4699 file_name=>"$basedir$t->{'name'}",%base_key)},4700"blob");4701if($have_blame) {4702print" | ".4703$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4704 file_name=>"$basedir$t->{'name'}",%base_key)},4705"blame");4706}4707if(defined$hash_base) {4708print" | ".4709$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4710 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4711"history");4712}4713print" | ".4714$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4715 file_name=>"$basedir$t->{'name'}")},4716"raw");4717print"</td>\n";47184719}elsif($t->{'type'}eq"tree") {4720print"<td class=\"list\">";4721print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4722 file_name=>"$basedir$t->{'name'}",4723%base_key)},4724 esc_path($t->{'name'}));4725print"</td>\n";4726print"<td class=\"link\">";4727print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4728 file_name=>"$basedir$t->{'name'}",4729%base_key)},4730"tree");4731if(defined$hash_base) {4732print" | ".4733$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4734 file_name=>"$basedir$t->{'name'}")},4735"history");4736}4737print"</td>\n";4738}else{4739# unknown object: we can only present history for it4740# (this includes 'commit' object, i.e. submodule support)4741print"<td class=\"list\">".4742 esc_path($t->{'name'}) .4743"</td>\n";4744print"<td class=\"link\">";4745if(defined$hash_base) {4746print$cgi->a({-href => href(action=>"history",4747 hash_base=>$hash_base,4748 file_name=>"$basedir$t->{'name'}")},4749"history");4750}4751print"</td>\n";4752}4753}47544755## ......................................................................4756## functions printing large fragments of HTML47574758# get pre-image filenames for merge (combined) diff4759sub fill_from_file_info {4760my($diff,@parents) =@_;47614762$diff->{'from_file'} = [ ];4763$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4764for(my$i=0;$i<$diff->{'nparents'};$i++) {4765if($diff->{'status'}[$i]eq'R'||4766$diff->{'status'}[$i]eq'C') {4767$diff->{'from_file'}[$i] =4768 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4769}4770}47714772return$diff;4773}47744775# is current raw difftree line of file deletion4776sub is_deleted {4777my$diffinfo=shift;47784779return$diffinfo->{'to_id'}eq('0' x 40);4780}47814782# does patch correspond to [previous] difftree raw line4783# $diffinfo - hashref of parsed raw diff format4784# $patchinfo - hashref of parsed patch diff format4785# (the same keys as in $diffinfo)4786sub is_patch_split {4787my($diffinfo,$patchinfo) =@_;47884789returndefined$diffinfo&&defined$patchinfo4790&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4791}479247934794sub git_difftree_body {4795my($difftree,$hash,@parents) =@_;4796my($parent) =$parents[0];4797my$have_blame= gitweb_check_feature('blame');4798print"<div class=\"list_head\">\n";4799if($#{$difftree} >10) {4800print(($#{$difftree} +1) ." files changed:\n");4801}4802print"</div>\n";48034804print"<table class=\"".4805(@parents>1?"combined ":"") .4806"diff_tree\">\n";48074808# header only for combined diff in 'commitdiff' view4809my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4810if($has_header) {4811# table header4812print"<thead><tr>\n".4813"<th></th><th></th>\n";# filename, patchN link4814for(my$i=0;$i<@parents;$i++) {4815my$par=$parents[$i];4816print"<th>".4817$cgi->a({-href => href(action=>"commitdiff",4818 hash=>$hash, hash_parent=>$par),4819-title =>'commitdiff to parent number '.4820($i+1) .': '.substr($par,0,7)},4821$i+1) .4822" </th>\n";4823}4824print"</tr></thead>\n<tbody>\n";4825}48264827my$alternate=1;4828my$patchno=0;4829foreachmy$line(@{$difftree}) {4830my$diff= parsed_difftree_line($line);48314832if($alternate) {4833print"<tr class=\"dark\">\n";4834}else{4835print"<tr class=\"light\">\n";4836}4837$alternate^=1;48384839if(exists$diff->{'nparents'}) {# combined diff48404841 fill_from_file_info($diff,@parents)4842unlessexists$diff->{'from_file'};48434844if(!is_deleted($diff)) {4845# file exists in the result (child) commit4846print"<td>".4847$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4848 file_name=>$diff->{'to_file'},4849 hash_base=>$hash),4850-class=>"list"}, esc_path($diff->{'to_file'})) .4851"</td>\n";4852}else{4853print"<td>".4854 esc_path($diff->{'to_file'}) .4855"</td>\n";4856}48574858if($actioneq'commitdiff') {4859# link to patch4860$patchno++;4861print"<td class=\"link\">".4862$cgi->a({-href => href(-anchor=>"patch$patchno")},4863"patch") .4864" | ".4865"</td>\n";4866}48674868my$has_history=0;4869my$not_deleted=0;4870for(my$i=0;$i<$diff->{'nparents'};$i++) {4871my$hash_parent=$parents[$i];4872my$from_hash=$diff->{'from_id'}[$i];4873my$from_path=$diff->{'from_file'}[$i];4874my$status=$diff->{'status'}[$i];48754876$has_history||= ($statusne'A');4877$not_deleted||= ($statusne'D');48784879if($statuseq'A') {4880print"<td class=\"link\"align=\"right\"> | </td>\n";4881}elsif($statuseq'D') {4882print"<td class=\"link\">".4883$cgi->a({-href => href(action=>"blob",4884 hash_base=>$hash,4885 hash=>$from_hash,4886 file_name=>$from_path)},4887"blob". ($i+1)) .4888" | </td>\n";4889}else{4890if($diff->{'to_id'}eq$from_hash) {4891print"<td class=\"link nochange\">";4892}else{4893print"<td class=\"link\">";4894}4895print$cgi->a({-href => href(action=>"blobdiff",4896 hash=>$diff->{'to_id'},4897 hash_parent=>$from_hash,4898 hash_base=>$hash,4899 hash_parent_base=>$hash_parent,4900 file_name=>$diff->{'to_file'},4901 file_parent=>$from_path)},4902"diff". ($i+1)) .4903" | </td>\n";4904}4905}49064907print"<td class=\"link\">";4908if($not_deleted) {4909print$cgi->a({-href => href(action=>"blob",4910 hash=>$diff->{'to_id'},4911 file_name=>$diff->{'to_file'},4912 hash_base=>$hash)},4913"blob");4914print" | "if($has_history);4915}4916if($has_history) {4917print$cgi->a({-href => href(action=>"history",4918 file_name=>$diff->{'to_file'},4919 hash_base=>$hash)},4920"history");4921}4922print"</td>\n";49234924print"</tr>\n";4925next;# instead of 'else' clause, to avoid extra indent4926}4927# else ordinary diff49284929my($to_mode_oct,$to_mode_str,$to_file_type);4930my($from_mode_oct,$from_mode_str,$from_file_type);4931if($diff->{'to_mode'}ne('0' x 6)) {4932$to_mode_oct=oct$diff->{'to_mode'};4933if(S_ISREG($to_mode_oct)) {# only for regular file4934$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4935}4936$to_file_type= file_type($diff->{'to_mode'});4937}4938if($diff->{'from_mode'}ne('0' x 6)) {4939$from_mode_oct=oct$diff->{'from_mode'};4940if(S_ISREG($from_mode_oct)) {# only for regular file4941$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4942}4943$from_file_type= file_type($diff->{'from_mode'});4944}49454946if($diff->{'status'}eq"A") {# created4947my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4948$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4949$mode_chng.="]</span>";4950print"<td>";4951print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4952 hash_base=>$hash, file_name=>$diff->{'file'}),4953-class=>"list"}, esc_path($diff->{'file'}));4954print"</td>\n";4955print"<td>$mode_chng</td>\n";4956print"<td class=\"link\">";4957if($actioneq'commitdiff') {4958# link to patch4959$patchno++;4960print$cgi->a({-href => href(-anchor=>"patch$patchno")},4961"patch") .4962" | ";4963}4964print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4965 hash_base=>$hash, file_name=>$diff->{'file'})},4966"blob");4967print"</td>\n";49684969}elsif($diff->{'status'}eq"D") {# deleted4970my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4971print"<td>";4972print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4973 hash_base=>$parent, file_name=>$diff->{'file'}),4974-class=>"list"}, esc_path($diff->{'file'}));4975print"</td>\n";4976print"<td>$mode_chng</td>\n";4977print"<td class=\"link\">";4978if($actioneq'commitdiff') {4979# link to patch4980$patchno++;4981print$cgi->a({-href => href(-anchor=>"patch$patchno")},4982"patch") .4983" | ";4984}4985print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4986 hash_base=>$parent, file_name=>$diff->{'file'})},4987"blob") ." | ";4988if($have_blame) {4989print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4990 file_name=>$diff->{'file'})},4991"blame") ." | ";4992}4993print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4994 file_name=>$diff->{'file'})},4995"history");4996print"</td>\n";49974998}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4999my$mode_chnge="";5000if($diff->{'from_mode'} !=$diff->{'to_mode'}) {5001$mode_chnge="<span class=\"file_status mode_chnge\">[changed";5002if($from_file_typene$to_file_type) {5003$mode_chnge.=" from$from_file_typeto$to_file_type";5004}5005if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {5006if($from_mode_str&&$to_mode_str) {5007$mode_chnge.=" mode:$from_mode_str->$to_mode_str";5008}elsif($to_mode_str) {5009$mode_chnge.=" mode:$to_mode_str";5010}5011}5012$mode_chnge.="]</span>\n";5013}5014print"<td>";5015print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},5016 hash_base=>$hash, file_name=>$diff->{'file'}),5017-class=>"list"}, esc_path($diff->{'file'}));5018print"</td>\n";5019print"<td>$mode_chnge</td>\n";5020print"<td class=\"link\">";5021if($actioneq'commitdiff') {5022# link to patch5023$patchno++;5024print$cgi->a({-href => href(-anchor=>"patch$patchno")},5025"patch") .5026" | ";5027}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {5028# "commit" view and modified file (not onlu mode changed)5029print$cgi->a({-href => href(action=>"blobdiff",5030 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},5031 hash_base=>$hash, hash_parent_base=>$parent,5032 file_name=>$diff->{'file'})},5033"diff") .5034" | ";5035}5036print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},5037 hash_base=>$hash, file_name=>$diff->{'file'})},5038"blob") ." | ";5039if($have_blame) {5040print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,5041 file_name=>$diff->{'file'})},5042"blame") ." | ";5043}5044print$cgi->a({-href => href(action=>"history", hash_base=>$hash,5045 file_name=>$diff->{'file'})},5046"history");5047print"</td>\n";50485049}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied5050my%status_name= ('R'=>'moved','C'=>'copied');5051my$nstatus=$status_name{$diff->{'status'}};5052my$mode_chng="";5053if($diff->{'from_mode'} !=$diff->{'to_mode'}) {5054# mode also for directories, so we cannot use $to_mode_str5055$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);5056}5057print"<td>".5058$cgi->a({-href => href(action=>"blob", hash_base=>$hash,5059 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),5060-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".5061"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".5062$cgi->a({-href => href(action=>"blob", hash_base=>$parent,5063 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),5064-class=>"list"}, esc_path($diff->{'from_file'})) .5065" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".5066"<td class=\"link\">";5067if($actioneq'commitdiff') {5068# link to patch5069$patchno++;5070print$cgi->a({-href => href(-anchor=>"patch$patchno")},5071"patch") .5072" | ";5073}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {5074# "commit" view and modified file (not only pure rename or copy)5075print$cgi->a({-href => href(action=>"blobdiff",5076 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},5077 hash_base=>$hash, hash_parent_base=>$parent,5078 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},5079"diff") .5080" | ";5081}5082print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},5083 hash_base=>$parent, file_name=>$diff->{'to_file'})},5084"blob") ." | ";5085if($have_blame) {5086print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,5087 file_name=>$diff->{'to_file'})},5088"blame") ." | ";5089}5090print$cgi->a({-href => href(action=>"history", hash_base=>$hash,5091 file_name=>$diff->{'to_file'})},5092"history");5093print"</td>\n";50945095}# we should not encounter Unmerged (U) or Unknown (X) status5096print"</tr>\n";5097}5098print"</tbody>"if$has_header;5099print"</table>\n";5100}51015102# Print context lines and then rem/add lines in a side-by-side manner.5103sub print_sidebyside_diff_lines {5104my($ctx,$rem,$add) =@_;51055106# print context block before add/rem block5107if(@$ctx) {5108print join'',5109'<div class="chunk_block ctx">',5110'<div class="old">',5111@$ctx,5112'</div>',5113'<div class="new">',5114@$ctx,5115'</div>',5116'</div>';5117}51185119if(!@$add) {5120# pure removal5121print join'',5122'<div class="chunk_block rem">',5123'<div class="old">',5124@$rem,5125'</div>',5126'</div>';5127}elsif(!@$rem) {5128# pure addition5129print join'',5130'<div class="chunk_block add">',5131'<div class="new">',5132@$add,5133'</div>',5134'</div>';5135}else{5136print join'',5137'<div class="chunk_block chg">',5138'<div class="old">',5139@$rem,5140'</div>',5141'<div class="new">',5142@$add,5143'</div>',5144'</div>';5145}5146}51475148# Print context lines and then rem/add lines in inline manner.5149sub print_inline_diff_lines {5150my($ctx,$rem,$add) =@_;51515152print@$ctx,@$rem,@$add;5153}51545155# Format removed and added line, mark changed part and HTML-format them.5156# Implementation is based on contrib/diff-highlight5157sub format_rem_add_lines_pair {5158my($rem,$add,$num_parents) =@_;51595160# We need to untabify lines before split()'ing them;5161# otherwise offsets would be invalid.5162chomp$rem;5163chomp$add;5164$rem= untabify($rem);5165$add= untabify($add);51665167my@rem=split(//,$rem);5168my@add=split(//,$add);5169my($esc_rem,$esc_add);5170# Ignore leading +/- characters for each parent.5171my($prefix_len,$suffix_len) = ($num_parents,0);5172my($prefix_has_nonspace,$suffix_has_nonspace);51735174my$shorter= (@rem<@add) ?@rem:@add;5175while($prefix_len<$shorter) {5176last if($rem[$prefix_len]ne$add[$prefix_len]);51775178$prefix_has_nonspace=1if($rem[$prefix_len] !~/\s/);5179$prefix_len++;5180}51815182while($prefix_len+$suffix_len<$shorter) {5183last if($rem[-1-$suffix_len]ne$add[-1-$suffix_len]);51845185$suffix_has_nonspace=1if($rem[-1-$suffix_len] !~/\s/);5186$suffix_len++;5187}51885189# Mark lines that are different from each other, but have some common5190# part that isn't whitespace. If lines are completely different, don't5191# mark them because that would make output unreadable, especially if5192# diff consists of multiple lines.5193if($prefix_has_nonspace||$suffix_has_nonspace) {5194$esc_rem= esc_html_hl_regions($rem,'marked',5195[$prefix_len,@rem-$suffix_len], -nbsp=>1);5196$esc_add= esc_html_hl_regions($add,'marked',5197[$prefix_len,@add-$suffix_len], -nbsp=>1);5198}else{5199$esc_rem= esc_html($rem, -nbsp=>1);5200$esc_add= esc_html($add, -nbsp=>1);5201}52025203return format_diff_line(\$esc_rem,'rem'),5204 format_diff_line(\$esc_add,'add');5205}52065207# HTML-format diff context, removed and added lines.5208sub format_ctx_rem_add_lines {5209my($ctx,$rem,$add,$num_parents) =@_;5210my(@new_ctx,@new_rem,@new_add);5211my$can_highlight=0;5212my$is_combined= ($num_parents>1);52135214# Highlight if every removed line has a corresponding added line.5215if(@$add>0&&@$add==@$rem) {5216$can_highlight=1;52175218# Highlight lines in combined diff only if the chunk contains5219# diff between the same version, e.g.5220#5221# - a5222# - b5223# + c5224# + d5225#5226# Otherwise the highlightling would be confusing.5227if($is_combined) {5228for(my$i=0;$i<@$add;$i++) {5229my$prefix_rem=substr($rem->[$i],0,$num_parents);5230my$prefix_add=substr($add->[$i],0,$num_parents);52315232$prefix_rem=~s/-/+/g;52335234if($prefix_remne$prefix_add) {5235$can_highlight=0;5236last;5237}5238}5239}5240}52415242if($can_highlight) {5243for(my$i=0;$i<@$add;$i++) {5244my($line_rem,$line_add) = format_rem_add_lines_pair(5245$rem->[$i],$add->[$i],$num_parents);5246push@new_rem,$line_rem;5247push@new_add,$line_add;5248}5249}else{5250@new_rem=map{ format_diff_line($_,'rem') }@$rem;5251@new_add=map{ format_diff_line($_,'add') }@$add;5252}52535254@new_ctx=map{ format_diff_line($_,'ctx') }@$ctx;52555256return(\@new_ctx, \@new_rem, \@new_add);5257}52585259# Print context lines and then rem/add lines.5260sub print_diff_lines {5261my($ctx,$rem,$add,$diff_style,$num_parents) =@_;5262my$is_combined=$num_parents>1;52635264($ctx,$rem,$add) = format_ctx_rem_add_lines($ctx,$rem,$add,5265$num_parents);52665267if($diff_styleeq'sidebyside'&& !$is_combined) {5268 print_sidebyside_diff_lines($ctx,$rem,$add);5269}else{5270# default 'inline' style and unknown styles5271 print_inline_diff_lines($ctx,$rem,$add);5272}5273}52745275sub print_diff_chunk {5276my($diff_style,$num_parents,$from,$to,@chunk) =@_;5277my(@ctx,@rem,@add);52785279# The class of the previous line.5280my$prev_class='';52815282return unless@chunk;52835284# incomplete last line might be among removed or added lines,5285# or both, or among context lines: find which5286for(my$i=1;$i<@chunk;$i++) {5287if($chunk[$i][0]eq'incomplete') {5288$chunk[$i][0] =$chunk[$i-1][0];5289}5290}52915292# guardian5293push@chunk, ["",""];52945295foreachmy$line_info(@chunk) {5296my($class,$line) =@$line_info;52975298# print chunk headers5299if($class&&$classeq'chunk_header') {5300print format_diff_line($line,$class,$from,$to);5301next;5302}53035304## print from accumulator when have some add/rem lines or end5305# of chunk (flush context lines), or when have add and rem5306# lines and new block is reached (otherwise add/rem lines could5307# be reordered)5308if(!$class|| ((@rem||@add) &&$classeq'ctx') ||5309(@rem&&@add&&$classne$prev_class)) {5310 print_diff_lines(\@ctx, \@rem, \@add,5311$diff_style,$num_parents);5312@ctx=@rem=@add= ();5313}53145315## adding lines to accumulator5316# guardian value5317last unless$line;5318# rem, add or change5319if($classeq'rem') {5320push@rem,$line;5321}elsif($classeq'add') {5322push@add,$line;5323}5324# context line5325if($classeq'ctx') {5326push@ctx,$line;5327}53285329$prev_class=$class;5330}5331}53325333sub git_patchset_body {5334my($fd,$diff_style,$difftree,$hash,@hash_parents) =@_;5335my($hash_parent) =$hash_parents[0];53365337my$is_combined= (@hash_parents>1);5338my$patch_idx=0;5339my$patch_number=0;5340my$patch_line;5341my$diffinfo;5342my$to_name;5343my(%from,%to);5344my@chunk;# for side-by-side diff53455346print"<div class=\"patchset\">\n";53475348# skip to first patch5349while($patch_line= <$fd>) {5350chomp$patch_line;53515352last if($patch_line=~m/^diff /);5353}53545355 PATCH:5356while($patch_line) {53575358# parse "git diff" header line5359if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {5360# $1 is from_name, which we do not use5361$to_name= unquote($2);5362$to_name=~s!^b/!!;5363}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {5364# $1 is 'cc' or 'combined', which we do not use5365$to_name= unquote($2);5366}else{5367$to_name=undef;5368}53695370# check if current patch belong to current raw line5371# and parse raw git-diff line if needed5372if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {5373# this is continuation of a split patch5374print"<div class=\"patch cont\">\n";5375}else{5376# advance raw git-diff output if needed5377$patch_idx++ifdefined$diffinfo;53785379# read and prepare patch information5380$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);53815382# compact combined diff output can have some patches skipped5383# find which patch (using pathname of result) we are at now;5384if($is_combined) {5385while($to_namene$diffinfo->{'to_file'}) {5386print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5387 format_diff_cc_simplified($diffinfo,@hash_parents) .5388"</div>\n";# class="patch"53895390$patch_idx++;5391$patch_number++;53925393last if$patch_idx>$#$difftree;5394$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);5395}5396}53975398# modifies %from, %to hashes5399 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);54005401# this is first patch for raw difftree line with $patch_idx index5402# we index @$difftree array from 0, but number patches from 15403print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";5404}54055406# git diff header5407#assert($patch_line =~ m/^diff /) if DEBUG;5408#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed5409$patch_number++;5410# print "git diff" header5411print format_git_diff_header_line($patch_line,$diffinfo,5412 \%from, \%to);54135414# print extended diff header5415print"<div class=\"diff extended_header\">\n";5416 EXTENDED_HEADER:5417while($patch_line= <$fd>) {5418chomp$patch_line;54195420last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);54215422print format_extended_diff_header_line($patch_line,$diffinfo,5423 \%from, \%to);5424}5425print"</div>\n";# class="diff extended_header"54265427# from-file/to-file diff header5428if(!$patch_line) {5429print"</div>\n";# class="patch"5430last PATCH;5431}5432next PATCH if($patch_line=~m/^diff /);5433#assert($patch_line =~ m/^---/) if DEBUG;54345435my$last_patch_line=$patch_line;5436$patch_line= <$fd>;5437chomp$patch_line;5438#assert($patch_line =~ m/^\+\+\+/) if DEBUG;54395440print format_diff_from_to_header($last_patch_line,$patch_line,5441$diffinfo, \%from, \%to,5442@hash_parents);54435444# the patch itself5445 LINE:5446while($patch_line= <$fd>) {5447chomp$patch_line;54485449next PATCH if($patch_line=~m/^diff /);54505451my$class= diff_line_class($patch_line, \%from, \%to);54525453if($classeq'chunk_header') {5454 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5455@chunk= ();5456}54575458push@chunk, [$class,$patch_line];5459}54605461}continue{5462if(@chunk) {5463 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5464@chunk= ();5465}5466print"</div>\n";# class="patch"5467}54685469# for compact combined (--cc) format, with chunk and patch simplification5470# the patchset might be empty, but there might be unprocessed raw lines5471for(++$patch_idxif$patch_number>0;5472$patch_idx<@$difftree;5473++$patch_idx) {5474# read and prepare patch information5475$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);54765477# generate anchor for "patch" links in difftree / whatchanged part5478print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5479 format_diff_cc_simplified($diffinfo,@hash_parents) .5480"</div>\n";# class="patch"54815482$patch_number++;5483}54845485if($patch_number==0) {5486if(@hash_parents>1) {5487print"<div class=\"diff nodifferences\">Trivial merge</div>\n";5488}else{5489print"<div class=\"diff nodifferences\">No differences found</div>\n";5490}5491}54925493print"</div>\n";# class="patchset"5494}54955496# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .54975498sub git_project_search_form {5499my($searchtext,$search_use_regexp) =@_;55005501my$limit='';5502if($project_filter) {5503$limit=" in '$project_filter/'";5504}55055506print"<div class=\"projsearch\">\n";5507print$cgi->startform(-method=>'get', -action =>$my_uri) .5508$cgi->hidden(-name =>'a', -value =>'project_list') ."\n";5509print$cgi->hidden(-name =>'pf', -value =>$project_filter)."\n"5510if(defined$project_filter);5511print$cgi->textfield(-name =>'s', -value =>$searchtext,5512-title =>"Search project by name and description$limit",5513-size =>60) ."\n".5514"<span title=\"Extended regular expression\">".5515$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',5516-checked =>$search_use_regexp) .5517"</span>\n".5518$cgi->submit(-name =>'btnS', -value =>'Search') .5519$cgi->end_form() ."\n".5520$cgi->a({-href => href(project =>undef, searchtext =>undef,5521 project_filter =>$project_filter)},5522 esc_html("List all projects$limit")) ."<br />\n";5523print"</div>\n";5524}55255526# entry for given @keys needs filling if at least one of keys in list5527# is not present in %$project_info5528sub project_info_needs_filling {5529my($project_info,@keys) =@_;55305531# return List::MoreUtils::any { !exists $project_info->{$_} } @keys;5532foreachmy$key(@keys) {5533if(!exists$project_info->{$key}) {5534return1;5535}5536}5537return;5538}55395540# fills project list info (age, description, owner, category, forks, etc.)5541# for each project in the list, removing invalid projects from5542# returned list, or fill only specified info.5543#5544# Invalid projects are removed from the returned list if and only if you5545# ask 'age' or 'age_string' to be filled, because they are the only fields5546# that run unconditionally git command that requires repository, and5547# therefore do always check if project repository is invalid.5548#5549# USAGE:5550# * fill_project_list_info(\@project_list, 'descr_long', 'ctags')5551# ensures that 'descr_long' and 'ctags' fields are filled5552# * @project_list = fill_project_list_info(\@project_list)5553# ensures that all fields are filled (and invalid projects removed)5554#5555# NOTE: modifies $projlist, but does not remove entries from it5556sub fill_project_list_info {5557my($projlist,@wanted_keys) =@_;5558my@projects;5559my$filter_set=sub{return@_; };5560if(@wanted_keys) {5561my%wanted_keys=map{$_=>1}@wanted_keys;5562$filter_set=sub{returngrep{$wanted_keys{$_} }@_; };5563}55645565my$show_ctags= gitweb_check_feature('ctags');5566 PROJECT:5567foreachmy$pr(@$projlist) {5568if(project_info_needs_filling($pr,$filter_set->('age','age_string'))) {5569my(@activity) = git_get_last_activity($pr->{'path'});5570unless(@activity) {5571next PROJECT;5572}5573($pr->{'age'},$pr->{'age_string'}) =@activity;5574}5575if(project_info_needs_filling($pr,$filter_set->('descr','descr_long'))) {5576my$descr= git_get_project_description($pr->{'path'}) ||"";5577$descr= to_utf8($descr);5578$pr->{'descr_long'} =$descr;5579$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);5580}5581if(project_info_needs_filling($pr,$filter_set->('owner'))) {5582$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";5583}5584if($show_ctags&&5585 project_info_needs_filling($pr,$filter_set->('ctags'))) {5586$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});5587}5588if($projects_list_group_categories&&5589 project_info_needs_filling($pr,$filter_set->('category'))) {5590my$cat= git_get_project_category($pr->{'path'}) ||5591$project_list_default_category;5592$pr->{'category'} = to_utf8($cat);5593}55945595push@projects,$pr;5596}55975598return@projects;5599}56005601sub sort_projects_list {5602my($projlist,$order) =@_;56035604sub order_str {5605my$key=shift;5606return sub{$a->{$key}cmp$b->{$key} };5607}56085609sub order_num_then_undef {5610my$key=shift;5611return sub{5612defined$a->{$key} ?5613(defined$b->{$key} ?$a->{$key} <=>$b->{$key} : -1) :5614(defined$b->{$key} ?1:0)5615};5616}56175618my%orderings= (5619 project => order_str('path'),5620 descr => order_str('descr_long'),5621 owner => order_str('owner'),5622 age => order_num_then_undef('age'),5623);56245625my$ordering=$orderings{$order};5626returndefined$ordering?sort$ordering @$projlist:@$projlist;5627}56285629# returns a hash of categories, containing the list of project5630# belonging to each category5631sub build_projlist_by_category {5632my($projlist,$from,$to) =@_;5633my%categories;56345635$from=0unlessdefined$from;5636$to=$#$projlistif(!defined$to||$#$projlist<$to);56375638for(my$i=$from;$i<=$to;$i++) {5639my$pr=$projlist->[$i];5640push@{$categories{$pr->{'category'} }},$pr;5641}56425643returnwantarray?%categories: \%categories;5644}56455646# print 'sort by' <th> element, generating 'sort by $name' replay link5647# if that order is not selected5648sub print_sort_th {5649print format_sort_th(@_);5650}56515652sub format_sort_th {5653my($name,$order,$header) =@_;5654my$sort_th="";5655$header||=ucfirst($name);56565657if($ordereq$name) {5658$sort_th.="<th>$header</th>\n";5659}else{5660$sort_th.="<th>".5661$cgi->a({-href => href(-replay=>1, order=>$name),5662-class=>"header"},$header) .5663"</th>\n";5664}56655666return$sort_th;5667}56685669sub git_project_list_rows {5670my($projlist,$from,$to,$check_forks) =@_;56715672$from=0unlessdefined$from;5673$to=$#$projlistif(!defined$to||$#$projlist<$to);56745675my$alternate=1;5676for(my$i=$from;$i<=$to;$i++) {5677my$pr=$projlist->[$i];56785679if($alternate) {5680print"<tr class=\"dark\">\n";5681}else{5682print"<tr class=\"light\">\n";5683}5684$alternate^=1;56855686if($check_forks) {5687print"<td>";5688if($pr->{'forks'}) {5689my$nforks=scalar@{$pr->{'forks'}};5690if($nforks>0) {5691print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5692-title =>"$nforksforks"},"+");5693}else{5694print$cgi->span({-title =>"$nforksforks"},"+");5695}5696}5697print"</td>\n";5698}5699print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5700-class=>"list"},5701 esc_html_match_hl($pr->{'path'},$search_regexp)) .5702"</td>\n".5703"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5704-class=>"list",5705-title =>$pr->{'descr_long'}},5706$search_regexp5707? esc_html_match_hl_chopped($pr->{'descr_long'},5708$pr->{'descr'},$search_regexp)5709: esc_html($pr->{'descr'})) .5710"</td>\n";5711unless($omit_owner) {5712print"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5713}5714unless($omit_age_column) {5715print"<td class=\"". age_class($pr->{'age'}) ."\">".5716(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n";5717}5718print"<td class=\"link\">".5719$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5720$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5721$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5722$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5723($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5724"</td>\n".5725"</tr>\n";5726}5727}57285729sub git_project_list_body {5730# actually uses global variable $project5731my($projlist,$order,$from,$to,$extra,$no_header) =@_;5732my@projects=@$projlist;57335734my$check_forks= gitweb_check_feature('forks');5735my$show_ctags= gitweb_check_feature('ctags');5736my$tagfilter=$show_ctags?$input_params{'ctag'} :undef;5737$check_forks=undef5738if($tagfilter||$search_regexp);57395740# filtering out forks before filling info allows to do less work5741@projects= filter_forks_from_projects_list(\@projects)5742if($check_forks);5743# search_projects_list pre-fills required info5744@projects= search_projects_list(\@projects,5745'search_regexp'=>$search_regexp,5746'tagfilter'=>$tagfilter)5747if($tagfilter||$search_regexp);5748# fill the rest5749my@all_fields= ('descr','descr_long','ctags','category');5750push@all_fields, ('age','age_string')unless($omit_age_column);5751push@all_fields,'owner'unless($omit_owner);5752@projects= fill_project_list_info(\@projects,@all_fields);57535754$order||=$default_projects_order;5755$from=0unlessdefined$from;5756$to=$#projectsif(!defined$to||$#projects<$to);57575758# short circuit5759if($from>$to) {5760print"<center>\n".5761"<b>No such projects found</b><br />\n".5762"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5763"</center>\n<br />\n";5764return;5765}57665767@projects= sort_projects_list(\@projects,$order);57685769if($show_ctags) {5770my$ctags= git_gather_all_ctags(\@projects);5771my$cloud= git_populate_project_tagcloud($ctags);5772print git_show_project_tagcloud($cloud,64);5773}57745775print"<table class=\"project_list\">\n";5776unless($no_header) {5777print"<tr>\n";5778if($check_forks) {5779print"<th></th>\n";5780}5781 print_sort_th('project',$order,'Project');5782 print_sort_th('descr',$order,'Description');5783 print_sort_th('owner',$order,'Owner')unless$omit_owner;5784 print_sort_th('age',$order,'Last Change')unless$omit_age_column;5785print"<th></th>\n".# for links5786"</tr>\n";5787}57885789if($projects_list_group_categories) {5790# only display categories with projects in the $from-$to window5791@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5792my%categories= build_projlist_by_category(\@projects,$from,$to);5793foreachmy$cat(sort keys%categories) {5794unless($cateq"") {5795print"<tr>\n";5796if($check_forks) {5797print"<td></td>\n";5798}5799print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5800print"</tr>\n";5801}58025803 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5804}5805}else{5806 git_project_list_rows(\@projects,$from,$to,$check_forks);5807}58085809if(defined$extra) {5810print"<tr>\n";5811if($check_forks) {5812print"<td></td>\n";5813}5814print"<td colspan=\"5\">$extra</td>\n".5815"</tr>\n";5816}5817print"</table>\n";5818}58195820sub git_log_body {5821# uses global variable $project5822my($commitlist,$from,$to,$refs,$extra) =@_;58235824$from=0unlessdefined$from;5825$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);58265827for(my$i=0;$i<=$to;$i++) {5828my%co= %{$commitlist->[$i]};5829next if!%co;5830my$commit=$co{'id'};5831my$ref= format_ref_marker($refs,$commit);5832 git_print_header_div('commit',5833"<span class=\"age\">$co{'age_string'}</span>".5834 esc_html($co{'title'}) .$ref,5835$commit);5836print"<div class=\"title_text\">\n".5837"<div class=\"log_link\">\n".5838$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5839" | ".5840$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5841" | ".5842$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5843"<br/>\n".5844"</div>\n";5845 git_print_authorship(\%co, -tag =>'span');5846print"<br/>\n</div>\n";58475848print"<div class=\"log_body\">\n";5849 git_print_log($co{'comment'}, -final_empty_line=>1);5850print"</div>\n";5851}5852if($extra) {5853print"<div class=\"page_nav\">\n";5854print"$extra\n";5855print"</div>\n";5856}5857}58585859sub git_shortlog_body {5860# uses global variable $project5861my($commitlist,$from,$to,$refs,$extra) =@_;58625863$from=0unlessdefined$from;5864$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);58655866print"<table class=\"shortlog\">\n";5867my$alternate=1;5868for(my$i=$from;$i<=$to;$i++) {5869my%co= %{$commitlist->[$i]};5870my$commit=$co{'id'};5871my$ref= format_ref_marker($refs,$commit);5872if($alternate) {5873print"<tr class=\"dark\">\n";5874}else{5875print"<tr class=\"light\">\n";5876}5877$alternate^=1;5878# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5879print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5880 format_author_html('td', \%co,10) ."<td>";5881print format_subject_html($co{'title'},$co{'title_short'},5882 href(action=>"commit", hash=>$commit),$ref);5883print"</td>\n".5884"<td class=\"link\">".5885$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5886$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5887$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5888my$snapshot_links= format_snapshot_links($commit);5889if(defined$snapshot_links) {5890print" | ".$snapshot_links;5891}5892print"</td>\n".5893"</tr>\n";5894}5895if(defined$extra) {5896print"<tr>\n".5897"<td colspan=\"4\">$extra</td>\n".5898"</tr>\n";5899}5900print"</table>\n";5901}59025903sub git_history_body {5904# Warning: assumes constant type (blob or tree) during history5905my($commitlist,$from,$to,$refs,$extra,5906$file_name,$file_hash,$ftype) =@_;59075908$from=0unlessdefined$from;5909$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});59105911print"<table class=\"history\">\n";5912my$alternate=1;5913for(my$i=$from;$i<=$to;$i++) {5914my%co= %{$commitlist->[$i]};5915if(!%co) {5916next;5917}5918my$commit=$co{'id'};59195920my$ref= format_ref_marker($refs,$commit);59215922if($alternate) {5923print"<tr class=\"dark\">\n";5924}else{5925print"<tr class=\"light\">\n";5926}5927$alternate^=1;5928print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5929# shortlog: format_author_html('td', \%co, 10)5930 format_author_html('td', \%co,15,3) ."<td>";5931# originally git_history used chop_str($co{'title'}, 50)5932print format_subject_html($co{'title'},$co{'title_short'},5933 href(action=>"commit", hash=>$commit),$ref);5934print"</td>\n".5935"<td class=\"link\">".5936$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5937$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");59385939if($ftypeeq'blob') {5940my$blob_current=$file_hash;5941my$blob_parent= git_get_hash_by_path($commit,$file_name);5942if(defined$blob_current&&defined$blob_parent&&5943$blob_currentne$blob_parent) {5944print" | ".5945$cgi->a({-href => href(action=>"blobdiff",5946 hash=>$blob_current, hash_parent=>$blob_parent,5947 hash_base=>$hash_base, hash_parent_base=>$commit,5948 file_name=>$file_name)},5949"diff to current");5950}5951}5952print"</td>\n".5953"</tr>\n";5954}5955if(defined$extra) {5956print"<tr>\n".5957"<td colspan=\"4\">$extra</td>\n".5958"</tr>\n";5959}5960print"</table>\n";5961}59625963sub git_tags_body {5964# uses global variable $project5965my($taglist,$from,$to,$extra) =@_;5966$from=0unlessdefined$from;5967$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);59685969print"<table class=\"tags\">\n";5970my$alternate=1;5971for(my$i=$from;$i<=$to;$i++) {5972my$entry=$taglist->[$i];5973my%tag=%$entry;5974my$comment=$tag{'subject'};5975my$comment_short;5976if(defined$comment) {5977$comment_short= chop_str($comment,30,5);5978}5979if($alternate) {5980print"<tr class=\"dark\">\n";5981}else{5982print"<tr class=\"light\">\n";5983}5984$alternate^=1;5985if(defined$tag{'age'}) {5986print"<td><i>$tag{'age'}</i></td>\n";5987}else{5988print"<td></td>\n";5989}5990print"<td>".5991$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5992-class=>"list name"}, esc_html($tag{'name'})) .5993"</td>\n".5994"<td>";5995if(defined$comment) {5996print format_subject_html($comment,$comment_short,5997 href(action=>"tag", hash=>$tag{'id'}));5998}5999print"</td>\n".6000"<td class=\"selflink\">";6001if($tag{'type'}eq"tag") {6002print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");6003}else{6004print" ";6005}6006print"</td>\n".6007"<td class=\"link\">"." | ".6008$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});6009if($tag{'reftype'}eq"commit") {6010print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .6011" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");6012}elsif($tag{'reftype'}eq"blob") {6013print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");6014}6015print"</td>\n".6016"</tr>";6017}6018if(defined$extra) {6019print"<tr>\n".6020"<td colspan=\"5\">$extra</td>\n".6021"</tr>\n";6022}6023print"</table>\n";6024}60256026sub git_heads_body {6027# uses global variable $project6028my($headlist,$head_at,$from,$to,$extra) =@_;6029$from=0unlessdefined$from;6030$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);60316032print"<table class=\"heads\">\n";6033my$alternate=1;6034for(my$i=$from;$i<=$to;$i++) {6035my$entry=$headlist->[$i];6036my%ref=%$entry;6037my$curr=defined$head_at&&$ref{'id'}eq$head_at;6038if($alternate) {6039print"<tr class=\"dark\">\n";6040}else{6041print"<tr class=\"light\">\n";6042}6043$alternate^=1;6044print"<td><i>$ref{'age'}</i></td>\n".6045($curr?"<td class=\"current_head\">":"<td>") .6046$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),6047-class=>"list name"},esc_html($ref{'name'})) .6048"</td>\n".6049"<td class=\"link\">".6050$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".6051$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".6052$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .6053"</td>\n".6054"</tr>";6055}6056if(defined$extra) {6057print"<tr>\n".6058"<td colspan=\"3\">$extra</td>\n".6059"</tr>\n";6060}6061print"</table>\n";6062}60636064# Display a single remote block6065sub git_remote_block {6066my($remote,$rdata,$limit,$head) =@_;60676068my$heads=$rdata->{'heads'};6069my$fetch=$rdata->{'fetch'};6070my$push=$rdata->{'push'};60716072my$urls_table="<table class=\"projects_list\">\n";60736074if(defined$fetch) {6075if($fetcheq$push) {6076$urls_table.= format_repo_url("URL",$fetch);6077}else{6078$urls_table.= format_repo_url("Fetch URL",$fetch);6079$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;6080}6081}elsif(defined$push) {6082$urls_table.= format_repo_url("Push URL",$push);6083}else{6084$urls_table.= format_repo_url("","No remote URL");6085}60866087$urls_table.="</table>\n";60886089my$dots;6090if(defined$limit&&$limit<@$heads) {6091$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");6092}60936094print$urls_table;6095 git_heads_body($heads,$head,0,$limit,$dots);6096}60976098# Display a list of remote names with the respective fetch and push URLs6099sub git_remotes_list {6100my($remotedata,$limit) =@_;6101print"<table class=\"heads\">\n";6102my$alternate=1;6103my@remotes=sort keys%$remotedata;61046105my$limited=$limit&&$limit<@remotes;61066107$#remotes=$limit-1if$limited;61086109while(my$remote=shift@remotes) {6110my$rdata=$remotedata->{$remote};6111my$fetch=$rdata->{'fetch'};6112my$push=$rdata->{'push'};6113if($alternate) {6114print"<tr class=\"dark\">\n";6115}else{6116print"<tr class=\"light\">\n";6117}6118$alternate^=1;6119print"<td>".6120$cgi->a({-href=> href(action=>'remotes', hash=>$remote),6121-class=>"list name"},esc_html($remote)) .6122"</td>";6123print"<td class=\"link\">".6124(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .6125" | ".6126(defined$push?$cgi->a({-href=>$push},"push") :"push") .6127"</td>";61286129print"</tr>\n";6130}61316132if($limited) {6133print"<tr>\n".6134"<td colspan=\"3\">".6135$cgi->a({-href => href(action=>"remotes")},"...") .6136"</td>\n"."</tr>\n";6137}61386139print"</table>";6140}61416142# Display remote heads grouped by remote, unless there are too many6143# remotes, in which case we only display the remote names6144sub git_remotes_body {6145my($remotedata,$limit,$head) =@_;6146if($limitand$limit<keys%$remotedata) {6147 git_remotes_list($remotedata,$limit);6148}else{6149 fill_remote_heads($remotedata);6150while(my($remote,$rdata) =each%$remotedata) {6151 git_print_section({-class=>"remote", -id=>$remote},6152["remotes",$remote,$remote],sub{6153 git_remote_block($remote,$rdata,$limit,$head);6154});6155}6156}6157}61586159sub git_search_message {6160my%co=@_;61616162my$greptype;6163if($searchtypeeq'commit') {6164$greptype="--grep=";6165}elsif($searchtypeeq'author') {6166$greptype="--author=";6167}elsif($searchtypeeq'committer') {6168$greptype="--committer=";6169}6170$greptype.=$searchtext;6171my@commitlist= parse_commits($hash,101, (100*$page),undef,6172$greptype,'--regexp-ignore-case',6173$search_use_regexp?'--extended-regexp':'--fixed-strings');61746175my$paging_nav='';6176if($page>0) {6177$paging_nav.=6178$cgi->a({-href => href(-replay=>1, page=>undef)},6179"first") .6180" ⋅ ".6181$cgi->a({-href => href(-replay=>1, page=>$page-1),6182-accesskey =>"p", -title =>"Alt-p"},"prev");6183}else{6184$paging_nav.="first ⋅ prev";6185}6186my$next_link='';6187if($#commitlist>=100) {6188$next_link=6189$cgi->a({-href => href(-replay=>1, page=>$page+1),6190-accesskey =>"n", -title =>"Alt-n"},"next");6191$paging_nav.=" ⋅$next_link";6192}else{6193$paging_nav.=" ⋅ next";6194}61956196 git_header_html();61976198 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);6199 git_print_header_div('commit', esc_html($co{'title'}),$hash);6200if($page==0&& !@commitlist) {6201print"<p>No match.</p>\n";6202}else{6203 git_search_grep_body(\@commitlist,0,99,$next_link);6204}62056206 git_footer_html();6207}62086209sub git_search_changes {6210my%co=@_;62116212local$/="\n";6213open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,6214'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",6215($search_use_regexp?'--pickaxe-regex': ())6216or die_error(500,"Open git-log failed");62176218 git_header_html();62196220 git_print_page_nav('','',$hash,$co{'tree'},$hash);6221 git_print_header_div('commit', esc_html($co{'title'}),$hash);62226223print"<table class=\"pickaxe search\">\n";6224my$alternate=1;6225undef%co;6226my@files;6227while(my$line= <$fd>) {6228chomp$line;6229next unless$line;62306231my%set= parse_difftree_raw_line($line);6232if(defined$set{'commit'}) {6233# finish previous commit6234if(%co) {6235print"</td>\n".6236"<td class=\"link\">".6237$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6238"commit") .6239" | ".6240$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6241 hash_base=>$co{'id'})},6242"tree") .6243"</td>\n".6244"</tr>\n";6245}62466247if($alternate) {6248print"<tr class=\"dark\">\n";6249}else{6250print"<tr class=\"light\">\n";6251}6252$alternate^=1;6253%co= parse_commit($set{'commit'});6254my$author= chop_and_escape_str($co{'author_name'},15,5);6255print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6256"<td><i>$author</i></td>\n".6257"<td>".6258$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6259-class=>"list subject"},6260 chop_and_escape_str($co{'title'},50) ."<br/>");6261}elsif(defined$set{'to_id'}) {6262next if($set{'to_id'} =~m/^0{40}$/);62636264print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},6265 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),6266-class=>"list"},6267"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .6268"<br/>\n";6269}6270}6271close$fd;62726273# finish last commit (warning: repetition!)6274if(%co) {6275print"</td>\n".6276"<td class=\"link\">".6277$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6278"commit") .6279" | ".6280$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6281 hash_base=>$co{'id'})},6282"tree") .6283"</td>\n".6284"</tr>\n";6285}62866287print"</table>\n";62886289 git_footer_html();6290}62916292sub git_search_files {6293my%co=@_;62946295local$/="\n";6296open my$fd,"-|", git_cmd(),'grep','-n','-z',6297$search_use_regexp? ('-E','-i') :'-F',6298$searchtext,$co{'tree'}6299or die_error(500,"Open git-grep failed");63006301 git_header_html();63026303 git_print_page_nav('','',$hash,$co{'tree'},$hash);6304 git_print_header_div('commit', esc_html($co{'title'}),$hash);63056306print"<table class=\"grep_search\">\n";6307my$alternate=1;6308my$matches=0;6309my$lastfile='';6310my$file_href;6311while(my$line= <$fd>) {6312chomp$line;6313my($file,$lno,$ltext,$binary);6314last if($matches++>1000);6315if($line=~/^Binary file (.+) matches$/) {6316$file=$1;6317$binary=1;6318}else{6319($file,$lno,$ltext) =split(/\0/,$line,3);6320$file=~s/^$co{'tree'}://;6321}6322if($filene$lastfile) {6323$lastfileand print"</td></tr>\n";6324if($alternate++) {6325print"<tr class=\"dark\">\n";6326}else{6327print"<tr class=\"light\">\n";6328}6329$file_href= href(action=>"blob", hash_base=>$co{'id'},6330 file_name=>$file);6331print"<td class=\"list\">".6332$cgi->a({-href =>$file_href, -class=>"list"}, esc_path($file));6333print"</td><td>\n";6334$lastfile=$file;6335}6336if($binary) {6337print"<div class=\"binary\">Binary file</div>\n";6338}else{6339$ltext= untabify($ltext);6340if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6341$ltext= esc_html($1, -nbsp=>1);6342$ltext.='<span class="match">';6343$ltext.= esc_html($2, -nbsp=>1);6344$ltext.='</span>';6345$ltext.= esc_html($3, -nbsp=>1);6346}else{6347$ltext= esc_html($ltext, -nbsp=>1);6348}6349print"<div class=\"pre\">".6350$cgi->a({-href =>$file_href.'#l'.$lno,6351-class=>"linenr"},sprintf('%4i',$lno)) .6352' '.$ltext."</div>\n";6353}6354}6355if($lastfile) {6356print"</td></tr>\n";6357if($matches>1000) {6358print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6359}6360}else{6361print"<div class=\"diff nodifferences\">No matches found</div>\n";6362}6363close$fd;63646365print"</table>\n";63666367 git_footer_html();6368}63696370sub git_search_grep_body {6371my($commitlist,$from,$to,$extra) =@_;6372$from=0unlessdefined$from;6373$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);63746375print"<table class=\"commit_search\">\n";6376my$alternate=1;6377for(my$i=$from;$i<=$to;$i++) {6378my%co= %{$commitlist->[$i]};6379if(!%co) {6380next;6381}6382my$commit=$co{'id'};6383if($alternate) {6384print"<tr class=\"dark\">\n";6385}else{6386print"<tr class=\"light\">\n";6387}6388$alternate^=1;6389print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6390 format_author_html('td', \%co,15,5) .6391"<td>".6392$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6393-class=>"list subject"},6394 chop_and_escape_str($co{'title'},50) ."<br/>");6395my$comment=$co{'comment'};6396foreachmy$line(@$comment) {6397if($line=~m/^(.*?)($search_regexp)(.*)$/i) {6398my($lead,$match,$trail) = ($1,$2,$3);6399$match= chop_str($match,70,5,'center');6400my$contextlen=int((80-length($match))/2);6401$contextlen=30if($contextlen>30);6402$lead= chop_str($lead,$contextlen,10,'left');6403$trail= chop_str($trail,$contextlen,10,'right');64046405$lead= esc_html($lead);6406$match= esc_html($match);6407$trail= esc_html($trail);64086409print"$lead<span class=\"match\">$match</span>$trail<br />";6410}6411}6412print"</td>\n".6413"<td class=\"link\">".6414$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6415" | ".6416$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .6417" | ".6418$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6419print"</td>\n".6420"</tr>\n";6421}6422if(defined$extra) {6423print"<tr>\n".6424"<td colspan=\"3\">$extra</td>\n".6425"</tr>\n";6426}6427print"</table>\n";6428}64296430## ======================================================================6431## ======================================================================6432## actions64336434sub git_project_list {6435my$order=$input_params{'order'};6436if(defined$order&&$order!~m/none|project|descr|owner|age/) {6437 die_error(400,"Unknown order parameter");6438}64396440my@list= git_get_projects_list($project_filter,$strict_export);6441if(!@list) {6442 die_error(404,"No projects found");6443}64446445 git_header_html();6446if(defined$home_text&& -f $home_text) {6447print"<div class=\"index_include\">\n";6448 insert_file($home_text);6449print"</div>\n";6450}64516452 git_project_search_form($searchtext,$search_use_regexp);6453 git_project_list_body(\@list,$order);6454 git_footer_html();6455}64566457sub git_forks {6458my$order=$input_params{'order'};6459if(defined$order&&$order!~m/none|project|descr|owner|age/) {6460 die_error(400,"Unknown order parameter");6461}64626463my$filter=$project;6464$filter=~s/\.git$//;6465my@list= git_get_projects_list($filter);6466if(!@list) {6467 die_error(404,"No forks found");6468}64696470 git_header_html();6471 git_print_page_nav('','');6472 git_print_header_div('summary',"$projectforks");6473 git_project_list_body(\@list,$order);6474 git_footer_html();6475}64766477sub git_project_index {6478my@projects= git_get_projects_list($project_filter,$strict_export);6479if(!@projects) {6480 die_error(404,"No projects found");6481}64826483print$cgi->header(6484-type =>'text/plain',6485-charset =>'utf-8',6486-content_disposition =>'inline; filename="index.aux"');64876488foreachmy$pr(@projects) {6489if(!exists$pr->{'owner'}) {6490$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");6491}64926493my($path,$owner) = ($pr->{'path'},$pr->{'owner'});6494# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '6495$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6496$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6497$path=~s/ /\+/g;6498$owner=~s/ /\+/g;64996500print"$path$owner\n";6501}6502}65036504sub git_summary {6505my$descr= git_get_project_description($project) ||"none";6506my%co= parse_commit("HEAD");6507my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();6508my$head=$co{'id'};6509my$remote_heads= gitweb_check_feature('remote_heads');65106511my$owner= git_get_project_owner($project);65126513my$refs= git_get_references();6514# These get_*_list functions return one more to allow us to see if6515# there are more ...6516my@taglist= git_get_tags_list(16);6517my@headlist= git_get_heads_list(16);6518my%remotedata=$remote_heads? git_get_remotes_list() : ();6519my@forklist;6520my$check_forks= gitweb_check_feature('forks');65216522if($check_forks) {6523# find forks of a project6524my$filter=$project;6525$filter=~s/\.git$//;6526@forklist= git_get_projects_list($filter);6527# filter out forks of forks6528@forklist= filter_forks_from_projects_list(\@forklist)6529if(@forklist);6530}65316532 git_header_html();6533 git_print_page_nav('summary','',$head);65346535print"<div class=\"title\"> </div>\n";6536print"<table class=\"projects_list\">\n".6537"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n";6538if($ownerand not$omit_owner) {6539print"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";6540}6541if(defined$cd{'rfc2822'}) {6542print"<tr id=\"metadata_lchange\"><td>last change</td>".6543"<td>".format_timestamp_html(\%cd)."</td></tr>\n";6544}65456546# use per project git URL list in $projectroot/$project/cloneurl6547# or make project git URL from git base URL and project name6548my$url_tag="URL";6549my@url_list= git_get_project_url_list($project);6550@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;6551foreachmy$git_url(@url_list) {6552next unless$git_url;6553print format_repo_url($url_tag,$git_url);6554$url_tag="";6555}65566557# Tag cloud6558my$show_ctags= gitweb_check_feature('ctags');6559if($show_ctags) {6560my$ctags= git_get_project_ctags($project);6561if(%$ctags) {6562# without ability to add tags, don't show if there are none6563my$cloud= git_populate_project_tagcloud($ctags);6564print"<tr id=\"metadata_ctags\">".6565"<td>content tags</td>".6566"<td>".git_show_project_tagcloud($cloud,48)."</td>".6567"</tr>\n";6568}6569}65706571print"</table>\n";65726573# If XSS prevention is on, we don't include README.html.6574# TODO: Allow a readme in some safe format.6575if(!$prevent_xss&& -s "$projectroot/$project/README.html") {6576print"<div class=\"title\">readme</div>\n".6577"<div class=\"readme\">\n";6578 insert_file("$projectroot/$project/README.html");6579print"\n</div>\n";# class="readme"6580}65816582# we need to request one more than 16 (0..15) to check if6583# those 16 are all6584my@commitlist=$head? parse_commits($head,17) : ();6585if(@commitlist) {6586 git_print_header_div('shortlog');6587 git_shortlog_body(\@commitlist,0,15,$refs,6588$#commitlist<=15?undef:6589$cgi->a({-href => href(action=>"shortlog")},"..."));6590}65916592if(@taglist) {6593 git_print_header_div('tags');6594 git_tags_body(\@taglist,0,15,6595$#taglist<=15?undef:6596$cgi->a({-href => href(action=>"tags")},"..."));6597}65986599if(@headlist) {6600 git_print_header_div('heads');6601 git_heads_body(\@headlist,$head,0,15,6602$#headlist<=15?undef:6603$cgi->a({-href => href(action=>"heads")},"..."));6604}66056606if(%remotedata) {6607 git_print_header_div('remotes');6608 git_remotes_body(\%remotedata,15,$head);6609}66106611if(@forklist) {6612 git_print_header_div('forks');6613 git_project_list_body(\@forklist,'age',0,15,6614$#forklist<=15?undef:6615$cgi->a({-href => href(action=>"forks")},"..."),6616'no_header');6617}66186619 git_footer_html();6620}66216622sub git_tag {6623my%tag= parse_tag($hash);66246625if(!%tag) {6626 die_error(404,"Unknown tag object");6627}66286629my$head= git_get_head_hash($project);6630 git_header_html();6631 git_print_page_nav('','',$head,undef,$head);6632 git_print_header_div('commit', esc_html($tag{'name'}),$hash);6633print"<div class=\"title_text\">\n".6634"<table class=\"object_header\">\n".6635"<tr>\n".6636"<td>object</td>\n".6637"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6638$tag{'object'}) ."</td>\n".6639"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6640$tag{'type'}) ."</td>\n".6641"</tr>\n";6642if(defined($tag{'author'})) {6643 git_print_authorship_rows(\%tag,'author');6644}6645print"</table>\n\n".6646"</div>\n";6647print"<div class=\"page_body\">";6648my$comment=$tag{'comment'};6649foreachmy$line(@$comment) {6650chomp$line;6651print esc_html($line, -nbsp=>1) ."<br/>\n";6652}6653print"</div>\n";6654 git_footer_html();6655}66566657sub git_blame_common {6658my$format=shift||'porcelain';6659if($formateq'porcelain'&&$input_params{'javascript'}) {6660$format='incremental';6661$action='blame_incremental';# for page title etc6662}66636664# permissions6665 gitweb_check_feature('blame')6666or die_error(403,"Blame view not allowed");66676668# error checking6669 die_error(400,"No file name given")unless$file_name;6670$hash_base||= git_get_head_hash($project);6671 die_error(404,"Couldn't find base commit")unless$hash_base;6672my%co= parse_commit($hash_base)6673or die_error(404,"Commit not found");6674my$ftype="blob";6675if(!defined$hash) {6676$hash= git_get_hash_by_path($hash_base,$file_name,"blob")6677or die_error(404,"Error looking up file");6678}else{6679$ftype= git_get_type($hash);6680if($ftype!~"blob") {6681 die_error(400,"Object is not a blob");6682}6683}66846685my$fd;6686if($formateq'incremental') {6687# get file contents (as base)6688open$fd,"-|", git_cmd(),'cat-file','blob',$hash6689or die_error(500,"Open git-cat-file failed");6690}elsif($formateq'data') {6691# run git-blame --incremental6692open$fd,"-|", git_cmd(),"blame","--incremental",6693$hash_base,"--",$file_name6694or die_error(500,"Open git-blame --incremental failed");6695}else{6696# run git-blame --porcelain6697open$fd,"-|", git_cmd(),"blame",'-p',6698$hash_base,'--',$file_name6699or die_error(500,"Open git-blame --porcelain failed");6700}6701binmode$fd,':utf8';67026703# incremental blame data returns early6704if($formateq'data') {6705print$cgi->header(6706-type=>"text/plain", -charset =>"utf-8",6707-status=>"200 OK");6708local$| =1;# output autoflush6709while(my$line= <$fd>) {6710print to_utf8($line);6711}6712close$fd6713or print"ERROR$!\n";67146715print'END';6716if(defined$t0&& gitweb_check_feature('timed')) {6717print' '.6718 tv_interval($t0, [ gettimeofday() ]).6719' '.$number_of_git_cmds;6720}6721print"\n";67226723return;6724}67256726# page header6727 git_header_html();6728my$formats_nav=6729$cgi->a({-href => href(action=>"blob", -replay=>1)},6730"blob") .6731" | ";6732if($formateq'incremental') {6733$formats_nav.=6734$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},6735"blame") ." (non-incremental)";6736}else{6737$formats_nav.=6738$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},6739"blame") ." (incremental)";6740}6741$formats_nav.=6742" | ".6743$cgi->a({-href => href(action=>"history", -replay=>1)},6744"history") .6745" | ".6746$cgi->a({-href => href(action=>$action, file_name=>$file_name)},6747"HEAD");6748 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6749 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6750 git_print_page_path($file_name,$ftype,$hash_base);67516752# page body6753if($formateq'incremental') {6754print"<noscript>\n<div class=\"error\"><center><b>\n".6755"This page requires JavaScript to run.\nUse ".6756$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},6757'this page').6758" instead.\n".6759"</b></center></div>\n</noscript>\n";67606761print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;6762}67636764print qq!<div class="page_body">\n!;6765print qq!<div id="progress_info">.../ ...</div>\n!6766if($formateq'incremental');6767print qq!<table id="blame_table"class="blame" width="100%">\n!.6768#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.6769 qq!<thead>\n!.6770 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.6771 qq!</thead>\n!.6772 qq!<tbody>\n!;67736774my@rev_color=qw(light dark);6775my$num_colors=scalar(@rev_color);6776my$current_color=0;67776778if($formateq'incremental') {6779my$color_class=$rev_color[$current_color];67806781#contents of a file6782my$linenr=0;6783 LINE:6784while(my$line= <$fd>) {6785chomp$line;6786$linenr++;67876788print qq!<tr id="l$linenr"class="$color_class">!.6789 qq!<td class="sha1"><a href=""> </a></td>!.6790 qq!<td class="linenr">!.6791 qq!<a class="linenr" href="">$linenr</a></td>!;6792print qq!<td class="pre">! . esc_html($line) ."</td>\n";6793print qq!</tr>\n!;6794}67956796}else{# porcelain, i.e. ordinary blame6797my%metainfo= ();# saves information about commits67986799# blame data6800 LINE:6801while(my$line= <$fd>) {6802chomp$line;6803# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]6804# no <lines in group> for subsequent lines in group of lines6805my($full_rev,$orig_lineno,$lineno,$group_size) =6806($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);6807if(!exists$metainfo{$full_rev}) {6808$metainfo{$full_rev} = {'nprevious'=>0};6809}6810my$meta=$metainfo{$full_rev};6811my$data;6812while($data= <$fd>) {6813chomp$data;6814last if($data=~s/^\t//);# contents of line6815if($data=~/^(\S+)(?: (.*))?$/) {6816$meta->{$1} =$2unlessexists$meta->{$1};6817}6818if($data=~/^previous /) {6819$meta->{'nprevious'}++;6820}6821}6822my$short_rev=substr($full_rev,0,8);6823my$author=$meta->{'author'};6824my%date=6825 parse_date($meta->{'author-time'},$meta->{'author-tz'});6826my$date=$date{'iso-tz'};6827if($group_size) {6828$current_color= ($current_color+1) %$num_colors;6829}6830my$tr_class=$rev_color[$current_color];6831$tr_class.=' boundary'if(exists$meta->{'boundary'});6832$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);6833$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);6834print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";6835if($group_size) {6836print"<td class=\"sha1\"";6837print" title=\"". esc_html($author) .",$date\"";6838print" rowspan=\"$group_size\""if($group_size>1);6839print">";6840print$cgi->a({-href => href(action=>"commit",6841 hash=>$full_rev,6842 file_name=>$file_name)},6843 esc_html($short_rev));6844if($group_size>=2) {6845my@author_initials= ($author=~/\b([[:upper:]])\B/g);6846if(@author_initials) {6847print"<br />".6848 esc_html(join('',@author_initials));6849# or join('.', ...)6850}6851}6852print"</td>\n";6853}6854# 'previous' <sha1 of parent commit> <filename at commit>6855if(exists$meta->{'previous'} &&6856$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {6857$meta->{'parent'} =$1;6858$meta->{'file_parent'} = unquote($2);6859}6860my$linenr_commit=6861exists($meta->{'parent'}) ?6862$meta->{'parent'} :$full_rev;6863my$linenr_filename=6864exists($meta->{'file_parent'}) ?6865$meta->{'file_parent'} : unquote($meta->{'filename'});6866my$blamed= href(action =>'blame',6867 file_name =>$linenr_filename,6868 hash_base =>$linenr_commit);6869print"<td class=\"linenr\">";6870print$cgi->a({ -href =>"$blamed#l$orig_lineno",6871-class=>"linenr"},6872 esc_html($lineno));6873print"</td>";6874print"<td class=\"pre\">". esc_html($data) ."</td>\n";6875print"</tr>\n";6876}# end while68776878}68796880# footer6881print"</tbody>\n".6882"</table>\n";# class="blame"6883print"</div>\n";# class="blame_body"6884close$fd6885or print"Reading blob failed\n";68866887 git_footer_html();6888}68896890sub git_blame {6891 git_blame_common();6892}68936894sub git_blame_incremental {6895 git_blame_common('incremental');6896}68976898sub git_blame_data {6899 git_blame_common('data');6900}69016902sub git_tags {6903my$head= git_get_head_hash($project);6904 git_header_html();6905 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6906 git_print_header_div('summary',$project);69076908my@tagslist= git_get_tags_list();6909if(@tagslist) {6910 git_tags_body(\@tagslist);6911}6912 git_footer_html();6913}69146915sub git_heads {6916my$head= git_get_head_hash($project);6917 git_header_html();6918 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6919 git_print_header_div('summary',$project);69206921my@headslist= git_get_heads_list();6922if(@headslist) {6923 git_heads_body(\@headslist,$head);6924}6925 git_footer_html();6926}69276928# used both for single remote view and for list of all the remotes6929sub git_remotes {6930 gitweb_check_feature('remote_heads')6931or die_error(403,"Remote heads view is disabled");69326933my$head= git_get_head_hash($project);6934my$remote=$input_params{'hash'};69356936my$remotedata= git_get_remotes_list($remote);6937 die_error(500,"Unable to get remote information")unlessdefined$remotedata;69386939unless(%$remotedata) {6940 die_error(404,defined$remote?6941"Remote$remotenot found":6942"No remotes found");6943}69446945 git_header_html(undef,undef, -action_extra =>$remote);6946 git_print_page_nav('','',$head,undef,$head,6947 format_ref_views($remote?'':'remotes'));69486949 fill_remote_heads($remotedata);6950if(defined$remote) {6951 git_print_header_div('remotes',"$remoteremote for$project");6952 git_remote_block($remote,$remotedata->{$remote},undef,$head);6953}else{6954 git_print_header_div('summary',"$projectremotes");6955 git_remotes_body($remotedata,undef,$head);6956}69576958 git_footer_html();6959}69606961sub git_blob_plain {6962my$type=shift;6963my$expires;69646965if(!defined$hash) {6966if(defined$file_name) {6967my$base=$hash_base|| git_get_head_hash($project);6968$hash= git_get_hash_by_path($base,$file_name,"blob")6969or die_error(404,"Cannot find file");6970}else{6971 die_error(400,"No file name defined");6972}6973}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6974# blobs defined by non-textual hash id's can be cached6975$expires="+1d";6976}69776978open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6979or die_error(500,"Open git-cat-file blob '$hash' failed");69806981# content-type (can include charset)6982$type= blob_contenttype($fd,$file_name,$type);69836984# "save as" filename, even when no $file_name is given6985my$save_as="$hash";6986if(defined$file_name) {6987$save_as=$file_name;6988}elsif($type=~m/^text\//) {6989$save_as.='.txt';6990}69916992# With XSS prevention on, blobs of all types except a few known safe6993# ones are served with "Content-Disposition: attachment" to make sure6994# they don't run in our security domain. For certain image types,6995# blob view writes an <img> tag referring to blob_plain view, and we6996# want to be sure not to break that by serving the image as an6997# attachment (though Firefox 3 doesn't seem to care).6998my$sandbox=$prevent_xss&&6999$type!~m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;70007001# serve text/* as text/plain7002if($prevent_xss&&7003($type=~m!^text/[a-z]+\b(.*)$!||7004($type=~m!^[a-z]+/[a-z]\+xml\b(.*)$!&& -T $fd))) {7005my$rest=$1;7006$rest=defined$rest?$rest:'';7007$type="text/plain$rest";7008}70097010print$cgi->header(7011-type =>$type,7012-expires =>$expires,7013-content_disposition =>7014($sandbox?'attachment':'inline')7015.'; filename="'.$save_as.'"');7016local$/=undef;7017binmode STDOUT,':raw';7018print<$fd>;7019binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi7020close$fd;7021}70227023sub git_blob {7024my$expires;70257026if(!defined$hash) {7027if(defined$file_name) {7028my$base=$hash_base|| git_get_head_hash($project);7029$hash= git_get_hash_by_path($base,$file_name,"blob")7030or die_error(404,"Cannot find file");7031}else{7032 die_error(400,"No file name defined");7033}7034}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {7035# blobs defined by non-textual hash id's can be cached7036$expires="+1d";7037}70387039my$have_blame= gitweb_check_feature('blame');7040open my$fd,"-|", git_cmd(),"cat-file","blob",$hash7041or die_error(500,"Couldn't cat$file_name,$hash");7042my$mimetype= blob_mimetype($fd,$file_name);7043# use 'blob_plain' (aka 'raw') view for files that cannot be displayed7044if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {7045close$fd;7046return git_blob_plain($mimetype);7047}7048# we can have blame only for text/* mimetype7049$have_blame&&= ($mimetype=~m!^text/!);70507051my$highlight= gitweb_check_feature('highlight');7052my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);7053$fd= run_highlighter($fd,$highlight,$syntax)7054if$syntax;70557056 git_header_html(undef,$expires);7057my$formats_nav='';7058if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7059if(defined$file_name) {7060if($have_blame) {7061$formats_nav.=7062$cgi->a({-href => href(action=>"blame", -replay=>1)},7063"blame") .7064" | ";7065}7066$formats_nav.=7067$cgi->a({-href => href(action=>"history", -replay=>1)},7068"history") .7069" | ".7070$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},7071"raw") .7072" | ".7073$cgi->a({-href => href(action=>"blob",7074 hash_base=>"HEAD", file_name=>$file_name)},7075"HEAD");7076}else{7077$formats_nav.=7078$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},7079"raw");7080}7081 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7082 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7083}else{7084print"<div class=\"page_nav\">\n".7085"<br/><br/></div>\n".7086"<div class=\"title\">".esc_html($hash)."</div>\n";7087}7088 git_print_page_path($file_name,"blob",$hash_base);7089print"<div class=\"page_body\">\n";7090if($mimetype=~m!^image/!) {7091print qq!<img type="!.esc_attr($mimetype).qq!"!;7092if($file_name) {7093print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;7094}7095print qq! src="! .7096 href(action=>"blob_plain", hash=>$hash,7097 hash_base=>$hash_base, file_name=>$file_name) .7098 qq!"/>\n!;7099}else{7100my$nr;7101while(my$line= <$fd>) {7102chomp$line;7103$nr++;7104$line= untabify($line);7105printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,7106$nr, esc_attr(href(-replay =>1)),$nr,$nr,7107$syntax? sanitize($line) : esc_html($line, -nbsp=>1);7108}7109}7110close$fd7111or print"Reading blob failed.\n";7112print"</div>";7113 git_footer_html();7114}71157116sub git_tree {7117if(!defined$hash_base) {7118$hash_base="HEAD";7119}7120if(!defined$hash) {7121if(defined$file_name) {7122$hash= git_get_hash_by_path($hash_base,$file_name,"tree");7123}else{7124$hash=$hash_base;7125}7126}7127 die_error(404,"No such tree")unlessdefined($hash);71287129my$show_sizes= gitweb_check_feature('show-sizes');7130my$have_blame= gitweb_check_feature('blame');71317132my@entries= ();7133{7134local$/="\0";7135open my$fd,"-|", git_cmd(),"ls-tree",'-z',7136($show_sizes?'-l': ()),@extra_options,$hash7137or die_error(500,"Open git-ls-tree failed");7138@entries=map{chomp;$_} <$fd>;7139close$fd7140or die_error(404,"Reading tree failed");7141}71427143my$refs= git_get_references();7144my$ref= format_ref_marker($refs,$hash_base);7145 git_header_html();7146my$basedir='';7147if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7148my@views_nav= ();7149if(defined$file_name) {7150push@views_nav,7151$cgi->a({-href => href(action=>"history", -replay=>1)},7152"history"),7153$cgi->a({-href => href(action=>"tree",7154 hash_base=>"HEAD", file_name=>$file_name)},7155"HEAD"),7156}7157my$snapshot_links= format_snapshot_links($hash);7158if(defined$snapshot_links) {7159# FIXME: Should be available when we have no hash base as well.7160push@views_nav,$snapshot_links;7161}7162 git_print_page_nav('tree','',$hash_base,undef,undef,7163join(' | ',@views_nav));7164 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);7165}else{7166undef$hash_base;7167print"<div class=\"page_nav\">\n";7168print"<br/><br/></div>\n";7169print"<div class=\"title\">".esc_html($hash)."</div>\n";7170}7171if(defined$file_name) {7172$basedir=$file_name;7173if($basedirne''&&substr($basedir, -1)ne'/') {7174$basedir.='/';7175}7176 git_print_page_path($file_name,'tree',$hash_base);7177}7178print"<div class=\"page_body\">\n";7179print"<table class=\"tree\">\n";7180my$alternate=1;7181# '..' (top directory) link if possible7182if(defined$hash_base&&7183defined$file_name&&$file_name=~m![^/]+$!) {7184if($alternate) {7185print"<tr class=\"dark\">\n";7186}else{7187print"<tr class=\"light\">\n";7188}7189$alternate^=1;71907191my$up=$file_name;7192$up=~s!/?[^/]+$!!;7193undef$upunless$up;7194# based on git_print_tree_entry7195print'<td class="mode">'. mode_str('040000') ."</td>\n";7196print'<td class="size"> </td>'."\n"if$show_sizes;7197print'<td class="list">';7198print$cgi->a({-href => href(action=>"tree",7199 hash_base=>$hash_base,7200 file_name=>$up)},7201"..");7202print"</td>\n";7203print"<td class=\"link\"></td>\n";72047205print"</tr>\n";7206}7207foreachmy$line(@entries) {7208my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);72097210if($alternate) {7211print"<tr class=\"dark\">\n";7212}else{7213print"<tr class=\"light\">\n";7214}7215$alternate^=1;72167217 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);72187219print"</tr>\n";7220}7221print"</table>\n".7222"</div>";7223 git_footer_html();7224}72257226sub snapshot_name {7227my($project,$hash) =@_;72287229# path/to/project.git -> project7230# path/to/project/.git -> project7231my$name= to_utf8($project);7232$name=~ s,([^/])/*\.git$,$1,;7233$name= basename($name);7234# sanitize name7235$name=~s/[[:cntrl:]]/?/g;72367237my$ver=$hash;7238if($hash=~/^[0-9a-fA-F]+$/) {7239# shorten SHA-1 hash7240my$full_hash= git_get_full_hash($project,$hash);7241if($full_hash=~/^$hash/&&length($hash) >7) {7242$ver= git_get_short_hash($project,$hash);7243}7244}elsif($hash=~m!^refs/tags/(.*)$!) {7245# tags don't need shortened SHA-1 hash7246$ver=$1;7247}else{7248# branches and other need shortened SHA-1 hash7249my$strip_refs=join'|',map{quotemeta} get_branch_refs();7250if($hash=~m!^refs/($strip_refs|remotes)/(.*)$!) {7251$ver=$1;7252}7253$ver.='-'. git_get_short_hash($project,$hash);7254}7255# in case of hierarchical branch names7256$ver=~s!/!.!g;72577258# name = project-version_string7259$name="$name-$ver";72607261returnwantarray? ($name,$name) :$name;7262}72637264sub exit_if_unmodified_since {7265my($latest_epoch) =@_;7266our$cgi;72677268my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7269if(defined$if_modified) {7270my$since;7271if(eval{require HTTP::Date;1; }) {7272$since= HTTP::Date::str2time($if_modified);7273}elsif(eval{require Time::ParseDate;1; }) {7274$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7275}7276if(defined$since&&$latest_epoch<=$since) {7277my%latest_date= parse_date($latest_epoch);7278print$cgi->header(7279-last_modified =>$latest_date{'rfc2822'},7280-status =>'304 Not Modified');7281goto DONE_GITWEB;7282}7283}7284}72857286sub git_snapshot {7287my$format=$input_params{'snapshot_format'};7288if(!@snapshot_fmts) {7289 die_error(403,"Snapshots not allowed");7290}7291# default to first supported snapshot format7292$format||=$snapshot_fmts[0];7293if($format!~m/^[a-z0-9]+$/) {7294 die_error(400,"Invalid snapshot format parameter");7295}elsif(!exists($known_snapshot_formats{$format})) {7296 die_error(400,"Unknown snapshot format");7297}elsif($known_snapshot_formats{$format}{'disabled'}) {7298 die_error(403,"Snapshot format not allowed");7299}elsif(!grep($_eq$format,@snapshot_fmts)) {7300 die_error(403,"Unsupported snapshot format");7301}73027303my$type= git_get_type("$hash^{}");7304if(!$type) {7305 die_error(404,'Object does not exist');7306}elsif($typeeq'blob') {7307 die_error(400,'Object is not a tree-ish');7308}73097310my($name,$prefix) = snapshot_name($project,$hash);7311my$filename="$name$known_snapshot_formats{$format}{'suffix'}";73127313my%co= parse_commit($hash);7314 exit_if_unmodified_since($co{'committer_epoch'})if%co;73157316my$cmd= quote_command(7317 git_cmd(),'archive',7318"--format=$known_snapshot_formats{$format}{'format'}",7319"--prefix=$prefix/",$hash);7320if(exists$known_snapshot_formats{$format}{'compressor'}) {7321$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});7322}73237324$filename=~s/(["\\])/\\$1/g;7325my%latest_date;7326if(%co) {7327%latest_date= parse_date($co{'committer_epoch'},$co{'committer_tz'});7328}73297330print$cgi->header(7331-type =>$known_snapshot_formats{$format}{'type'},7332-content_disposition =>'inline; filename="'.$filename.'"',7333%co? (-last_modified =>$latest_date{'rfc2822'}) : (),7334-status =>'200 OK');73357336open my$fd,"-|",$cmd7337or die_error(500,"Execute git-archive failed");7338binmode STDOUT,':raw';7339print<$fd>;7340binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi7341close$fd;7342}73437344sub git_log_generic {7345my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;73467347my$head= git_get_head_hash($project);7348if(!defined$base) {7349$base=$head;7350}7351if(!defined$page) {7352$page=0;7353}7354my$refs= git_get_references();73557356my$commit_hash=$base;7357if(defined$parent) {7358$commit_hash="$parent..$base";7359}7360my@commitlist=7361 parse_commits($commit_hash,101, (100*$page),7362defined$file_name? ($file_name,"--full-history") : ());73637364my$ftype;7365if(!defined$file_hash&&defined$file_name) {7366# some commits could have deleted file in question,7367# and not have it in tree, but one of them has to have it7368for(my$i=0;$i<@commitlist;$i++) {7369$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);7370last ifdefined$file_hash;7371}7372}7373if(defined$file_hash) {7374$ftype= git_get_type($file_hash);7375}7376if(defined$file_name&& !defined$ftype) {7377 die_error(500,"Unknown type of object");7378}7379my%co;7380if(defined$file_name) {7381%co= parse_commit($base)7382or die_error(404,"Unknown commit object");7383}738473857386my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);7387my$next_link='';7388if($#commitlist>=100) {7389$next_link=7390$cgi->a({-href => href(-replay=>1, page=>$page+1),7391-accesskey =>"n", -title =>"Alt-n"},"next");7392}7393my$patch_max= gitweb_get_feature('patches');7394if($patch_max&& !defined$file_name) {7395if($patch_max<0||@commitlist<=$patch_max) {7396$paging_nav.=" ⋅ ".7397$cgi->a({-href => href(action=>"patches", -replay=>1)},7398"patches");7399}7400}74017402 git_header_html();7403 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);7404if(defined$file_name) {7405 git_print_header_div('commit', esc_html($co{'title'}),$base);7406}else{7407 git_print_header_div('summary',$project)7408}7409 git_print_page_path($file_name,$ftype,$hash_base)7410if(defined$file_name);74117412$body_subr->(\@commitlist,0,99,$refs,$next_link,7413$file_name,$file_hash,$ftype);74147415 git_footer_html();7416}74177418sub git_log {7419 git_log_generic('log', \&git_log_body,7420$hash,$hash_parent);7421}74227423sub git_commit {7424$hash||=$hash_base||"HEAD";7425my%co= parse_commit($hash)7426or die_error(404,"Unknown commit object");74277428my$parent=$co{'parent'};7429my$parents=$co{'parents'};# listref74307431# we need to prepare $formats_nav before any parameter munging7432my$formats_nav;7433if(!defined$parent) {7434# --root commitdiff7435$formats_nav.='(initial)';7436}elsif(@$parents==1) {7437# single parent commit7438$formats_nav.=7439'(parent: '.7440$cgi->a({-href => href(action=>"commit",7441 hash=>$parent)},7442 esc_html(substr($parent,0,7))) .7443')';7444}else{7445# merge commit7446$formats_nav.=7447'(merge: '.7448join(' ',map{7449$cgi->a({-href => href(action=>"commit",7450 hash=>$_)},7451 esc_html(substr($_,0,7)));7452}@$parents) .7453')';7454}7455if(gitweb_check_feature('patches') &&@$parents<=1) {7456$formats_nav.=" | ".7457$cgi->a({-href => href(action=>"patch", -replay=>1)},7458"patch");7459}74607461if(!defined$parent) {7462$parent="--root";7463}7464my@difftree;7465open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",7466@diff_opts,7467(@$parents<=1?$parent:'-c'),7468$hash,"--"7469or die_error(500,"Open git-diff-tree failed");7470@difftree=map{chomp;$_} <$fd>;7471close$fdor die_error(404,"Reading git-diff-tree failed");74727473# non-textual hash id's can be cached7474my$expires;7475if($hash=~m/^[0-9a-fA-F]{40}$/) {7476$expires="+1d";7477}7478my$refs= git_get_references();7479my$ref= format_ref_marker($refs,$co{'id'});74807481 git_header_html(undef,$expires);7482 git_print_page_nav('commit','',7483$hash,$co{'tree'},$hash,7484$formats_nav);74857486if(defined$co{'parent'}) {7487 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);7488}else{7489 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);7490}7491print"<div class=\"title_text\">\n".7492"<table class=\"object_header\">\n";7493 git_print_authorship_rows(\%co);7494print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";7495print"<tr>".7496"<td>tree</td>".7497"<td class=\"sha1\">".7498$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),7499class=>"list"},$co{'tree'}) .7500"</td>".7501"<td class=\"link\">".7502$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},7503"tree");7504my$snapshot_links= format_snapshot_links($hash);7505if(defined$snapshot_links) {7506print" | ".$snapshot_links;7507}7508print"</td>".7509"</tr>\n";75107511foreachmy$par(@$parents) {7512print"<tr>".7513"<td>parent</td>".7514"<td class=\"sha1\">".7515$cgi->a({-href => href(action=>"commit", hash=>$par),7516class=>"list"},$par) .7517"</td>".7518"<td class=\"link\">".7519$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .7520" | ".7521$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .7522"</td>".7523"</tr>\n";7524}7525print"</table>".7526"</div>\n";75277528print"<div class=\"page_body\">\n";7529 git_print_log($co{'comment'});7530print"</div>\n";75317532 git_difftree_body(\@difftree,$hash,@$parents);75337534 git_footer_html();7535}75367537sub git_object {7538# object is defined by:7539# - hash or hash_base alone7540# - hash_base and file_name7541my$type;75427543# - hash or hash_base alone7544if($hash|| ($hash_base&& !defined$file_name)) {7545my$object_id=$hash||$hash_base;75467547open my$fd,"-|", quote_command(7548 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'7549or die_error(404,"Object does not exist");7550$type= <$fd>;7551chomp$type;7552close$fd7553or die_error(404,"Object does not exist");75547555# - hash_base and file_name7556}elsif($hash_base&&defined$file_name) {7557$file_name=~ s,/+$,,;75587559system(git_cmd(),"cat-file",'-e',$hash_base) ==07560or die_error(404,"Base object does not exist");75617562# here errors should not happen7563open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name7564or die_error(500,"Open git-ls-tree failed");7565my$line= <$fd>;7566close$fd;75677568#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'7569unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {7570 die_error(404,"File or directory for given base does not exist");7571}7572$type=$2;7573$hash=$3;7574}else{7575 die_error(400,"Not enough information to find object");7576}75777578print$cgi->redirect(-uri => href(action=>$type, -full=>1,7579 hash=>$hash, hash_base=>$hash_base,7580 file_name=>$file_name),7581-status =>'302 Found');7582}75837584sub git_blobdiff {7585my$format=shift||'html';7586my$diff_style=$input_params{'diff_style'} ||'inline';75877588my$fd;7589my@difftree;7590my%diffinfo;7591my$expires;75927593# preparing $fd and %diffinfo for git_patchset_body7594# new style URI7595if(defined$hash_base&&defined$hash_parent_base) {7596if(defined$file_name) {7597# read raw output7598open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7599$hash_parent_base,$hash_base,7600"--", (defined$file_parent?$file_parent: ()),$file_name7601or die_error(500,"Open git-diff-tree failed");7602@difftree=map{chomp;$_} <$fd>;7603close$fd7604or die_error(404,"Reading git-diff-tree failed");7605@difftree7606or die_error(404,"Blob diff not found");76077608}elsif(defined$hash&&7609$hash=~/[0-9a-fA-F]{40}/) {7610# try to find filename from $hash76117612# read filtered raw output7613open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7614$hash_parent_base,$hash_base,"--"7615or die_error(500,"Open git-diff-tree failed");7616@difftree=7617# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'7618# $hash == to_id7619grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}7620map{chomp;$_} <$fd>;7621close$fd7622or die_error(404,"Reading git-diff-tree failed");7623@difftree7624or die_error(404,"Blob diff not found");76257626}else{7627 die_error(400,"Missing one of the blob diff parameters");7628}76297630if(@difftree>1) {7631 die_error(400,"Ambiguous blob diff specification");7632}76337634%diffinfo= parse_difftree_raw_line($difftree[0]);7635$file_parent||=$diffinfo{'from_file'} ||$file_name;7636$file_name||=$diffinfo{'to_file'};76377638$hash_parent||=$diffinfo{'from_id'};7639$hash||=$diffinfo{'to_id'};76407641# non-textual hash id's can be cached7642if($hash_base=~m/^[0-9a-fA-F]{40}$/&&7643$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {7644$expires='+1d';7645}76467647# open patch output7648open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7649'-p', ($formateq'html'?"--full-index": ()),7650$hash_parent_base,$hash_base,7651"--", (defined$file_parent?$file_parent: ()),$file_name7652or die_error(500,"Open git-diff-tree failed");7653}76547655# old/legacy style URI -- not generated anymore since 1.4.3.7656if(!%diffinfo) {7657 die_error('404 Not Found',"Missing one of the blob diff parameters")7658}76597660# header7661if($formateq'html') {7662my$formats_nav=7663$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},7664"raw");7665$formats_nav.= diff_style_nav($diff_style);7666 git_header_html(undef,$expires);7667if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7668 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7669 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7670}else{7671print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";7672print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";7673}7674if(defined$file_name) {7675 git_print_page_path($file_name,"blob",$hash_base);7676}else{7677print"<div class=\"page_path\"></div>\n";7678}76797680}elsif($formateq'plain') {7681print$cgi->header(7682-type =>'text/plain',7683-charset =>'utf-8',7684-expires =>$expires,7685-content_disposition =>'inline; filename="'."$file_name".'.patch"');76867687print"X-Git-Url: ".$cgi->self_url() ."\n\n";76887689}else{7690 die_error(400,"Unknown blobdiff format");7691}76927693# patch7694if($formateq'html') {7695print"<div class=\"page_body\">\n";76967697 git_patchset_body($fd,$diff_style,7698[ \%diffinfo],$hash_base,$hash_parent_base);7699close$fd;77007701print"</div>\n";# class="page_body"7702 git_footer_html();77037704}else{7705while(my$line= <$fd>) {7706$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;7707$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;77087709print$line;77107711last if$line=~m!^\+\+\+!;7712}7713local$/=undef;7714print<$fd>;7715close$fd;7716}7717}77187719sub git_blobdiff_plain {7720 git_blobdiff('plain');7721}77227723# assumes that it is added as later part of already existing navigation,7724# so it returns "| foo | bar" rather than just "foo | bar"7725sub diff_style_nav {7726my($diff_style,$is_combined) =@_;7727$diff_style||='inline';77287729return""if($is_combined);77307731my@styles= (inline =>'inline','sidebyside'=>'side by side');7732my%styles=@styles;7733@styles=7734@styles[map{$_*2}0..$#styles/2];77357736returnjoin'',7737map{" | ".$_}7738map{7739$_eq$diff_style?$styles{$_} :7740$cgi->a({-href => href(-replay=>1, diff_style =>$_)},$styles{$_})7741}@styles;7742}77437744sub git_commitdiff {7745my%params=@_;7746my$format=$params{-format} ||'html';7747my$diff_style=$input_params{'diff_style'} ||'inline';77487749my($patch_max) = gitweb_get_feature('patches');7750if($formateq'patch') {7751 die_error(403,"Patch view not allowed")unless$patch_max;7752}77537754$hash||=$hash_base||"HEAD";7755my%co= parse_commit($hash)7756or die_error(404,"Unknown commit object");77577758# choose format for commitdiff for merge7759if(!defined$hash_parent&& @{$co{'parents'}} >1) {7760$hash_parent='--cc';7761}7762# we need to prepare $formats_nav before almost any parameter munging7763my$formats_nav;7764if($formateq'html') {7765$formats_nav=7766$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},7767"raw");7768if($patch_max&& @{$co{'parents'}} <=1) {7769$formats_nav.=" | ".7770$cgi->a({-href => href(action=>"patch", -replay=>1)},7771"patch");7772}7773$formats_nav.= diff_style_nav($diff_style, @{$co{'parents'}} >1);77747775if(defined$hash_parent&&7776$hash_parentne'-c'&&$hash_parentne'--cc') {7777# commitdiff with two commits given7778my$hash_parent_short=$hash_parent;7779if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {7780$hash_parent_short=substr($hash_parent,0,7);7781}7782$formats_nav.=7783' (from';7784for(my$i=0;$i< @{$co{'parents'}};$i++) {7785if($co{'parents'}[$i]eq$hash_parent) {7786$formats_nav.=' parent '. ($i+1);7787last;7788}7789}7790$formats_nav.=': '.7791$cgi->a({-href => href(-replay=>1,7792 hash=>$hash_parent, hash_base=>undef)},7793 esc_html($hash_parent_short)) .7794')';7795}elsif(!$co{'parent'}) {7796# --root commitdiff7797$formats_nav.=' (initial)';7798}elsif(scalar@{$co{'parents'}} ==1) {7799# single parent commit7800$formats_nav.=7801' (parent: '.7802$cgi->a({-href => href(-replay=>1,7803 hash=>$co{'parent'}, hash_base=>undef)},7804 esc_html(substr($co{'parent'},0,7))) .7805')';7806}else{7807# merge commit7808if($hash_parenteq'--cc') {7809$formats_nav.=' | '.7810$cgi->a({-href => href(-replay=>1,7811 hash=>$hash, hash_parent=>'-c')},7812'combined');7813}else{# $hash_parent eq '-c'7814$formats_nav.=' | '.7815$cgi->a({-href => href(-replay=>1,7816 hash=>$hash, hash_parent=>'--cc')},7817'compact');7818}7819$formats_nav.=7820' (merge: '.7821join(' ',map{7822$cgi->a({-href => href(-replay=>1,7823 hash=>$_, hash_base=>undef)},7824 esc_html(substr($_,0,7)));7825} @{$co{'parents'}} ) .7826')';7827}7828}78297830my$hash_parent_param=$hash_parent;7831if(!defined$hash_parent_param) {7832# --cc for multiple parents, --root for parentless7833$hash_parent_param=7834@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';7835}78367837# read commitdiff7838my$fd;7839my@difftree;7840if($formateq'html') {7841open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7842"--no-commit-id","--patch-with-raw","--full-index",7843$hash_parent_param,$hash,"--"7844or die_error(500,"Open git-diff-tree failed");78457846while(my$line= <$fd>) {7847chomp$line;7848# empty line ends raw part of diff-tree output7849last unless$line;7850push@difftree,scalar parse_difftree_raw_line($line);7851}78527853}elsif($formateq'plain') {7854open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7855'-p',$hash_parent_param,$hash,"--"7856or die_error(500,"Open git-diff-tree failed");7857}elsif($formateq'patch') {7858# For commit ranges, we limit the output to the number of7859# patches specified in the 'patches' feature.7860# For single commits, we limit the output to a single patch,7861# diverging from the git-format-patch default.7862my@commit_spec= ();7863if($hash_parent) {7864if($patch_max>0) {7865push@commit_spec,"-$patch_max";7866}7867push@commit_spec,'-n',"$hash_parent..$hash";7868}else{7869if($params{-single}) {7870push@commit_spec,'-1';7871}else{7872if($patch_max>0) {7873push@commit_spec,"-$patch_max";7874}7875push@commit_spec,"-n";7876}7877push@commit_spec,'--root',$hash;7878}7879open$fd,"-|", git_cmd(),"format-patch",@diff_opts,7880'--encoding=utf8','--stdout',@commit_spec7881or die_error(500,"Open git-format-patch failed");7882}else{7883 die_error(400,"Unknown commitdiff format");7884}78857886# non-textual hash id's can be cached7887my$expires;7888if($hash=~m/^[0-9a-fA-F]{40}$/) {7889$expires="+1d";7890}78917892# write commit message7893if($formateq'html') {7894my$refs= git_get_references();7895my$ref= format_ref_marker($refs,$co{'id'});78967897 git_header_html(undef,$expires);7898 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);7899 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);7900print"<div class=\"title_text\">\n".7901"<table class=\"object_header\">\n";7902 git_print_authorship_rows(\%co);7903print"</table>".7904"</div>\n";7905print"<div class=\"page_body\">\n";7906if(@{$co{'comment'}} >1) {7907print"<div class=\"log\">\n";7908 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);7909print"</div>\n";# class="log"7910}79117912}elsif($formateq'plain') {7913my$refs= git_get_references("tags");7914my$tagname= git_get_rev_name_tags($hash);7915my$filename= basename($project) ."-$hash.patch";79167917print$cgi->header(7918-type =>'text/plain',7919-charset =>'utf-8',7920-expires =>$expires,7921-content_disposition =>'inline; filename="'."$filename".'"');7922my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});7923print"From: ". to_utf8($co{'author'}) ."\n";7924print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";7925print"Subject: ". to_utf8($co{'title'}) ."\n";79267927print"X-Git-Tag:$tagname\n"if$tagname;7928print"X-Git-Url: ".$cgi->self_url() ."\n\n";79297930foreachmy$line(@{$co{'comment'}}) {7931print to_utf8($line) ."\n";7932}7933print"---\n\n";7934}elsif($formateq'patch') {7935my$filename= basename($project) ."-$hash.patch";79367937print$cgi->header(7938-type =>'text/plain',7939-charset =>'utf-8',7940-expires =>$expires,7941-content_disposition =>'inline; filename="'."$filename".'"');7942}79437944# write patch7945if($formateq'html') {7946my$use_parents= !defined$hash_parent||7947$hash_parenteq'-c'||$hash_parenteq'--cc';7948 git_difftree_body(\@difftree,$hash,7949$use_parents? @{$co{'parents'}} :$hash_parent);7950print"<br/>\n";79517952 git_patchset_body($fd,$diff_style,7953 \@difftree,$hash,7954$use_parents? @{$co{'parents'}} :$hash_parent);7955close$fd;7956print"</div>\n";# class="page_body"7957 git_footer_html();79587959}elsif($formateq'plain') {7960local$/=undef;7961print<$fd>;7962close$fd7963or print"Reading git-diff-tree failed\n";7964}elsif($formateq'patch') {7965local$/=undef;7966print<$fd>;7967close$fd7968or print"Reading git-format-patch failed\n";7969}7970}79717972sub git_commitdiff_plain {7973 git_commitdiff(-format =>'plain');7974}79757976# format-patch-style patches7977sub git_patch {7978 git_commitdiff(-format =>'patch', -single =>1);7979}79807981sub git_patches {7982 git_commitdiff(-format =>'patch');7983}79847985sub git_history {7986 git_log_generic('history', \&git_history_body,7987$hash_base,$hash_parent_base,7988$file_name,$hash);7989}79907991sub git_search {7992$searchtype||='commit';79937994# check if appropriate features are enabled7995 gitweb_check_feature('search')7996or die_error(403,"Search is disabled");7997if($searchtypeeq'pickaxe') {7998# pickaxe may take all resources of your box and run for several minutes7999# with every query - so decide by yourself how public you make this feature8000 gitweb_check_feature('pickaxe')8001or die_error(403,"Pickaxe search is disabled");8002}8003if($searchtypeeq'grep') {8004# grep search might be potentially CPU-intensive, too8005 gitweb_check_feature('grep')8006or die_error(403,"Grep search is disabled");8007}80088009if(!defined$searchtext) {8010 die_error(400,"Text field is empty");8011}8012if(!defined$hash) {8013$hash= git_get_head_hash($project);8014}8015my%co= parse_commit($hash);8016if(!%co) {8017 die_error(404,"Unknown commit object");8018}8019if(!defined$page) {8020$page=0;8021}80228023if($searchtypeeq'commit'||8024$searchtypeeq'author'||8025$searchtypeeq'committer') {8026 git_search_message(%co);8027}elsif($searchtypeeq'pickaxe') {8028 git_search_changes(%co);8029}elsif($searchtypeeq'grep') {8030 git_search_files(%co);8031}else{8032 die_error(400,"Unknown search type");8033}8034}80358036sub git_search_help {8037 git_header_html();8038 git_print_page_nav('','',$hash,$hash,$hash);8039print<<EOT;8040<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without8041regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,8042the pattern entered is recognized as the POSIX extended8043<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case8044insensitive).</p>8045<dl>8046<dt><b>commit</b></dt>8047<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>8048EOT8049my$have_grep= gitweb_check_feature('grep');8050if($have_grep) {8051print<<EOT;8052<dt><b>grep</b></dt>8053<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing8054 a different one) are searched for the given pattern. On large trees, this search can take8055a while and put some strain on the server, so please use it with some consideration. Note that8056due to git-grep peculiarity, currently if regexp mode is turned off, the matches are8057case-sensitive.</dd>8058EOT8059}8060print<<EOT;8061<dt><b>author</b></dt>8062<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>8063<dt><b>committer</b></dt>8064<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>8065EOT8066my$have_pickaxe= gitweb_check_feature('pickaxe');8067if($have_pickaxe) {8068print<<EOT;8069<dt><b>pickaxe</b></dt>8070<dd>All commits that caused the string to appear or disappear from any file (changes that8071added, removed or "modified" the string) will be listed. This search can take a while and8072takes a lot of strain on the server, so please use it wisely. Note that since you may be8073interested even in changes just changing the case as well, this search is case sensitive.</dd>8074EOT8075}8076print"</dl>\n";8077 git_footer_html();8078}80798080sub git_shortlog {8081 git_log_generic('shortlog', \&git_shortlog_body,8082$hash,$hash_parent);8083}80848085## ......................................................................8086## feeds (RSS, Atom; OPML)80878088sub git_feed {8089my$format=shift||'atom';8090my$have_blame= gitweb_check_feature('blame');80918092# Atom: http://www.atomenabled.org/developers/syndication/8093# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ8094if($formatne'rss'&&$formatne'atom') {8095 die_error(400,"Unknown web feed format");8096}80978098# log/feed of current (HEAD) branch, log of given branch, history of file/directory8099my$head=$hash||'HEAD';8100my@commitlist= parse_commits($head,150,0,$file_name);81018102my%latest_commit;8103my%latest_date;8104my$content_type="application/$format+xml";8105if(defined$cgi->http('HTTP_ACCEPT') &&8106$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {8107# browser (feed reader) prefers text/xml8108$content_type='text/xml';8109}8110if(defined($commitlist[0])) {8111%latest_commit= %{$commitlist[0]};8112my$latest_epoch=$latest_commit{'committer_epoch'};8113 exit_if_unmodified_since($latest_epoch);8114%latest_date= parse_date($latest_epoch,$latest_commit{'committer_tz'});8115}8116print$cgi->header(8117-type =>$content_type,8118-charset =>'utf-8',8119%latest_date? (-last_modified =>$latest_date{'rfc2822'}) : (),8120-status =>'200 OK');81218122# Optimization: skip generating the body if client asks only8123# for Last-Modified date.8124return if($cgi->request_method()eq'HEAD');81258126# header variables8127my$title="$site_name-$project/$action";8128my$feed_type='log';8129if(defined$hash) {8130$title.=" - '$hash'";8131$feed_type='branch log';8132if(defined$file_name) {8133$title.=" ::$file_name";8134$feed_type='history';8135}8136}elsif(defined$file_name) {8137$title.=" -$file_name";8138$feed_type='history';8139}8140$title.="$feed_type";8141$title= esc_html($title);8142my$descr= git_get_project_description($project);8143if(defined$descr) {8144$descr= esc_html($descr);8145}else{8146$descr="$project".8147($formateq'rss'?'RSS':'Atom') .8148" feed";8149}8150my$owner= git_get_project_owner($project);8151$owner= esc_html($owner);81528153#header8154my$alt_url;8155if(defined$file_name) {8156$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);8157}elsif(defined$hash) {8158$alt_url= href(-full=>1, action=>"log", hash=>$hash);8159}else{8160$alt_url= href(-full=>1, action=>"summary");8161}8162print qq!<?xml version="1.0" encoding="utf-8"?>\n!;8163if($formateq'rss') {8164print<<XML;8165<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">8166<channel>8167XML8168print"<title>$title</title>\n".8169"<link>$alt_url</link>\n".8170"<description>$descr</description>\n".8171"<language>en</language>\n".8172# project owner is responsible for 'editorial' content8173"<managingEditor>$owner</managingEditor>\n";8174if(defined$logo||defined$favicon) {8175# prefer the logo to the favicon, since RSS8176# doesn't allow both8177my$img= esc_url($logo||$favicon);8178print"<image>\n".8179"<url>$img</url>\n".8180"<title>$title</title>\n".8181"<link>$alt_url</link>\n".8182"</image>\n";8183}8184if(%latest_date) {8185print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";8186print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";8187}8188print"<generator>gitweb v.$version/$git_version</generator>\n";8189}elsif($formateq'atom') {8190print<<XML;8191<feed xmlns="http://www.w3.org/2005/Atom">8192XML8193print"<title>$title</title>\n".8194"<subtitle>$descr</subtitle>\n".8195'<link rel="alternate" type="text/html" href="'.8196$alt_url.'" />'."\n".8197'<link rel="self" type="'.$content_type.'" href="'.8198$cgi->self_url() .'" />'."\n".8199"<id>". href(-full=>1) ."</id>\n".8200# use project owner for feed author8201"<author><name>$owner</name></author>\n";8202if(defined$favicon) {8203print"<icon>". esc_url($favicon) ."</icon>\n";8204}8205if(defined$logo) {8206# not twice as wide as tall: 72 x 27 pixels8207print"<logo>". esc_url($logo) ."</logo>\n";8208}8209if(!%latest_date) {8210# dummy date to keep the feed valid until commits trickle in:8211print"<updated>1970-01-01T00:00:00Z</updated>\n";8212}else{8213print"<updated>$latest_date{'iso-8601'}</updated>\n";8214}8215print"<generator version='$version/$git_version'>gitweb</generator>\n";8216}82178218# contents8219for(my$i=0;$i<=$#commitlist;$i++) {8220my%co= %{$commitlist[$i]};8221my$commit=$co{'id'};8222# we read 150, we always show 30 and the ones more recent than 48 hours8223if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {8224last;8225}8226my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});82278228# get list of changed files8229open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,8230$co{'parent'} ||"--root",8231$co{'id'},"--", (defined$file_name?$file_name: ())8232ornext;8233my@difftree=map{chomp;$_} <$fd>;8234close$fd8235ornext;82368237# print element (entry, item)8238my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);8239if($formateq'rss') {8240print"<item>\n".8241"<title>". esc_html($co{'title'}) ."</title>\n".8242"<author>". esc_html($co{'author'}) ."</author>\n".8243"<pubDate>$cd{'rfc2822'}</pubDate>\n".8244"<guid isPermaLink=\"true\">$co_url</guid>\n".8245"<link>$co_url</link>\n".8246"<description>". esc_html($co{'title'}) ."</description>\n".8247"<content:encoded>".8248"<![CDATA[\n";8249}elsif($formateq'atom') {8250print"<entry>\n".8251"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".8252"<updated>$cd{'iso-8601'}</updated>\n".8253"<author>\n".8254" <name>". esc_html($co{'author_name'}) ."</name>\n";8255if($co{'author_email'}) {8256print" <email>". esc_html($co{'author_email'}) ."</email>\n";8257}8258print"</author>\n".8259# use committer for contributor8260"<contributor>\n".8261" <name>". esc_html($co{'committer_name'}) ."</name>\n";8262if($co{'committer_email'}) {8263print" <email>". esc_html($co{'committer_email'}) ."</email>\n";8264}8265print"</contributor>\n".8266"<published>$cd{'iso-8601'}</published>\n".8267"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".8268"<id>$co_url</id>\n".8269"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".8270"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";8271}8272my$comment=$co{'comment'};8273print"<pre>\n";8274foreachmy$line(@$comment) {8275$line= esc_html($line);8276print"$line\n";8277}8278print"</pre><ul>\n";8279foreachmy$difftree_line(@difftree) {8280my%difftree= parse_difftree_raw_line($difftree_line);8281next if!$difftree{'from_id'};82828283my$file=$difftree{'file'} ||$difftree{'to_file'};82848285print"<li>".8286"[".8287$cgi->a({-href => href(-full=>1, action=>"blobdiff",8288 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},8289 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},8290 file_name=>$file, file_parent=>$difftree{'from_file'}),8291-title =>"diff"},'D');8292if($have_blame) {8293print$cgi->a({-href => href(-full=>1, action=>"blame",8294 file_name=>$file, hash_base=>$commit),8295-title =>"blame"},'B');8296}8297# if this is not a feed of a file history8298if(!defined$file_name||$file_namene$file) {8299print$cgi->a({-href => href(-full=>1, action=>"history",8300 file_name=>$file, hash=>$commit),8301-title =>"history"},'H');8302}8303$file= esc_path($file);8304print"] ".8305"$file</li>\n";8306}8307if($formateq'rss') {8308print"</ul>]]>\n".8309"</content:encoded>\n".8310"</item>\n";8311}elsif($formateq'atom') {8312print"</ul>\n</div>\n".8313"</content>\n".8314"</entry>\n";8315}8316}83178318# end of feed8319if($formateq'rss') {8320print"</channel>\n</rss>\n";8321}elsif($formateq'atom') {8322print"</feed>\n";8323}8324}83258326sub git_rss {8327 git_feed('rss');8328}83298330sub git_atom {8331 git_feed('atom');8332}83338334sub git_opml {8335my@list= git_get_projects_list($project_filter,$strict_export);8336if(!@list) {8337 die_error(404,"No projects found");8338}83398340print$cgi->header(8341-type =>'text/xml',8342-charset =>'utf-8',8343-content_disposition =>'inline; filename="opml.xml"');83448345my$title= esc_html($site_name);8346my$filter=" within subdirectory ";8347if(defined$project_filter) {8348$filter.= esc_html($project_filter);8349}else{8350$filter="";8351}8352print<<XML;8353<?xml version="1.0" encoding="utf-8"?>8354<opml version="1.0">8355<head>8356 <title>$titleOPML Export$filter</title>8357</head>8358<body>8359<outline text="git RSS feeds">8360XML83618362foreachmy$pr(@list) {8363my%proj=%$pr;8364my$head= git_get_head_hash($proj{'path'});8365if(!defined$head) {8366next;8367}8368$git_dir="$projectroot/$proj{'path'}";8369my%co= parse_commit($head);8370if(!%co) {8371next;8372}83738374my$path= esc_html(chop_str($proj{'path'},25,5));8375my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);8376my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);8377print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";8378}8379print<<XML;8380</outline>8381</body>8382</opml>8383XML8384}