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; 13# handle ACL in file access tests 14use filetest 'access'; 15use CGI qw(:standard :escapeHTML -nosticky); 16use CGI::Util qw(unescape); 17use CGI::Carp qw(fatalsToBrowser set_message); 18use Encode; 19use Fcntl ':mode'; 20use File::Find qw(); 21use File::Basename qw(basename); 22use Time::HiRes qw(gettimeofday tv_interval); 23use Digest::MD5 qw(md5_hex); 24 25binmode STDOUT,':utf8'; 26 27if(!defined($CGI::VERSION) ||$CGI::VERSION <4.08) { 28eval'sub CGI::multi_param { CGI::param(@_) }' 29} 30 31our$t0= [ gettimeofday() ]; 32our$number_of_git_cmds=0; 33 34BEGIN{ 35 CGI->compile()if$ENV{'MOD_PERL'}; 36} 37 38our$version="++GIT_VERSION++"; 39 40our($my_url,$my_uri,$base_url,$path_info,$home_link); 41sub evaluate_uri { 42our$cgi; 43 44our$my_url=$cgi->url(); 45our$my_uri=$cgi->url(-absolute =>1); 46 47# Base URL for relative URLs in gitweb ($logo, $favicon, ...), 48# needed and used only for URLs with nonempty PATH_INFO 49our$base_url=$my_url; 50 51# When the script is used as DirectoryIndex, the URL does not contain the name 52# of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we 53# have to do it ourselves. We make $path_info global because it's also used 54# later on. 55# 56# Another issue with the script being the DirectoryIndex is that the resulting 57# $my_url data is not the full script URL: this is good, because we want 58# generated links to keep implying the script name if it wasn't explicitly 59# indicated in the URL we're handling, but it means that $my_url cannot be used 60# as base URL. 61# Therefore, if we needed to strip PATH_INFO, then we know that we have 62# to build the base URL ourselves: 63our$path_info= decode_utf8($ENV{"PATH_INFO"}); 64if($path_info) { 65# $path_info has already been URL-decoded by the web server, but 66# $my_url and $my_uri have not. URL-decode them so we can properly 67# strip $path_info. 68$my_url= unescape($my_url); 69$my_uri= unescape($my_uri); 70if($my_url=~ s,\Q$path_info\E$,, && 71$my_uri=~ s,\Q$path_info\E$,, && 72defined$ENV{'SCRIPT_NAME'}) { 73$base_url=$cgi->url(-base =>1) .$ENV{'SCRIPT_NAME'}; 74} 75} 76 77# target of the home link on top of all pages 78our$home_link=$my_uri||"/"; 79} 80 81# core git executable to use 82# this can just be "git" if your webserver has a sensible PATH 83our$GIT="++GIT_BINDIR++/git"; 84 85# absolute fs-path which will be prepended to the project path 86#our $projectroot = "/pub/scm"; 87our$projectroot="++GITWEB_PROJECTROOT++"; 88 89# fs traversing limit for getting project list 90# the number is relative to the projectroot 91our$project_maxdepth="++GITWEB_PROJECT_MAXDEPTH++"; 92 93# string of the home link on top of all pages 94our$home_link_str="++GITWEB_HOME_LINK_STR++"; 95 96# extra breadcrumbs preceding the home link 97our@extra_breadcrumbs= (); 98 99# name of your site or organization to appear in page titles 100# replace this with something more descriptive for clearer bookmarks 101our$site_name="++GITWEB_SITENAME++" 102|| ($ENV{'SERVER_NAME'} ||"Untitled") ." Git"; 103 104# html snippet to include in the <head> section of each page 105our$site_html_head_string="++GITWEB_SITE_HTML_HEAD_STRING++"; 106# filename of html text to include at top of each page 107our$site_header="++GITWEB_SITE_HEADER++"; 108# html text to include at home page 109our$home_text="++GITWEB_HOMETEXT++"; 110# filename of html text to include at bottom of each page 111our$site_footer="++GITWEB_SITE_FOOTER++"; 112 113# URI of stylesheets 114our@stylesheets= ("++GITWEB_CSS++"); 115# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG. 116our$stylesheet=undef; 117# URI of GIT logo (72x27 size) 118our$logo="++GITWEB_LOGO++"; 119# URI of GIT favicon, assumed to be image/png type 120our$favicon="++GITWEB_FAVICON++"; 121# URI of gitweb.js (JavaScript code for gitweb) 122our$javascript="++GITWEB_JS++"; 123 124# URI and label (title) of GIT logo link 125#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/"; 126#our $logo_label = "git documentation"; 127our$logo_url="http://git-scm.com/"; 128our$logo_label="git homepage"; 129 130# source of projects list 131our$projects_list="++GITWEB_LIST++"; 132 133# the width (in characters) of the projects list "Description" column 134our$projects_list_description_width=25; 135 136# group projects by category on the projects list 137# (enabled if this variable evaluates to true) 138our$projects_list_group_categories=0; 139 140# default category if none specified 141# (leave the empty string for no category) 142our$project_list_default_category=""; 143 144# default order of projects list 145# valid values are none, project, descr, owner, and age 146our$default_projects_order="project"; 147 148# show repository only if this file exists 149# (only effective if this variable evaluates to true) 150our$export_ok="++GITWEB_EXPORT_OK++"; 151 152# don't generate age column on the projects list page 153our$omit_age_column=0; 154 155# don't generate information about owners of repositories 156our$omit_owner=0; 157 158# show repository only if this subroutine returns true 159# when given the path to the project, for example: 160# sub { return -e "$_[0]/git-daemon-export-ok"; } 161our$export_auth_hook=undef; 162 163# only allow viewing of repositories also shown on the overview page 164our$strict_export="++GITWEB_STRICT_EXPORT++"; 165 166# list of git base URLs used for URL to where fetch project from, 167# i.e. full URL is "$git_base_url/$project" 168our@git_base_url_list=grep{$_ne''} ("++GITWEB_BASE_URL++"); 169 170# default blob_plain mimetype and default charset for text/plain blob 171our$default_blob_plain_mimetype='text/plain'; 172our$default_text_plain_charset=undef; 173 174# file to use for guessing MIME types before trying /etc/mime.types 175# (relative to the current git repository) 176our$mimetypes_file=undef; 177 178# assume this charset if line contains non-UTF-8 characters; 179# it should be valid encoding (see Encoding::Supported(3pm) for list), 180# for which encoding all byte sequences are valid, for example 181# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it 182# could be even 'utf-8' for the old behavior) 183our$fallback_encoding='latin1'; 184 185# rename detection options for git-diff and git-diff-tree 186# - default is '-M', with the cost proportional to 187# (number of removed files) * (number of new files). 188# - more costly is '-C' (which implies '-M'), with the cost proportional to 189# (number of changed files + number of removed files) * (number of new files) 190# - even more costly is '-C', '--find-copies-harder' with cost 191# (number of files in the original tree) * (number of new files) 192# - one might want to include '-B' option, e.g. '-B', '-M' 193our@diff_opts= ('-M');# taken from git_commit 194 195# Disables features that would allow repository owners to inject script into 196# the gitweb domain. 197our$prevent_xss=0; 198 199# Path to the highlight executable to use (must be the one from 200# http://www.andre-simon.de due to assumptions about parameters and output). 201# Useful if highlight is not installed on your webserver's PATH. 202# [Default: highlight] 203our$highlight_bin="++HIGHLIGHT_BIN++"; 204 205# information about snapshot formats that gitweb is capable of serving 206our%known_snapshot_formats= ( 207# name => { 208# 'display' => display name, 209# 'type' => mime type, 210# 'suffix' => filename suffix, 211# 'format' => --format for git-archive, 212# 'compressor' => [compressor command and arguments] 213# (array reference, optional) 214# 'disabled' => boolean (optional)} 215# 216'tgz'=> { 217'display'=>'tar.gz', 218'type'=>'application/x-gzip', 219'suffix'=>'.tar.gz', 220'format'=>'tar', 221'compressor'=> ['gzip','-n']}, 222 223'tbz2'=> { 224'display'=>'tar.bz2', 225'type'=>'application/x-bzip2', 226'suffix'=>'.tar.bz2', 227'format'=>'tar', 228'compressor'=> ['bzip2']}, 229 230'txz'=> { 231'display'=>'tar.xz', 232'type'=>'application/x-xz', 233'suffix'=>'.tar.xz', 234'format'=>'tar', 235'compressor'=> ['xz'], 236'disabled'=>1}, 237 238'zip'=> { 239'display'=>'zip', 240'type'=>'application/x-zip', 241'suffix'=>'.zip', 242'format'=>'zip'}, 243); 244 245# Aliases so we understand old gitweb.snapshot values in repository 246# configuration. 247our%known_snapshot_format_aliases= ( 248'gzip'=>'tgz', 249'bzip2'=>'tbz2', 250'xz'=>'txz', 251 252# backward compatibility: legacy gitweb config support 253'x-gzip'=>undef,'gz'=>undef, 254'x-bzip2'=>undef,'bz2'=>undef, 255'x-zip'=>undef,''=>undef, 256); 257 258# Pixel sizes for icons and avatars. If the default font sizes or lineheights 259# are changed, it may be appropriate to change these values too via 260# $GITWEB_CONFIG. 261our%avatar_size= ( 262'default'=>16, 263'double'=>32 264); 265 266# Used to set the maximum load that we will still respond to gitweb queries. 267# If server load exceed this value then return "503 server busy" error. 268# If gitweb cannot determined server load, it is taken to be 0. 269# Leave it undefined (or set to 'undef') to turn off load checking. 270our$maxload=300; 271 272# configuration for 'highlight' (http://www.andre-simon.de/) 273# match by basename 274our%highlight_basename= ( 275#'Program' => 'py', 276#'Library' => 'py', 277'SConstruct'=>'py',# SCons equivalent of Makefile 278'Makefile'=>'make', 279); 280# match by extension 281our%highlight_ext= ( 282# main extensions, defining name of syntax; 283# see files in /usr/share/highlight/langDefs/ directory 284(map{$_=>$_}qw(py rb java css js tex bib xml awk bat ini spec tcl sql)), 285# alternate extensions, see /etc/highlight/filetypes.conf 286(map{$_=>'c'}qw(c h)), 287(map{$_=>'sh'}qw(sh bash zsh ksh)), 288(map{$_=>'cpp'}qw(cpp cxx c++ cc)), 289(map{$_=>'php'}qw(php php3 php4 php5 phps)), 290(map{$_=>'pl'}qw(pl perl pm)),# perhaps also 'cgi' 291(map{$_=>'make'}qw(make mak mk)), 292(map{$_=>'xml'}qw(xml xhtml html htm)), 293); 294 295# You define site-wide feature defaults here; override them with 296# $GITWEB_CONFIG as necessary. 297our%feature= ( 298# feature => { 299# 'sub' => feature-sub (subroutine), 300# 'override' => allow-override (boolean), 301# 'default' => [ default options...] (array reference)} 302# 303# if feature is overridable (it means that allow-override has true value), 304# then feature-sub will be called with default options as parameters; 305# return value of feature-sub indicates if to enable specified feature 306# 307# if there is no 'sub' key (no feature-sub), then feature cannot be 308# overridden 309# 310# use gitweb_get_feature(<feature>) to retrieve the <feature> value 311# (an array) or gitweb_check_feature(<feature>) to check if <feature> 312# is enabled 313 314# Enable the 'blame' blob view, showing the last commit that modified 315# each line in the file. This can be very CPU-intensive. 316 317# To enable system wide have in $GITWEB_CONFIG 318# $feature{'blame'}{'default'} = [1]; 319# To have project specific config enable override in $GITWEB_CONFIG 320# $feature{'blame'}{'override'} = 1; 321# and in project config gitweb.blame = 0|1; 322'blame'=> { 323'sub'=>sub{ feature_bool('blame',@_) }, 324'override'=>0, 325'default'=> [0]}, 326 327# Enable the 'snapshot' link, providing a compressed archive of any 328# tree. This can potentially generate high traffic if you have large 329# project. 330 331# Value is a list of formats defined in %known_snapshot_formats that 332# you wish to offer. 333# To disable system wide have in $GITWEB_CONFIG 334# $feature{'snapshot'}{'default'} = []; 335# To have project specific config enable override in $GITWEB_CONFIG 336# $feature{'snapshot'}{'override'} = 1; 337# and in project config, a comma-separated list of formats or "none" 338# to disable. Example: gitweb.snapshot = tbz2,zip; 339'snapshot'=> { 340'sub'=> \&feature_snapshot, 341'override'=>0, 342'default'=> ['tgz']}, 343 344# Enable text search, which will list the commits which match author, 345# committer or commit text to a given string. Enabled by default. 346# Project specific override is not supported. 347# 348# Note that this controls all search features, which means that if 349# it is disabled, then 'grep' and 'pickaxe' search would also be 350# disabled. 351'search'=> { 352'override'=>0, 353'default'=> [1]}, 354 355# Enable grep search, which will list the files in currently selected 356# tree containing the given string. Enabled by default. This can be 357# potentially CPU-intensive, of course. 358# Note that you need to have 'search' feature enabled too. 359 360# To enable system wide have in $GITWEB_CONFIG 361# $feature{'grep'}{'default'} = [1]; 362# To have project specific config enable override in $GITWEB_CONFIG 363# $feature{'grep'}{'override'} = 1; 364# and in project config gitweb.grep = 0|1; 365'grep'=> { 366'sub'=>sub{ feature_bool('grep',@_) }, 367'override'=>0, 368'default'=> [1]}, 369 370# Enable the pickaxe search, which will list the commits that modified 371# a given string in a file. This can be practical and quite faster 372# alternative to 'blame', but still potentially CPU-intensive. 373# Note that you need to have 'search' feature enabled too. 374 375# To enable system wide have in $GITWEB_CONFIG 376# $feature{'pickaxe'}{'default'} = [1]; 377# To have project specific config enable override in $GITWEB_CONFIG 378# $feature{'pickaxe'}{'override'} = 1; 379# and in project config gitweb.pickaxe = 0|1; 380'pickaxe'=> { 381'sub'=>sub{ feature_bool('pickaxe',@_) }, 382'override'=>0, 383'default'=> [1]}, 384 385# Enable showing size of blobs in a 'tree' view, in a separate 386# column, similar to what 'ls -l' does. This cost a bit of IO. 387 388# To disable system wide have in $GITWEB_CONFIG 389# $feature{'show-sizes'}{'default'} = [0]; 390# To have project specific config enable override in $GITWEB_CONFIG 391# $feature{'show-sizes'}{'override'} = 1; 392# and in project config gitweb.showsizes = 0|1; 393'show-sizes'=> { 394'sub'=>sub{ feature_bool('showsizes',@_) }, 395'override'=>0, 396'default'=> [1]}, 397 398# Make gitweb use an alternative format of the URLs which can be 399# more readable and natural-looking: project name is embedded 400# directly in the path and the query string contains other 401# auxiliary information. All gitweb installations recognize 402# URL in either format; this configures in which formats gitweb 403# generates links. 404 405# To enable system wide have in $GITWEB_CONFIG 406# $feature{'pathinfo'}{'default'} = [1]; 407# Project specific override is not supported. 408 409# Note that you will need to change the default location of CSS, 410# favicon, logo and possibly other files to an absolute URL. Also, 411# if gitweb.cgi serves as your indexfile, you will need to force 412# $my_uri to contain the script name in your $GITWEB_CONFIG. 413'pathinfo'=> { 414'override'=>0, 415'default'=> [0]}, 416 417# Make gitweb consider projects in project root subdirectories 418# to be forks of existing projects. Given project $projname.git, 419# projects matching $projname/*.git will not be shown in the main 420# projects list, instead a '+' mark will be added to $projname 421# there and a 'forks' view will be enabled for the project, listing 422# all the forks. If project list is taken from a file, forks have 423# to be listed after the main project. 424 425# To enable system wide have in $GITWEB_CONFIG 426# $feature{'forks'}{'default'} = [1]; 427# Project specific override is not supported. 428'forks'=> { 429'override'=>0, 430'default'=> [0]}, 431 432# Insert custom links to the action bar of all project pages. 433# This enables you mainly to link to third-party scripts integrating 434# into gitweb; e.g. git-browser for graphical history representation 435# or custom web-based repository administration interface. 436 437# The 'default' value consists of a list of triplets in the form 438# (label, link, position) where position is the label after which 439# to insert the link and link is a format string where %n expands 440# to the project name, %f to the project path within the filesystem, 441# %h to the current hash (h gitweb parameter) and %b to the current 442# hash base (hb gitweb parameter); %% expands to %. 443 444# To enable system wide have in $GITWEB_CONFIG e.g. 445# $feature{'actions'}{'default'} = [('graphiclog', 446# '/git-browser/by-commit.html?r=%n', 'summary')]; 447# Project specific override is not supported. 448'actions'=> { 449'override'=>0, 450'default'=> []}, 451 452# Allow gitweb scan project content tags of project repository, 453# and display the popular Web 2.0-ish "tag cloud" near the projects 454# list. Note that this is something COMPLETELY different from the 455# normal Git tags. 456 457# gitweb by itself can show existing tags, but it does not handle 458# tagging itself; you need to do it externally, outside gitweb. 459# The format is described in git_get_project_ctags() subroutine. 460# You may want to install the HTML::TagCloud Perl module to get 461# a pretty tag cloud instead of just a list of tags. 462 463# To enable system wide have in $GITWEB_CONFIG 464# $feature{'ctags'}{'default'} = [1]; 465# Project specific override is not supported. 466 467# In the future whether ctags editing is enabled might depend 468# on the value, but using 1 should always mean no editing of ctags. 469'ctags'=> { 470'override'=>0, 471'default'=> [0]}, 472 473# The maximum number of patches in a patchset generated in patch 474# view. Set this to 0 or undef to disable patch view, or to a 475# negative number to remove any limit. 476 477# To disable system wide have in $GITWEB_CONFIG 478# $feature{'patches'}{'default'} = [0]; 479# To have project specific config enable override in $GITWEB_CONFIG 480# $feature{'patches'}{'override'} = 1; 481# and in project config gitweb.patches = 0|n; 482# where n is the maximum number of patches allowed in a patchset. 483'patches'=> { 484'sub'=> \&feature_patches, 485'override'=>0, 486'default'=> [16]}, 487 488# Avatar support. When this feature is enabled, views such as 489# shortlog or commit will display an avatar associated with 490# the email of the committer(s) and/or author(s). 491 492# Currently available providers are gravatar and picon. 493# If an unknown provider is specified, the feature is disabled. 494 495# Picon currently relies on the indiana.edu database. 496 497# To enable system wide have in $GITWEB_CONFIG 498# $feature{'avatar'}{'default'} = ['<provider>']; 499# where <provider> is either gravatar or picon. 500# To have project specific config enable override in $GITWEB_CONFIG 501# $feature{'avatar'}{'override'} = 1; 502# and in project config gitweb.avatar = <provider>; 503'avatar'=> { 504'sub'=> \&feature_avatar, 505'override'=>0, 506'default'=> ['']}, 507 508# Enable displaying how much time and how many git commands 509# it took to generate and display page. Disabled by default. 510# Project specific override is not supported. 511'timed'=> { 512'override'=>0, 513'default'=> [0]}, 514 515# Enable turning some links into links to actions which require 516# JavaScript to run (like 'blame_incremental'). Not enabled by 517# default. Project specific override is currently not supported. 518'javascript-actions'=> { 519'override'=>0, 520'default'=> [0]}, 521 522# Enable and configure ability to change common timezone for dates 523# in gitweb output via JavaScript. Enabled by default. 524# Project specific override is not supported. 525'javascript-timezone'=> { 526'override'=>0, 527'default'=> [ 528'local',# default timezone: 'utc', 'local', or '(-|+)HHMM' format, 529# or undef to turn off this feature 530'gitweb_tz',# name of cookie where to store selected timezone 531'datetime',# CSS class used to mark up dates for manipulation 532]}, 533 534# Syntax highlighting support. This is based on Daniel Svensson's 535# and Sham Chukoury's work in gitweb-xmms2.git. 536# It requires the 'highlight' program present in $PATH, 537# and therefore is disabled by default. 538 539# To enable system wide have in $GITWEB_CONFIG 540# $feature{'highlight'}{'default'} = [1]; 541 542'highlight'=> { 543'sub'=>sub{ feature_bool('highlight',@_) }, 544'override'=>0, 545'default'=> [0]}, 546 547# Enable displaying of remote heads in the heads list 548 549# To enable system wide have in $GITWEB_CONFIG 550# $feature{'remote_heads'}{'default'} = [1]; 551# To have project specific config enable override in $GITWEB_CONFIG 552# $feature{'remote_heads'}{'override'} = 1; 553# and in project config gitweb.remoteheads = 0|1; 554'remote_heads'=> { 555'sub'=>sub{ feature_bool('remote_heads',@_) }, 556'override'=>0, 557'default'=> [0]}, 558 559# Enable showing branches under other refs in addition to heads 560 561# To set system wide extra branch refs have in $GITWEB_CONFIG 562# $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice']; 563# To have project specific config enable override in $GITWEB_CONFIG 564# $feature{'extra-branch-refs'}{'override'} = 1; 565# and in project config gitweb.extrabranchrefs = dirs of choice 566# Every directory is separated with whitespace. 567 568'extra-branch-refs'=> { 569'sub'=> \&feature_extra_branch_refs, 570'override'=>0, 571'default'=> []}, 572); 573 574sub gitweb_get_feature { 575my($name) =@_; 576return unlessexists$feature{$name}; 577my($sub,$override,@defaults) = ( 578$feature{$name}{'sub'}, 579$feature{$name}{'override'}, 580@{$feature{$name}{'default'}}); 581# project specific override is possible only if we have project 582our$git_dir;# global variable, declared later 583if(!$override|| !defined$git_dir) { 584return@defaults; 585} 586if(!defined$sub) { 587warn"feature$nameis not overridable"; 588return@defaults; 589} 590return$sub->(@defaults); 591} 592 593# A wrapper to check if a given feature is enabled. 594# With this, you can say 595# 596# my $bool_feat = gitweb_check_feature('bool_feat'); 597# gitweb_check_feature('bool_feat') or somecode; 598# 599# instead of 600# 601# my ($bool_feat) = gitweb_get_feature('bool_feat'); 602# (gitweb_get_feature('bool_feat'))[0] or somecode; 603# 604sub gitweb_check_feature { 605return(gitweb_get_feature(@_))[0]; 606} 607 608 609sub feature_bool { 610my$key=shift; 611my($val) = git_get_project_config($key,'--bool'); 612 613if(!defined$val) { 614return($_[0]); 615}elsif($valeq'true') { 616return(1); 617}elsif($valeq'false') { 618return(0); 619} 620} 621 622sub feature_snapshot { 623my(@fmts) =@_; 624 625my($val) = git_get_project_config('snapshot'); 626 627if($val) { 628@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 629} 630 631return@fmts; 632} 633 634sub feature_patches { 635my@val= (git_get_project_config('patches','--int')); 636 637if(@val) { 638return@val; 639} 640 641return($_[0]); 642} 643 644sub feature_avatar { 645my@val= (git_get_project_config('avatar')); 646 647return@val?@val:@_; 648} 649 650sub feature_extra_branch_refs { 651my(@branch_refs) =@_; 652my$values= git_get_project_config('extrabranchrefs'); 653 654if($values) { 655$values= config_to_multi ($values); 656@branch_refs= (); 657foreachmy$value(@{$values}) { 658push@branch_refs,split/\s+/,$value; 659} 660} 661 662return@branch_refs; 663} 664 665# checking HEAD file with -e is fragile if the repository was 666# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 667# and then pruned. 668sub check_head_link { 669my($dir) =@_; 670my$headfile="$dir/HEAD"; 671return((-e $headfile) || 672(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 673} 674 675sub check_export_ok { 676my($dir) =@_; 677return(check_head_link($dir) && 678(!$export_ok|| -e "$dir/$export_ok") && 679(!$export_auth_hook||$export_auth_hook->($dir))); 680} 681 682# process alternate names for backward compatibility 683# filter out unsupported (unknown) snapshot formats 684sub filter_snapshot_fmts { 685my@fmts=@_; 686 687@fmts=map{ 688exists$known_snapshot_format_aliases{$_} ? 689$known_snapshot_format_aliases{$_} :$_}@fmts; 690@fmts=grep{ 691exists$known_snapshot_formats{$_} && 692!$known_snapshot_formats{$_}{'disabled'}}@fmts; 693} 694 695sub filter_and_validate_refs { 696my@refs=@_; 697my%unique_refs= (); 698 699foreachmy$ref(@refs) { 700 die_error(500,"Invalid ref '$ref' in 'extra-branch-refs' feature")unless(is_valid_ref_format($ref)); 701# 'heads' are added implicitly in get_branch_refs(). 702$unique_refs{$ref} =1if($refne'heads'); 703} 704returnsort keys%unique_refs; 705} 706 707# If it is set to code reference, it is code that it is to be run once per 708# request, allowing updating configurations that change with each request, 709# while running other code in config file only once. 710# 711# Otherwise, if it is false then gitweb would process config file only once; 712# if it is true then gitweb config would be run for each request. 713our$per_request_config=1; 714 715# read and parse gitweb config file given by its parameter. 716# returns true on success, false on recoverable error, allowing 717# to chain this subroutine, using first file that exists. 718# dies on errors during parsing config file, as it is unrecoverable. 719sub read_config_file { 720my$filename=shift; 721return unlessdefined$filename; 722# die if there are errors parsing config file 723if(-e $filename) { 724do$filename; 725die$@if$@; 726return1; 727} 728return; 729} 730 731our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM,$GITWEB_CONFIG_COMMON); 732sub evaluate_gitweb_config { 733our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 734our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 735our$GITWEB_CONFIG_COMMON=$ENV{'GITWEB_CONFIG_COMMON'} ||"++GITWEB_CONFIG_COMMON++"; 736 737# Protect against duplications of file names, to not read config twice. 738# Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so 739# there possibility of duplication of filename there doesn't matter. 740$GITWEB_CONFIG=""if($GITWEB_CONFIGeq$GITWEB_CONFIG_COMMON); 741$GITWEB_CONFIG_SYSTEM=""if($GITWEB_CONFIG_SYSTEMeq$GITWEB_CONFIG_COMMON); 742 743# Common system-wide settings for convenience. 744# Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM. 745 read_config_file($GITWEB_CONFIG_COMMON); 746 747# Use first config file that exists. This means use the per-instance 748# GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG. 749 read_config_file($GITWEB_CONFIG)andreturn; 750 read_config_file($GITWEB_CONFIG_SYSTEM); 751} 752 753# Get loadavg of system, to compare against $maxload. 754# Currently it requires '/proc/loadavg' present to get loadavg; 755# if it is not present it returns 0, which means no load checking. 756sub get_loadavg { 757if( -e '/proc/loadavg'){ 758open my$fd,'<','/proc/loadavg' 759orreturn0; 760my@load=split(/\s+/,scalar<$fd>); 761close$fd; 762 763# The first three columns measure CPU and IO utilization of the last one, 764# five, and 10 minute periods. The fourth column shows the number of 765# currently running processes and the total number of processes in the m/n 766# format. The last column displays the last process ID used. 767return$load[0] ||0; 768} 769# additional checks for load average should go here for things that don't export 770# /proc/loadavg 771 772return0; 773} 774 775# version of the core git binary 776our$git_version; 777sub evaluate_git_version { 778our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 779$number_of_git_cmds++; 780} 781 782sub check_loadavg { 783if(defined$maxload&& get_loadavg() >$maxload) { 784 die_error(503,"The load average on the server is too high"); 785} 786} 787 788# ====================================================================== 789# input validation and dispatch 790 791# input parameters can be collected from a variety of sources (presently, CGI 792# and PATH_INFO), so we define an %input_params hash that collects them all 793# together during validation: this allows subsequent uses (e.g. href()) to be 794# agnostic of the parameter origin 795 796our%input_params= (); 797 798# input parameters are stored with the long parameter name as key. This will 799# also be used in the href subroutine to convert parameters to their CGI 800# equivalent, and since the href() usage is the most frequent one, we store 801# the name -> CGI key mapping here, instead of the reverse. 802# 803# XXX: Warning: If you touch this, check the search form for updating, 804# too. 805 806our@cgi_param_mapping= ( 807 project =>"p", 808 action =>"a", 809 file_name =>"f", 810 file_parent =>"fp", 811 hash =>"h", 812 hash_parent =>"hp", 813 hash_base =>"hb", 814 hash_parent_base =>"hpb", 815 page =>"pg", 816 order =>"o", 817 searchtext =>"s", 818 searchtype =>"st", 819 snapshot_format =>"sf", 820 extra_options =>"opt", 821 search_use_regexp =>"sr", 822 ctag =>"by_tag", 823 diff_style =>"ds", 824 project_filter =>"pf", 825# this must be last entry (for manipulation from JavaScript) 826 javascript =>"js" 827); 828our%cgi_param_mapping=@cgi_param_mapping; 829 830# we will also need to know the possible actions, for validation 831our%actions= ( 832"blame"=> \&git_blame, 833"blame_incremental"=> \&git_blame_incremental, 834"blame_data"=> \&git_blame_data, 835"blobdiff"=> \&git_blobdiff, 836"blobdiff_plain"=> \&git_blobdiff_plain, 837"blob"=> \&git_blob, 838"blob_plain"=> \&git_blob_plain, 839"commitdiff"=> \&git_commitdiff, 840"commitdiff_plain"=> \&git_commitdiff_plain, 841"commit"=> \&git_commit, 842"forks"=> \&git_forks, 843"heads"=> \&git_heads, 844"history"=> \&git_history, 845"log"=> \&git_log, 846"patch"=> \&git_patch, 847"patches"=> \&git_patches, 848"remotes"=> \&git_remotes, 849"rss"=> \&git_rss, 850"atom"=> \&git_atom, 851"search"=> \&git_search, 852"search_help"=> \&git_search_help, 853"shortlog"=> \&git_shortlog, 854"summary"=> \&git_summary, 855"tag"=> \&git_tag, 856"tags"=> \&git_tags, 857"tree"=> \&git_tree, 858"snapshot"=> \&git_snapshot, 859"object"=> \&git_object, 860# those below don't need $project 861"opml"=> \&git_opml, 862"project_list"=> \&git_project_list, 863"project_index"=> \&git_project_index, 864); 865 866# finally, we have the hash of allowed extra_options for the commands that 867# allow them 868our%allowed_options= ( 869"--no-merges"=> [qw(rss atom log shortlog history)], 870); 871 872# fill %input_params with the CGI parameters. All values except for 'opt' 873# should be single values, but opt can be an array. We should probably 874# build an array of parameters that can be multi-valued, but since for the time 875# being it's only this one, we just single it out 876sub evaluate_query_params { 877our$cgi; 878 879while(my($name,$symbol) =each%cgi_param_mapping) { 880if($symboleq'opt') { 881$input_params{$name} = [map{ decode_utf8($_) }$cgi->multi_param($symbol) ]; 882}else{ 883$input_params{$name} = decode_utf8($cgi->param($symbol)); 884} 885} 886} 887 888# now read PATH_INFO and update the parameter list for missing parameters 889sub evaluate_path_info { 890return ifdefined$input_params{'project'}; 891return if!$path_info; 892$path_info=~ s,^/+,,; 893return if!$path_info; 894 895# find which part of PATH_INFO is project 896my$project=$path_info; 897$project=~ s,/+$,,; 898while($project&& !check_head_link("$projectroot/$project")) { 899$project=~ s,/*[^/]*$,,; 900} 901return unless$project; 902$input_params{'project'} =$project; 903 904# do not change any parameters if an action is given using the query string 905return if$input_params{'action'}; 906$path_info=~ s,^\Q$project\E/*,,; 907 908# next, check if we have an action 909my$action=$path_info; 910$action=~ s,/.*$,,; 911if(exists$actions{$action}) { 912$path_info=~ s,^$action/*,,; 913$input_params{'action'} =$action; 914} 915 916# list of actions that want hash_base instead of hash, but can have no 917# pathname (f) parameter 918my@wants_base= ( 919'tree', 920'history', 921); 922 923# we want to catch, among others 924# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 925my($parentrefname,$parentpathname,$refname,$pathname) = 926($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/); 927 928# first, analyze the 'current' part 929if(defined$pathname) { 930# we got "branch:filename" or "branch:dir/" 931# we could use git_get_type(branch:pathname), but: 932# - it needs $git_dir 933# - it does a git() call 934# - the convention of terminating directories with a slash 935# makes it superfluous 936# - embedding the action in the PATH_INFO would make it even 937# more superfluous 938$pathname=~ s,^/+,,; 939if(!$pathname||substr($pathname, -1)eq"/") { 940$input_params{'action'} ||="tree"; 941$pathname=~ s,/$,,; 942}else{ 943# the default action depends on whether we had parent info 944# or not 945if($parentrefname) { 946$input_params{'action'} ||="blobdiff_plain"; 947}else{ 948$input_params{'action'} ||="blob_plain"; 949} 950} 951$input_params{'hash_base'} ||=$refname; 952$input_params{'file_name'} ||=$pathname; 953}elsif(defined$refname) { 954# we got "branch". In this case we have to choose if we have to 955# set hash or hash_base. 956# 957# Most of the actions without a pathname only want hash to be 958# set, except for the ones specified in @wants_base that want 959# hash_base instead. It should also be noted that hand-crafted 960# links having 'history' as an action and no pathname or hash 961# set will fail, but that happens regardless of PATH_INFO. 962if(defined$parentrefname) { 963# if there is parent let the default be 'shortlog' action 964# (for http://git.example.com/repo.git/A..B links); if there 965# is no parent, dispatch will detect type of object and set 966# action appropriately if required (if action is not set) 967$input_params{'action'} ||="shortlog"; 968} 969if($input_params{'action'} && 970grep{$_eq$input_params{'action'} }@wants_base) { 971$input_params{'hash_base'} ||=$refname; 972}else{ 973$input_params{'hash'} ||=$refname; 974} 975} 976 977# next, handle the 'parent' part, if present 978if(defined$parentrefname) { 979# a missing pathspec defaults to the 'current' filename, allowing e.g. 980# someproject/blobdiff/oldrev..newrev:/filename 981if($parentpathname) { 982$parentpathname=~ s,^/+,,; 983$parentpathname=~ s,/$,,; 984$input_params{'file_parent'} ||=$parentpathname; 985}else{ 986$input_params{'file_parent'} ||=$input_params{'file_name'}; 987} 988# we assume that hash_parent_base is wanted if a path was specified, 989# or if the action wants hash_base instead of hash 990if(defined$input_params{'file_parent'} || 991grep{$_eq$input_params{'action'} }@wants_base) { 992$input_params{'hash_parent_base'} ||=$parentrefname; 993}else{ 994$input_params{'hash_parent'} ||=$parentrefname; 995} 996} 997 998# for the snapshot action, we allow URLs in the form 999# $project/snapshot/$hash.ext1000# where .ext determines the snapshot and gets removed from the1001# passed $refname to provide the $hash.1002#1003# To be able to tell that $refname includes the format extension, we1004# require the following two conditions to be satisfied:1005# - the hash input parameter MUST have been set from the $refname part1006# of the URL (i.e. they must be equal)1007# - the snapshot format MUST NOT have been defined already (e.g. from1008# CGI parameter sf)1009# It's also useless to try any matching unless $refname has a dot,1010# so we check for that too1011if(defined$input_params{'action'} &&1012$input_params{'action'}eq'snapshot'&&1013defined$refname&&index($refname,'.') != -1&&1014$refnameeq$input_params{'hash'} &&1015!defined$input_params{'snapshot_format'}) {1016# We loop over the known snapshot formats, checking for1017# extensions. Allowed extensions are both the defined suffix1018# (which includes the initial dot already) and the snapshot1019# format key itself, with a prepended dot1020while(my($fmt,$opt) =each%known_snapshot_formats) {1021my$hash=$refname;1022unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {1023next;1024}1025my$sfx=$1;1026# a valid suffix was found, so set the snapshot format1027# and reset the hash parameter1028$input_params{'snapshot_format'} =$fmt;1029$input_params{'hash'} =$hash;1030# we also set the format suffix to the one requested1031# in the URL: this way a request for e.g. .tgz returns1032# a .tgz instead of a .tar.gz1033$known_snapshot_formats{$fmt}{'suffix'} =$sfx;1034last;1035}1036}1037}10381039our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base,1040$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp,1041$searchtext,$search_regexp,$project_filter);1042sub evaluate_and_validate_params {1043our$action=$input_params{'action'};1044if(defined$action) {1045if(!is_valid_action($action)) {1046 die_error(400,"Invalid action parameter");1047}1048}10491050# parameters which are pathnames1051our$project=$input_params{'project'};1052if(defined$project) {1053if(!is_valid_project($project)) {1054undef$project;1055 die_error(404,"No such project");1056}1057}10581059our$project_filter=$input_params{'project_filter'};1060if(defined$project_filter) {1061if(!is_valid_pathname($project_filter)) {1062 die_error(404,"Invalid project_filter parameter");1063}1064}10651066our$file_name=$input_params{'file_name'};1067if(defined$file_name) {1068if(!is_valid_pathname($file_name)) {1069 die_error(400,"Invalid file parameter");1070}1071}10721073our$file_parent=$input_params{'file_parent'};1074if(defined$file_parent) {1075if(!is_valid_pathname($file_parent)) {1076 die_error(400,"Invalid file parent parameter");1077}1078}10791080# parameters which are refnames1081our$hash=$input_params{'hash'};1082if(defined$hash) {1083if(!is_valid_refname($hash)) {1084 die_error(400,"Invalid hash parameter");1085}1086}10871088our$hash_parent=$input_params{'hash_parent'};1089if(defined$hash_parent) {1090if(!is_valid_refname($hash_parent)) {1091 die_error(400,"Invalid hash parent parameter");1092}1093}10941095our$hash_base=$input_params{'hash_base'};1096if(defined$hash_base) {1097if(!is_valid_refname($hash_base)) {1098 die_error(400,"Invalid hash base parameter");1099}1100}11011102our@extra_options= @{$input_params{'extra_options'}};1103# @extra_options is always defined, since it can only be (currently) set from1104# CGI, and $cgi->param() returns the empty array in array context if the param1105# is not set1106foreachmy$opt(@extra_options) {1107if(not exists$allowed_options{$opt}) {1108 die_error(400,"Invalid option parameter");1109}1110if(not grep(/^$action$/, @{$allowed_options{$opt}})) {1111 die_error(400,"Invalid option parameter for this action");1112}1113}11141115our$hash_parent_base=$input_params{'hash_parent_base'};1116if(defined$hash_parent_base) {1117if(!is_valid_refname($hash_parent_base)) {1118 die_error(400,"Invalid hash parent base parameter");1119}1120}11211122# other parameters1123our$page=$input_params{'page'};1124if(defined$page) {1125if($page=~m/[^0-9]/) {1126 die_error(400,"Invalid page parameter");1127}1128}11291130our$searchtype=$input_params{'searchtype'};1131if(defined$searchtype) {1132if($searchtype=~m/[^a-z]/) {1133 die_error(400,"Invalid searchtype parameter");1134}1135}11361137our$search_use_regexp=$input_params{'search_use_regexp'};11381139our$searchtext=$input_params{'searchtext'};1140our$search_regexp=undef;1141if(defined$searchtext) {1142if(length($searchtext) <2) {1143 die_error(403,"At least two characters are required for search parameter");1144}1145if($search_use_regexp) {1146$search_regexp=$searchtext;1147if(!eval{qr/$search_regexp/;1; }) {1148(my$error=$@) =~s/ at \S+ line \d+.*\n?//;1149 die_error(400,"Invalid search regexp '$search_regexp'",1150 esc_html($error));1151}1152}else{1153$search_regexp=quotemeta$searchtext;1154}1155}1156}11571158# path to the current git repository1159our$git_dir;1160sub evaluate_git_dir {1161our$git_dir="$projectroot/$project"if$project;1162}11631164our(@snapshot_fmts,$git_avatar,@extra_branch_refs);1165sub configure_gitweb_features {1166# list of supported snapshot formats1167our@snapshot_fmts= gitweb_get_feature('snapshot');1168@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);11691170our($git_avatar) = gitweb_get_feature('avatar');1171$git_avatar=''unless$git_avatar=~/^(?:gravatar|picon)$/s;11721173our@extra_branch_refs= gitweb_get_feature('extra-branch-refs');1174@extra_branch_refs= filter_and_validate_refs (@extra_branch_refs);1175}11761177sub get_branch_refs {1178return('heads',@extra_branch_refs);1179}11801181# custom error handler: 'die <message>' is Internal Server Error1182sub handle_errors_html {1183my$msg=shift;# it is already HTML escaped11841185# to avoid infinite loop where error occurs in die_error,1186# change handler to default handler, disabling handle_errors_html1187 set_message("Error occurred when inside die_error:\n$msg");11881189# you cannot jump out of die_error when called as error handler;1190# the subroutine set via CGI::Carp::set_message is called _after_1191# HTTP headers are already written, so it cannot write them itself1192 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1193}1194set_message(\&handle_errors_html);11951196# dispatch1197sub dispatch {1198if(!defined$action) {1199if(defined$hash) {1200$action= git_get_type($hash);1201$actionor die_error(404,"Object does not exist");1202}elsif(defined$hash_base&&defined$file_name) {1203$action= git_get_type("$hash_base:$file_name");1204$actionor die_error(404,"File or directory does not exist");1205}elsif(defined$project) {1206$action='summary';1207}else{1208$action='project_list';1209}1210}1211if(!defined($actions{$action})) {1212 die_error(400,"Unknown action");1213}1214if($action!~m/^(?:opml|project_list|project_index)$/&&1215!$project) {1216 die_error(400,"Project needed");1217}1218$actions{$action}->();1219}12201221sub reset_timer {1222our$t0= [ gettimeofday() ]1223ifdefined$t0;1224our$number_of_git_cmds=0;1225}12261227our$first_request=1;1228sub run_request {1229 reset_timer();12301231 evaluate_uri();1232if($first_request) {1233 evaluate_gitweb_config();1234 evaluate_git_version();1235}1236if($per_request_config) {1237if(ref($per_request_config)eq'CODE') {1238$per_request_config->();1239}elsif(!$first_request) {1240 evaluate_gitweb_config();1241}1242}1243 check_loadavg();12441245# $projectroot and $projects_list might be set in gitweb config file1246$projects_list||=$projectroot;12471248 evaluate_query_params();1249 evaluate_path_info();1250 evaluate_and_validate_params();1251 evaluate_git_dir();12521253 configure_gitweb_features();12541255 dispatch();1256}12571258our$is_last_request=sub{1};1259our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1260our$CGI='CGI';1261our$cgi;1262sub configure_as_fcgi {1263require CGI::Fast;1264our$CGI='CGI::Fast';12651266my$request_number=0;1267# let each child service 100 requests1268our$is_last_request=sub{ ++$request_number>100};1269}1270sub evaluate_argv {1271my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1272 configure_as_fcgi()1273if$script_name=~/\.fcgi$/;12741275return unless(@ARGV);12761277require Getopt::Long;1278 Getopt::Long::GetOptions(1279'fastcgi|fcgi|f'=> \&configure_as_fcgi,1280'nproc|n=i'=>sub{1281my($arg,$val) =@_;1282return unlesseval{require FCGI::ProcManager;1; };1283my$proc_manager= FCGI::ProcManager->new({1284 n_processes =>$val,1285});1286our$pre_listen_hook=sub{$proc_manager->pm_manage() };1287our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1288our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1289},1290);1291}12921293sub run {1294 evaluate_argv();12951296$first_request=1;1297$pre_listen_hook->()1298if$pre_listen_hook;12991300 REQUEST:1301while($cgi=$CGI->new()) {1302$pre_dispatch_hook->()1303if$pre_dispatch_hook;13041305 run_request();13061307$post_dispatch_hook->()1308if$post_dispatch_hook;1309$first_request=0;13101311last REQUEST if($is_last_request->());1312}13131314 DONE_GITWEB:13151;1316}13171318run();13191320if(defined caller) {1321# wrapped in a subroutine processing requests,1322# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1323return;1324}else{1325# pure CGI script, serving single request1326exit;1327}13281329## ======================================================================1330## action links13311332# possible values of extra options1333# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1334# -replay => 1 - start from a current view (replay with modifications)1335# -path_info => 0|1 - don't use/use path_info URL (if possible)1336# -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone1337sub href {1338my%params=@_;1339# default is to use -absolute url() i.e. $my_uri1340my$href=$params{-full} ?$my_url:$my_uri;13411342# implicit -replay, must be first of implicit params1343$params{-replay} =1if(keys%params==1&&$params{-anchor});13441345$params{'project'} =$projectunlessexists$params{'project'};13461347if($params{-replay}) {1348while(my($name,$symbol) =each%cgi_param_mapping) {1349if(!exists$params{$name}) {1350$params{$name} =$input_params{$name};1351}1352}1353}13541355my$use_pathinfo= gitweb_check_feature('pathinfo');1356if(defined$params{'project'} &&1357(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1358# try to put as many parameters as possible in PATH_INFO:1359# - project name1360# - action1361# - hash_parent or hash_parent_base:/file_parent1362# - hash or hash_base:/filename1363# - the snapshot_format as an appropriate suffix13641365# When the script is the root DirectoryIndex for the domain,1366# $href here would be something like http://gitweb.example.com/1367# Thus, we strip any trailing / from $href, to spare us double1368# slashes in the final URL1369$href=~ s,/$,,;13701371# Then add the project name, if present1372$href.="/".esc_path_info($params{'project'});1373delete$params{'project'};13741375# since we destructively absorb parameters, we keep this1376# boolean that remembers if we're handling a snapshot1377my$is_snapshot=$params{'action'}eq'snapshot';13781379# Summary just uses the project path URL, any other action is1380# added to the URL1381if(defined$params{'action'}) {1382$href.="/".esc_path_info($params{'action'})1383unless$params{'action'}eq'summary';1384delete$params{'action'};1385}13861387# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1388# stripping nonexistent or useless pieces1389$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1390||$params{'hash_parent'} ||$params{'hash'});1391if(defined$params{'hash_base'}) {1392if(defined$params{'hash_parent_base'}) {1393$href.= esc_path_info($params{'hash_parent_base'});1394# skip the file_parent if it's the same as the file_name1395if(defined$params{'file_parent'}) {1396if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1397delete$params{'file_parent'};1398}elsif($params{'file_parent'} !~/\.\./) {1399$href.=":/".esc_path_info($params{'file_parent'});1400delete$params{'file_parent'};1401}1402}1403$href.="..";1404delete$params{'hash_parent'};1405delete$params{'hash_parent_base'};1406}elsif(defined$params{'hash_parent'}) {1407$href.= esc_path_info($params{'hash_parent'})."..";1408delete$params{'hash_parent'};1409}14101411$href.= esc_path_info($params{'hash_base'});1412if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1413$href.=":/".esc_path_info($params{'file_name'});1414delete$params{'file_name'};1415}1416delete$params{'hash'};1417delete$params{'hash_base'};1418}elsif(defined$params{'hash'}) {1419$href.= esc_path_info($params{'hash'});1420delete$params{'hash'};1421}14221423# If the action was a snapshot, we can absorb the1424# snapshot_format parameter too1425if($is_snapshot) {1426my$fmt=$params{'snapshot_format'};1427# snapshot_format should always be defined when href()1428# is called, but just in case some code forgets, we1429# fall back to the default1430$fmt||=$snapshot_fmts[0];1431$href.=$known_snapshot_formats{$fmt}{'suffix'};1432delete$params{'snapshot_format'};1433}1434}14351436# now encode the parameters explicitly1437my@result= ();1438for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1439my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1440if(defined$params{$name}) {1441if(ref($params{$name})eq"ARRAY") {1442foreachmy$par(@{$params{$name}}) {1443push@result,$symbol."=". esc_param($par);1444}1445}else{1446push@result,$symbol."=". esc_param($params{$name});1447}1448}1449}1450$href.="?".join(';',@result)ifscalar@result;14511452# final transformation: trailing spaces must be escaped (URI-encoded)1453$href=~s/(\s+)$/CGI::escape($1)/e;14541455if($params{-anchor}) {1456$href.="#".esc_param($params{-anchor});1457}14581459return$href;1460}146114621463## ======================================================================1464## validation, quoting/unquoting and escaping14651466sub is_valid_action {1467my$input=shift;1468returnundefunlessexists$actions{$input};1469return1;1470}14711472sub is_valid_project {1473my$input=shift;14741475return unlessdefined$input;1476if(!is_valid_pathname($input) ||1477!(-d "$projectroot/$input") ||1478!check_export_ok("$projectroot/$input") ||1479($strict_export&& !project_in_list($input))) {1480returnundef;1481}else{1482return1;1483}1484}14851486sub is_valid_pathname {1487my$input=shift;14881489returnundefunlessdefined$input;1490# no '.' or '..' as elements of path, i.e. no '.' or '..'1491# at the beginning, at the end, and between slashes.1492# also this catches doubled slashes1493if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1494returnundef;1495}1496# no null characters1497if($input=~m!\0!) {1498returnundef;1499}1500return1;1501}15021503sub is_valid_ref_format {1504my$input=shift;15051506returnundefunlessdefined$input;1507# restrictions on ref name according to git-check-ref-format1508if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1509returnundef;1510}1511return1;1512}15131514sub is_valid_refname {1515my$input=shift;15161517returnundefunlessdefined$input;1518# textual hashes are O.K.1519if($input=~m/^[0-9a-fA-F]{40}$/) {1520return1;1521}1522# it must be correct pathname1523 is_valid_pathname($input)orreturnundef;1524# check git-check-ref-format restrictions1525 is_valid_ref_format($input)orreturnundef;1526return1;1527}15281529# decode sequences of octets in utf8 into Perl's internal form,1530# which is utf-8 with utf8 flag set if needed. gitweb writes out1531# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1532sub to_utf8 {1533my$str=shift;1534returnundefunlessdefined$str;15351536if(utf8::is_utf8($str) || utf8::decode($str)) {1537return$str;1538}else{1539return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1540}1541}15421543# quote unsafe chars, but keep the slash, even when it's not1544# correct, but quoted slashes look too horrible in bookmarks1545sub esc_param {1546my$str=shift;1547returnundefunlessdefined$str;1548$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1549$str=~s/ /\+/g;1550return$str;1551}15521553# the quoting rules for path_info fragment are slightly different1554sub esc_path_info {1555my$str=shift;1556returnundefunlessdefined$str;15571558# path_info doesn't treat '+' as space (specially), but '?' must be escaped1559$str=~s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;15601561return$str;1562}15631564# quote unsafe chars in whole URL, so some characters cannot be quoted1565sub esc_url {1566my$str=shift;1567returnundefunlessdefined$str;1568$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1569$str=~s/ /\+/g;1570return$str;1571}15721573# quote unsafe characters in HTML attributes1574sub esc_attr {15751576# for XHTML conformance escaping '"' to '"' is not enough1577return esc_html(@_);1578}15791580# replace invalid utf8 character with SUBSTITUTION sequence1581sub esc_html {1582my$str=shift;1583my%opts=@_;15841585returnundefunlessdefined$str;15861587$str= to_utf8($str);1588$str=$cgi->escapeHTML($str);1589if($opts{'-nbsp'}) {1590$str=~s/ / /g;1591}1592$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1593return$str;1594}15951596# quote control characters and escape filename to HTML1597sub esc_path {1598my$str=shift;1599my%opts=@_;16001601returnundefunlessdefined$str;16021603$str= to_utf8($str);1604$str=$cgi->escapeHTML($str);1605if($opts{'-nbsp'}) {1606$str=~s/ / /g;1607}1608$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1609return$str;1610}16111612# Sanitize for use in XHTML + application/xml+xhtml (valid XML 1.0)1613sub sanitize {1614my$str=shift;16151616returnundefunlessdefined$str;16171618$str= to_utf8($str);1619$str=~ s|([[:cntrl:]])|(index("\t\n\r",$1) != -1?$1: quot_cec($1))|eg;1620return$str;1621}16221623# Make control characters "printable", using character escape codes (CEC)1624sub quot_cec {1625my$cntrl=shift;1626my%opts=@_;1627my%es= (# character escape codes, aka escape sequences1628"\t"=>'\t',# tab (HT)1629"\n"=>'\n',# line feed (LF)1630"\r"=>'\r',# carrige return (CR)1631"\f"=>'\f',# form feed (FF)1632"\b"=>'\b',# backspace (BS)1633"\a"=>'\a',# alarm (bell) (BEL)1634"\e"=>'\e',# escape (ESC)1635"\013"=>'\v',# vertical tab (VT)1636"\000"=>'\0',# nul character (NUL)1637);1638my$chr= ( (exists$es{$cntrl})1639?$es{$cntrl}1640:sprintf('\%2x',ord($cntrl)) );1641if($opts{-nohtml}) {1642return$chr;1643}else{1644return"<span class=\"cntrl\">$chr</span>";1645}1646}16471648# Alternatively use unicode control pictures codepoints,1649# Unicode "printable representation" (PR)1650sub quot_upr {1651my$cntrl=shift;1652my%opts=@_;16531654my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1655if($opts{-nohtml}) {1656return$chr;1657}else{1658return"<span class=\"cntrl\">$chr</span>";1659}1660}16611662# git may return quoted and escaped filenames1663sub unquote {1664my$str=shift;16651666sub unq {1667my$seq=shift;1668my%es= (# character escape codes, aka escape sequences1669't'=>"\t",# tab (HT, TAB)1670'n'=>"\n",# newline (NL)1671'r'=>"\r",# return (CR)1672'f'=>"\f",# form feed (FF)1673'b'=>"\b",# backspace (BS)1674'a'=>"\a",# alarm (bell) (BEL)1675'e'=>"\e",# escape (ESC)1676'v'=>"\013",# vertical tab (VT)1677);16781679if($seq=~m/^[0-7]{1,3}$/) {1680# octal char sequence1681returnchr(oct($seq));1682}elsif(exists$es{$seq}) {1683# C escape sequence, aka character escape code1684return$es{$seq};1685}1686# quoted ordinary character1687return$seq;1688}16891690if($str=~m/^"(.*)"$/) {1691# needs unquoting1692$str=$1;1693$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1694}1695return$str;1696}16971698# escape tabs (convert tabs to spaces)1699sub untabify {1700my$line=shift;17011702while((my$pos=index($line,"\t")) != -1) {1703if(my$count= (8- ($pos%8))) {1704my$spaces=' ' x $count;1705$line=~s/\t/$spaces/;1706}1707}17081709return$line;1710}17111712sub project_in_list {1713my$project=shift;1714my@list= git_get_projects_list();1715return@list&&scalar(grep{$_->{'path'}eq$project}@list);1716}17171718## ----------------------------------------------------------------------1719## HTML aware string manipulation17201721# Try to chop given string on a word boundary between position1722# $len and $len+$add_len. If there is no word boundary there,1723# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1724# (marking chopped part) would be longer than given string.1725sub chop_str {1726my$str=shift;1727my$len=shift;1728my$add_len=shift||10;1729my$where=shift||'right';# 'left' | 'center' | 'right'17301731# Make sure perl knows it is utf8 encoded so we don't1732# cut in the middle of a utf8 multibyte char.1733$str= to_utf8($str);17341735# allow only $len chars, but don't cut a word if it would fit in $add_len1736# if it doesn't fit, cut it if it's still longer than the dots we would add1737# remove chopped character entities entirely17381739# when chopping in the middle, distribute $len into left and right part1740# return early if chopping wouldn't make string shorter1741if($whereeq'center') {1742return$strif($len+5>=length($str));# filler is length 51743$len=int($len/2);1744}else{1745return$strif($len+4>=length($str));# filler is length 41746}17471748# regexps: ending and beginning with word part up to $add_len1749my$endre=qr/.{$len}\w{0,$add_len}/;1750my$begre=qr/\w{0,$add_len}.{$len}/;17511752if($whereeq'left') {1753$str=~m/^(.*?)($begre)$/;1754my($lead,$body) = ($1,$2);1755if(length($lead) >4) {1756$lead=" ...";1757}1758return"$lead$body";17591760}elsif($whereeq'center') {1761$str=~m/^($endre)(.*)$/;1762my($left,$str) = ($1,$2);1763$str=~m/^(.*?)($begre)$/;1764my($mid,$right) = ($1,$2);1765if(length($mid) >5) {1766$mid=" ... ";1767}1768return"$left$mid$right";17691770}else{1771$str=~m/^($endre)(.*)$/;1772my$body=$1;1773my$tail=$2;1774if(length($tail) >4) {1775$tail="... ";1776}1777return"$body$tail";1778}1779}17801781# takes the same arguments as chop_str, but also wraps a <span> around the1782# result with a title attribute if it does get chopped. Additionally, the1783# string is HTML-escaped.1784sub chop_and_escape_str {1785my($str) =@_;17861787my$chopped= chop_str(@_);1788$str= to_utf8($str);1789if($choppedeq$str) {1790return esc_html($chopped);1791}else{1792$str=~s/[[:cntrl:]]/?/g;1793return$cgi->span({-title=>$str}, esc_html($chopped));1794}1795}17961797# Highlight selected fragments of string, using given CSS class,1798# and escape HTML. It is assumed that fragments do not overlap.1799# Regions are passed as list of pairs (array references).1800#1801# Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns1802# '<span class="mark">foo</span>bar'1803sub esc_html_hl_regions {1804my($str,$css_class,@sel) =@_;1805my%opts=grep{ref($_)ne'ARRAY'}@sel;1806@sel=grep{ref($_)eq'ARRAY'}@sel;1807return esc_html($str,%opts)unless@sel;18081809my$out='';1810my$pos=0;18111812formy$s(@sel) {1813my($begin,$end) =@$s;18141815# Don't create empty <span> elements.1816next if$end<=$begin;18171818my$escaped= esc_html(substr($str,$begin,$end-$begin),1819%opts);18201821$out.= esc_html(substr($str,$pos,$begin-$pos),%opts)1822if($begin-$pos>0);1823$out.=$cgi->span({-class=>$css_class},$escaped);18241825$pos=$end;1826}1827$out.= esc_html(substr($str,$pos),%opts)1828if($pos<length($str));18291830return$out;1831}18321833# return positions of beginning and end of each match1834sub matchpos_list {1835my($str,$regexp) =@_;1836return unless(defined$str&&defined$regexp);18371838my@matches;1839while($str=~/$regexp/g) {1840push@matches, [$-[0],$+[0]];1841}1842return@matches;1843}18441845# highlight match (if any), and escape HTML1846sub esc_html_match_hl {1847my($str,$regexp) =@_;1848return esc_html($str)unlessdefined$regexp;18491850my@matches= matchpos_list($str,$regexp);1851return esc_html($str)unless@matches;18521853return esc_html_hl_regions($str,'match',@matches);1854}185518561857# highlight match (if any) of shortened string, and escape HTML1858sub esc_html_match_hl_chopped {1859my($str,$chopped,$regexp) =@_;1860return esc_html_match_hl($str,$regexp)unlessdefined$chopped;18611862my@matches= matchpos_list($str,$regexp);1863return esc_html($chopped)unless@matches;18641865# filter matches so that we mark chopped string1866my$tail="... ";# see chop_str1867unless($chopped=~s/\Q$tail\E$//) {1868$tail='';1869}1870my$chop_len=length($chopped);1871my$tail_len=length($tail);1872my@filtered;18731874formy$m(@matches) {1875if($m->[0] >$chop_len) {1876push@filtered, [$chop_len,$chop_len+$tail_len]if($tail_len>0);1877last;1878}elsif($m->[1] >$chop_len) {1879push@filtered, [$m->[0],$chop_len+$tail_len];1880last;1881}1882push@filtered,$m;1883}18841885return esc_html_hl_regions($chopped.$tail,'match',@filtered);1886}18871888## ----------------------------------------------------------------------1889## functions returning short strings18901891# CSS class for given age value (in seconds)1892sub age_class {1893my$age=shift;18941895if(!defined$age) {1896return"noage";1897}elsif($age<60*60*2) {1898return"age0";1899}elsif($age<60*60*24*2) {1900return"age1";1901}else{1902return"age2";1903}1904}19051906# convert age in seconds to "nn units ago" string1907sub age_string {1908my$age=shift;1909my$age_str;19101911if($age>60*60*24*365*2) {1912$age_str= (int$age/60/60/24/365);1913$age_str.=" years ago";1914}elsif($age>60*60*24*(365/12)*2) {1915$age_str=int$age/60/60/24/(365/12);1916$age_str.=" months ago";1917}elsif($age>60*60*24*7*2) {1918$age_str=int$age/60/60/24/7;1919$age_str.=" weeks ago";1920}elsif($age>60*60*24*2) {1921$age_str=int$age/60/60/24;1922$age_str.=" days ago";1923}elsif($age>60*60*2) {1924$age_str=int$age/60/60;1925$age_str.=" hours ago";1926}elsif($age>60*2) {1927$age_str=int$age/60;1928$age_str.=" min ago";1929}elsif($age>2) {1930$age_str=int$age;1931$age_str.=" sec ago";1932}else{1933$age_str.=" right now";1934}1935return$age_str;1936}19371938useconstant{1939 S_IFINVALID =>0030000,1940 S_IFGITLINK =>0160000,1941};19421943# submodule/subproject, a commit object reference1944sub S_ISGITLINK {1945my$mode=shift;19461947return(($mode& S_IFMT) == S_IFGITLINK)1948}19491950# convert file mode in octal to symbolic file mode string1951sub mode_str {1952my$mode=oct shift;19531954if(S_ISGITLINK($mode)) {1955return'm---------';1956}elsif(S_ISDIR($mode& S_IFMT)) {1957return'drwxr-xr-x';1958}elsif(S_ISLNK($mode)) {1959return'lrwxrwxrwx';1960}elsif(S_ISREG($mode)) {1961# git cares only about the executable bit1962if($mode& S_IXUSR) {1963return'-rwxr-xr-x';1964}else{1965return'-rw-r--r--';1966};1967}else{1968return'----------';1969}1970}19711972# convert file mode in octal to file type string1973sub file_type {1974my$mode=shift;19751976if($mode!~m/^[0-7]+$/) {1977return$mode;1978}else{1979$mode=oct$mode;1980}19811982if(S_ISGITLINK($mode)) {1983return"submodule";1984}elsif(S_ISDIR($mode& S_IFMT)) {1985return"directory";1986}elsif(S_ISLNK($mode)) {1987return"symlink";1988}elsif(S_ISREG($mode)) {1989return"file";1990}else{1991return"unknown";1992}1993}19941995# convert file mode in octal to file type description string1996sub file_type_long {1997my$mode=shift;19981999if($mode!~m/^[0-7]+$/) {2000return$mode;2001}else{2002$mode=oct$mode;2003}20042005if(S_ISGITLINK($mode)) {2006return"submodule";2007}elsif(S_ISDIR($mode& S_IFMT)) {2008return"directory";2009}elsif(S_ISLNK($mode)) {2010return"symlink";2011}elsif(S_ISREG($mode)) {2012if($mode& S_IXUSR) {2013return"executable";2014}else{2015return"file";2016};2017}else{2018return"unknown";2019}2020}202120222023## ----------------------------------------------------------------------2024## functions returning short HTML fragments, or transforming HTML fragments2025## which don't belong to other sections20262027# format line of commit message.2028sub format_log_line_html {2029my$line=shift;20302031$line= esc_html($line, -nbsp=>1);2032$line=~ s{2033\b2034(2035# The output of "git describe", e.g. v2.10.0-297-gf6727b02036# or hadoop-20160921-113441-20-g094fb7d2037(?<!-)# see strbuf_check_tag_ref(). Tags can't start with -2038[A-Za-z0-9.-]+2039(?!\.)# refs can't end with ".", see check_refname_format()2040-g[0-9a-fA-F]{7,40}2041|2042# Just a normal looking Git SHA12043[0-9a-fA-F]{7,40}2044)2045\b2046}{2047$cgi->a({-href => href(action=>"object", hash=>$1),2048-class=>"text"},$1);2049}egx;20502051return$line;2052}20532054# format marker of refs pointing to given object20552056# the destination action is chosen based on object type and current context:2057# - for annotated tags, we choose the tag view unless it's the current view2058# already, in which case we go to shortlog view2059# - for other refs, we keep the current view if we're in history, shortlog or2060# log view, and select shortlog otherwise2061sub format_ref_marker {2062my($refs,$id) =@_;2063my$markers='';20642065if(defined$refs->{$id}) {2066foreachmy$ref(@{$refs->{$id}}) {2067# this code exploits the fact that non-lightweight tags are the2068# only indirect objects, and that they are the only objects for which2069# we want to use tag instead of shortlog as action2070my($type,$name) =qw();2071my$indirect= ($ref=~s/\^\{\}$//);2072# e.g. tags/v2.6.11 or heads/next2073if($ref=~m!^(.*?)s?/(.*)$!) {2074$type=$1;2075$name=$2;2076}else{2077$type="ref";2078$name=$ref;2079}20802081my$class=$type;2082$class.=" indirect"if$indirect;20832084my$dest_action="shortlog";20852086if($indirect) {2087$dest_action="tag"unless$actioneq"tag";2088}elsif($action=~/^(history|(short)?log)$/) {2089$dest_action=$action;2090}20912092my$dest="";2093$dest.="refs/"unless$ref=~ m!^refs/!;2094$dest.=$ref;20952096my$link=$cgi->a({2097-href => href(2098 action=>$dest_action,2099 hash=>$dest2100)}, esc_html($name));21012102$markers.=" <span class=\"".esc_attr($class)."\"title=\"".esc_attr($ref)."\">".2103$link."</span>";2104}2105}21062107if($markers) {2108return' <span class="refs">'.$markers.'</span>';2109}else{2110return"";2111}2112}21132114# format, perhaps shortened and with markers, title line2115sub format_subject_html {2116my($long,$short,$href,$extra) =@_;2117$extra=''unlessdefined($extra);21182119if(length($short) <length($long)) {2120$long=~s/[[:cntrl:]]/?/g;2121return$cgi->a({-href =>$href, -class=>"list subject",2122-title => to_utf8($long)},2123 esc_html($short)) .$extra;2124}else{2125return$cgi->a({-href =>$href, -class=>"list subject"},2126 esc_html($long)) .$extra;2127}2128}21292130# Rather than recomputing the url for an email multiple times, we cache it2131# after the first hit. This gives a visible benefit in views where the avatar2132# for the same email is used repeatedly (e.g. shortlog).2133# The cache is shared by all avatar engines (currently gravatar only), which2134# are free to use it as preferred. Since only one avatar engine is used for any2135# given page, there's no risk for cache conflicts.2136our%avatar_cache= ();21372138# Compute the picon url for a given email, by using the picon search service over at2139# http://www.cs.indiana.edu/picons/search.html2140sub picon_url {2141my$email=lc shift;2142if(!$avatar_cache{$email}) {2143my($user,$domain) =split('@',$email);2144$avatar_cache{$email} =2145"//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".2146"$domain/$user/".2147"users+domains+unknown/up/single";2148}2149return$avatar_cache{$email};2150}21512152# Compute the gravatar url for a given email, if it's not in the cache already.2153# Gravatar stores only the part of the URL before the size, since that's the2154# one computationally more expensive. This also allows reuse of the cache for2155# different sizes (for this particular engine).2156sub gravatar_url {2157my$email=lc shift;2158my$size=shift;2159$avatar_cache{$email} ||=2160"//www.gravatar.com/avatar/".2161 md5_hex($email) ."?s=";2162return$avatar_cache{$email} .$size;2163}21642165# Insert an avatar for the given $email at the given $size if the feature2166# is enabled.2167sub git_get_avatar {2168my($email,%opts) =@_;2169my$pre_white= ($opts{-pad_before} ?" ":"");2170my$post_white= ($opts{-pad_after} ?" ":"");2171$opts{-size} ||='default';2172my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};2173my$url="";2174if($git_avatareq'gravatar') {2175$url= gravatar_url($email,$size);2176}elsif($git_avatareq'picon') {2177$url= picon_url($email);2178}2179# Other providers can be added by extending the if chain, defining $url2180# as needed. If no variant puts something in $url, we assume avatars2181# are completely disabled/unavailable.2182if($url) {2183return$pre_white.2184"<img width=\"$size\"".2185"class=\"avatar\"".2186"src=\"".esc_url($url)."\"".2187"alt=\"\"".2188"/>".$post_white;2189}else{2190return"";2191}2192}21932194sub format_search_author {2195my($author,$searchtype,$displaytext) =@_;2196my$have_search= gitweb_check_feature('search');21972198if($have_search) {2199my$performed="";2200if($searchtypeeq'author') {2201$performed="authored";2202}elsif($searchtypeeq'committer') {2203$performed="committed";2204}22052206return$cgi->a({-href => href(action=>"search", hash=>$hash,2207 searchtext=>$author,2208 searchtype=>$searchtype),class=>"list",2209 title=>"Search for commits$performedby$author"},2210$displaytext);22112212}else{2213return$displaytext;2214}2215}22162217# format the author name of the given commit with the given tag2218# the author name is chopped and escaped according to the other2219# optional parameters (see chop_str).2220sub format_author_html {2221my$tag=shift;2222my$co=shift;2223my$author= chop_and_escape_str($co->{'author_name'},@_);2224return"<$tagclass=\"author\">".2225 format_search_author($co->{'author_name'},"author",2226 git_get_avatar($co->{'author_email'}, -pad_after =>1) .2227$author) .2228"</$tag>";2229}22302231# format git diff header line, i.e. "diff --(git|combined|cc) ..."2232sub format_git_diff_header_line {2233my$line=shift;2234my$diffinfo=shift;2235my($from,$to) =@_;22362237if($diffinfo->{'nparents'}) {2238# combined diff2239$line=~s!^(diff (.*?) )"?.*$!$1!;2240if($to->{'href'}) {2241$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2242 esc_path($to->{'file'}));2243}else{# file was deleted (no href)2244$line.= esc_path($to->{'file'});2245}2246}else{2247# "ordinary" diff2248$line=~s!^(diff (.*?) )"?a/.*$!$1!;2249if($from->{'href'}) {2250$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},2251'a/'. esc_path($from->{'file'}));2252}else{# file was added (no href)2253$line.='a/'. esc_path($from->{'file'});2254}2255$line.=' ';2256if($to->{'href'}) {2257$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2258'b/'. esc_path($to->{'file'}));2259}else{# file was deleted2260$line.='b/'. esc_path($to->{'file'});2261}2262}22632264return"<div class=\"diff header\">$line</div>\n";2265}22662267# format extended diff header line, before patch itself2268sub format_extended_diff_header_line {2269my$line=shift;2270my$diffinfo=shift;2271my($from,$to) =@_;22722273# match <path>2274if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {2275$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},2276 esc_path($from->{'file'}));2277}2278if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {2279$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},2280 esc_path($to->{'file'}));2281}2282# match single <mode>2283if($line=~m/\s(\d{6})$/) {2284$line.='<span class="info"> ('.2285 file_type_long($1) .2286')</span>';2287}2288# match <hash>2289if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {2290# can match only for combined diff2291$line='index ';2292for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2293if($from->{'href'}[$i]) {2294$line.=$cgi->a({-href=>$from->{'href'}[$i],2295-class=>"hash"},2296substr($diffinfo->{'from_id'}[$i],0,7));2297}else{2298$line.='0' x 7;2299}2300# separator2301$line.=','if($i<$diffinfo->{'nparents'} -1);2302}2303$line.='..';2304if($to->{'href'}) {2305$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2306substr($diffinfo->{'to_id'},0,7));2307}else{2308$line.='0' x 7;2309}23102311}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {2312# can match only for ordinary diff2313my($from_link,$to_link);2314if($from->{'href'}) {2315$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},2316substr($diffinfo->{'from_id'},0,7));2317}else{2318$from_link='0' x 7;2319}2320if($to->{'href'}) {2321$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2322substr($diffinfo->{'to_id'},0,7));2323}else{2324$to_link='0' x 7;2325}2326my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});2327$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;2328}23292330return$line."<br/>\n";2331}23322333# format from-file/to-file diff header2334sub format_diff_from_to_header {2335my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2336my$line;2337my$result='';23382339$line=$from_line;2340#assert($line =~ m/^---/) if DEBUG;2341# no extra formatting for "^--- /dev/null"2342if(!$diffinfo->{'nparents'}) {2343# ordinary (single parent) diff2344if($line=~m!^--- "?a/!) {2345if($from->{'href'}) {2346$line='--- a/'.2347$cgi->a({-href=>$from->{'href'}, -class=>"path"},2348 esc_path($from->{'file'}));2349}else{2350$line='--- a/'.2351 esc_path($from->{'file'});2352}2353}2354$result.= qq!<div class="diff from_file">$line</div>\n!;23552356}else{2357# combined diff (merge commit)2358for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2359if($from->{'href'}[$i]) {2360$line='--- '.2361$cgi->a({-href=>href(action=>"blobdiff",2362 hash_parent=>$diffinfo->{'from_id'}[$i],2363 hash_parent_base=>$parents[$i],2364 file_parent=>$from->{'file'}[$i],2365 hash=>$diffinfo->{'to_id'},2366 hash_base=>$hash,2367 file_name=>$to->{'file'}),2368-class=>"path",2369-title=>"diff". ($i+1)},2370$i+1) .2371'/'.2372$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2373 esc_path($from->{'file'}[$i]));2374}else{2375$line='--- /dev/null';2376}2377$result.= qq!<div class="diff from_file">$line</div>\n!;2378}2379}23802381$line=$to_line;2382#assert($line =~ m/^\+\+\+/) if DEBUG;2383# no extra formatting for "^+++ /dev/null"2384if($line=~m!^\+\+\+ "?b/!) {2385if($to->{'href'}) {2386$line='+++ b/'.2387$cgi->a({-href=>$to->{'href'}, -class=>"path"},2388 esc_path($to->{'file'}));2389}else{2390$line='+++ b/'.2391 esc_path($to->{'file'});2392}2393}2394$result.= qq!<div class="diff to_file">$line</div>\n!;23952396return$result;2397}23982399# create note for patch simplified by combined diff2400sub format_diff_cc_simplified {2401my($diffinfo,@parents) =@_;2402my$result='';24032404$result.="<div class=\"diff header\">".2405"diff --cc ";2406if(!is_deleted($diffinfo)) {2407$result.=$cgi->a({-href => href(action=>"blob",2408 hash_base=>$hash,2409 hash=>$diffinfo->{'to_id'},2410 file_name=>$diffinfo->{'to_file'}),2411-class=>"path"},2412 esc_path($diffinfo->{'to_file'}));2413}else{2414$result.= esc_path($diffinfo->{'to_file'});2415}2416$result.="</div>\n".# class="diff header"2417"<div class=\"diff nodifferences\">".2418"Simple merge".2419"</div>\n";# class="diff nodifferences"24202421return$result;2422}24232424sub diff_line_class {2425my($line,$from,$to) =@_;24262427# ordinary diff2428my$num_sign=1;2429# combined diff2430if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2431$num_sign=scalar@{$from->{'href'}};2432}24332434my@diff_line_classifier= (2435{ regexp =>qr/^\@\@{$num_sign} /,class=>"chunk_header"},2436{ regexp =>qr/^\\/,class=>"incomplete"},2437{ regexp =>qr/^ {$num_sign}/,class=>"ctx"},2438# classifier for context must come before classifier add/rem,2439# or we would have to use more complicated regexp, for example2440# qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;2441{ regexp =>qr/^[+ ]{$num_sign}/,class=>"add"},2442{ regexp =>qr/^[- ]{$num_sign}/,class=>"rem"},2443);2444formy$clsfy(@diff_line_classifier) {2445return$clsfy->{'class'}2446if($line=~$clsfy->{'regexp'});2447}24482449# fallback2450return"";2451}24522453# assumes that $from and $to are defined and correctly filled,2454# and that $line holds a line of chunk header for unified diff2455sub format_unidiff_chunk_header {2456my($line,$from,$to) =@_;24572458my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2459$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;24602461$from_lines=0unlessdefined$from_lines;2462$to_lines=0unlessdefined$to_lines;24632464if($from->{'href'}) {2465$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2466-class=>"list"},$from_text);2467}2468if($to->{'href'}) {2469$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2470-class=>"list"},$to_text);2471}2472$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2473"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2474return$line;2475}24762477# assumes that $from and $to are defined and correctly filled,2478# and that $line holds a line of chunk header for combined diff2479sub format_cc_diff_chunk_header {2480my($line,$from,$to) =@_;24812482my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2483my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);24842485@from_text=split(' ',$ranges);2486for(my$i=0;$i<@from_text; ++$i) {2487($from_start[$i],$from_nlines[$i]) =2488(split(',',substr($from_text[$i],1)),0);2489}24902491$to_text=pop@from_text;2492$to_start=pop@from_start;2493$to_nlines=pop@from_nlines;24942495$line="<span class=\"chunk_info\">$prefix";2496for(my$i=0;$i<@from_text; ++$i) {2497if($from->{'href'}[$i]) {2498$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2499-class=>"list"},$from_text[$i]);2500}else{2501$line.=$from_text[$i];2502}2503$line.=" ";2504}2505if($to->{'href'}) {2506$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2507-class=>"list"},$to_text);2508}else{2509$line.=$to_text;2510}2511$line.="$prefix</span>".2512"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2513return$line;2514}25152516# process patch (diff) line (not to be used for diff headers),2517# returning HTML-formatted (but not wrapped) line.2518# If the line is passed as a reference, it is treated as HTML and not2519# esc_html()'ed.2520sub format_diff_line {2521my($line,$diff_class,$from,$to) =@_;25222523if(ref($line)) {2524$line=$$line;2525}else{2526chomp$line;2527$line= untabify($line);25282529if($from&&$to&&$line=~m/^\@{2} /) {2530$line= format_unidiff_chunk_header($line,$from,$to);2531}elsif($from&&$to&&$line=~m/^\@{3}/) {2532$line= format_cc_diff_chunk_header($line,$from,$to);2533}else{2534$line= esc_html($line, -nbsp=>1);2535}2536}25372538my$diff_classes="diff";2539$diff_classes.="$diff_class"if($diff_class);2540$line="<div class=\"$diff_classes\">$line</div>\n";25412542return$line;2543}25442545# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2546# linked. Pass the hash of the tree/commit to snapshot.2547sub format_snapshot_links {2548my($hash) =@_;2549my$num_fmts=@snapshot_fmts;2550if($num_fmts>1) {2551# A parenthesized list of links bearing format names.2552# e.g. "snapshot (_tar.gz_ _zip_)"2553return"snapshot (".join(' ',map2554$cgi->a({2555-href => href(2556 action=>"snapshot",2557 hash=>$hash,2558 snapshot_format=>$_2559)2560},$known_snapshot_formats{$_}{'display'})2561,@snapshot_fmts) .")";2562}elsif($num_fmts==1) {2563# A single "snapshot" link whose tooltip bears the format name.2564# i.e. "_snapshot_"2565my($fmt) =@snapshot_fmts;2566return2567$cgi->a({2568-href => href(2569 action=>"snapshot",2570 hash=>$hash,2571 snapshot_format=>$fmt2572),2573-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2574},"snapshot");2575}else{# $num_fmts == 02576returnundef;2577}2578}25792580## ......................................................................2581## functions returning values to be passed, perhaps after some2582## transformation, to other functions; e.g. returning arguments to href()25832584# returns hash to be passed to href to generate gitweb URL2585# in -title key it returns description of link2586sub get_feed_info {2587my$format=shift||'Atom';2588my%res= (action =>lc($format));2589my$matched_ref=0;25902591# feed links are possible only for project views2592return unless(defined$project);2593# some views should link to OPML, or to generic project feed,2594# or don't have specific feed yet (so they should use generic)2595return if(!$action||$action=~/^(?:tags|heads|forks|tag|search)$/x);25962597my$branch=undef;2598# branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix2599# (fullname) to differentiate from tag links; this also makes2600# possible to detect branch links2601formy$ref(get_branch_refs()) {2602if((defined$hash_base&&$hash_base=~m!^refs/\Q$ref\E/(.*)$!) ||2603(defined$hash&&$hash=~m!^refs/\Q$ref\E/(.*)$!)) {2604$branch=$1;2605$matched_ref=$ref;2606last;2607}2608}2609# find log type for feed description (title)2610my$type='log';2611if(defined$file_name) {2612$type="history of$file_name";2613$type.="/"if($actioneq'tree');2614$type.=" on '$branch'"if(defined$branch);2615}else{2616$type="log of$branch"if(defined$branch);2617}26182619$res{-title} =$type;2620$res{'hash'} = (defined$branch?"refs/$matched_ref/$branch":undef);2621$res{'file_name'} =$file_name;26222623return%res;2624}26252626## ----------------------------------------------------------------------2627## git utility subroutines, invoking git commands26282629# returns path to the core git executable and the --git-dir parameter as list2630sub git_cmd {2631$number_of_git_cmds++;2632return$GIT,'--git-dir='.$git_dir;2633}26342635# quote the given arguments for passing them to the shell2636# quote_command("command", "arg 1", "arg with ' and ! characters")2637# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2638# Try to avoid using this function wherever possible.2639sub quote_command {2640returnjoin(' ',2641map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2642}26432644# get HEAD ref of given project as hash2645sub git_get_head_hash {2646return git_get_full_hash(shift,'HEAD');2647}26482649sub git_get_full_hash {2650return git_get_hash(@_);2651}26522653sub git_get_short_hash {2654return git_get_hash(@_,'--short=7');2655}26562657sub git_get_hash {2658my($project,$hash,@options) =@_;2659my$o_git_dir=$git_dir;2660my$retval=undef;2661$git_dir="$projectroot/$project";2662if(open my$fd,'-|', git_cmd(),'rev-parse',2663'--verify','-q',@options,$hash) {2664$retval= <$fd>;2665chomp$retvalifdefined$retval;2666close$fd;2667}2668if(defined$o_git_dir) {2669$git_dir=$o_git_dir;2670}2671return$retval;2672}26732674# get type of given object2675sub git_get_type {2676my$hash=shift;26772678open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2679my$type= <$fd>;2680close$fdorreturn;2681chomp$type;2682return$type;2683}26842685# repository configuration2686our$config_file='';2687our%config;26882689# store multiple values for single key as anonymous array reference2690# single values stored directly in the hash, not as [ <value> ]2691sub hash_set_multi {2692my($hash,$key,$value) =@_;26932694if(!exists$hash->{$key}) {2695$hash->{$key} =$value;2696}elsif(!ref$hash->{$key}) {2697$hash->{$key} = [$hash->{$key},$value];2698}else{2699push@{$hash->{$key}},$value;2700}2701}27022703# return hash of git project configuration2704# optionally limited to some section, e.g. 'gitweb'2705sub git_parse_project_config {2706my$section_regexp=shift;2707my%config;27082709local$/="\0";27102711open my$fh,"-|", git_cmd(),"config",'-z','-l',2712orreturn;27132714while(my$keyval= <$fh>) {2715chomp$keyval;2716my($key,$value) =split(/\n/,$keyval,2);27172718 hash_set_multi(\%config,$key,$value)2719if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2720}2721close$fh;27222723return%config;2724}27252726# convert config value to boolean: 'true' or 'false'2727# no value, number > 0, 'true' and 'yes' values are true2728# rest of values are treated as false (never as error)2729sub config_to_bool {2730my$val=shift;27312732return1if!defined$val;# section.key27332734# strip leading and trailing whitespace2735$val=~s/^\s+//;2736$val=~s/\s+$//;27372738return(($val=~/^\d+$/&&$val) ||# section.key = 12739($val=~/^(?:true|yes)$/i));# section.key = true2740}27412742# convert config value to simple decimal number2743# an optional value suffix of 'k', 'm', or 'g' will cause the value2744# to be multiplied by 1024, 1048576, or 10737418242745sub config_to_int {2746my$val=shift;27472748# strip leading and trailing whitespace2749$val=~s/^\s+//;2750$val=~s/\s+$//;27512752if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2753$unit=lc($unit);2754# unknown unit is treated as 12755return$num* ($uniteq'g'?1073741824:2756$uniteq'm'?1048576:2757$uniteq'k'?1024:1);2758}2759return$val;2760}27612762# convert config value to array reference, if needed2763sub config_to_multi {2764my$val=shift;27652766returnref($val) ?$val: (defined($val) ? [$val] : []);2767}27682769sub git_get_project_config {2770my($key,$type) =@_;27712772return unlessdefined$git_dir;27732774# key sanity check2775return unless($key);2776# only subsection, if exists, is case sensitive,2777# and not lowercased by 'git config -z -l'2778if(my($hi,$mi,$lo) = ($key=~/^([^.]*)\.(.*)\.([^.]*)$/)) {2779$lo=~s/_//g;2780$key=join(".",lc($hi),$mi,lc($lo));2781return if($lo=~/\W/||$hi=~/\W/);2782}else{2783$key=lc($key);2784$key=~s/_//g;2785return if($key=~/\W/);2786}2787$key=~s/^gitweb\.//;27882789# type sanity check2790if(defined$type) {2791$type=~s/^--//;2792$type=undef2793unless($typeeq'bool'||$typeeq'int');2794}27952796# get config2797if(!defined$config_file||2798$config_filene"$git_dir/config") {2799%config= git_parse_project_config('gitweb');2800$config_file="$git_dir/config";2801}28022803# check if config variable (key) exists2804return unlessexists$config{"gitweb.$key"};28052806# ensure given type2807if(!defined$type) {2808return$config{"gitweb.$key"};2809}elsif($typeeq'bool') {2810# backward compatibility: 'git config --bool' returns true/false2811return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2812}elsif($typeeq'int') {2813return config_to_int($config{"gitweb.$key"});2814}2815return$config{"gitweb.$key"};2816}28172818# get hash of given path at given ref2819sub git_get_hash_by_path {2820my$base=shift;2821my$path=shift||returnundef;2822my$type=shift;28232824$path=~ s,/+$,,;28252826open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2827or die_error(500,"Open git-ls-tree failed");2828my$line= <$fd>;2829close$fdorreturnundef;28302831if(!defined$line) {2832# there is no tree or hash given by $path at $base2833returnundef;2834}28352836#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2837$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2838if(defined$type&&$typene$2) {2839# type doesn't match2840returnundef;2841}2842return$3;2843}28442845# get path of entry with given hash at given tree-ish (ref)2846# used to get 'from' filename for combined diff (merge commit) for renames2847sub git_get_path_by_hash {2848my$base=shift||return;2849my$hash=shift||return;28502851local$/="\0";28522853open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2854orreturnundef;2855while(my$line= <$fd>) {2856chomp$line;28572858#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2859#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2860if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2861close$fd;2862return$1;2863}2864}2865close$fd;2866returnundef;2867}28682869## ......................................................................2870## git utility functions, directly accessing git repository28712872# get the value of config variable either from file named as the variable2873# itself in the repository ($GIT_DIR/$name file), or from gitweb.$name2874# configuration variable in the repository config file.2875sub git_get_file_or_project_config {2876my($path,$name) =@_;28772878$git_dir="$projectroot/$path";2879open my$fd,'<',"$git_dir/$name"2880orreturn git_get_project_config($name);2881my$conf= <$fd>;2882close$fd;2883if(defined$conf) {2884chomp$conf;2885}2886return$conf;2887}28882889sub git_get_project_description {2890my$path=shift;2891return git_get_file_or_project_config($path,'description');2892}28932894sub git_get_project_category {2895my$path=shift;2896return git_get_file_or_project_config($path,'category');2897}289828992900# supported formats:2901# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2902# - if its contents is a number, use it as tag weight,2903# - otherwise add a tag with weight 12904# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2905# the same value multiple times increases tag weight2906# * `gitweb.ctag' multi-valued repo config variable2907sub git_get_project_ctags {2908my$project=shift;2909my$ctags= {};29102911$git_dir="$projectroot/$project";2912if(opendir my$dh,"$git_dir/ctags") {2913my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2914foreachmy$tagfile(@files) {2915open my$ct,'<',$tagfile2916ornext;2917my$val= <$ct>;2918chomp$valif$val;2919close$ct;29202921(my$ctag=$tagfile) =~ s#.*/##;2922if($val=~/^\d+$/) {2923$ctags->{$ctag} =$val;2924}else{2925$ctags->{$ctag} =1;2926}2927}2928closedir$dh;29292930}elsif(open my$fh,'<',"$git_dir/ctags") {2931while(my$line= <$fh>) {2932chomp$line;2933$ctags->{$line}++if$line;2934}2935close$fh;29362937}else{2938my$taglist= config_to_multi(git_get_project_config('ctag'));2939foreachmy$tag(@$taglist) {2940$ctags->{$tag}++;2941}2942}29432944return$ctags;2945}29462947# return hash, where keys are content tags ('ctags'),2948# and values are sum of weights of given tag in every project2949sub git_gather_all_ctags {2950my$projects=shift;2951my$ctags= {};29522953foreachmy$p(@$projects) {2954foreachmy$ct(keys%{$p->{'ctags'}}) {2955$ctags->{$ct} +=$p->{'ctags'}->{$ct};2956}2957}29582959return$ctags;2960}29612962sub git_populate_project_tagcloud {2963my$ctags=shift;29642965# First, merge different-cased tags; tags vote on casing2966my%ctags_lc;2967foreach(keys%$ctags) {2968$ctags_lc{lc$_}->{count} +=$ctags->{$_};2969if(not$ctags_lc{lc$_}->{topcount}2970or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2971$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2972$ctags_lc{lc$_}->{topname} =$_;2973}2974}29752976my$cloud;2977my$matched=$input_params{'ctag'};2978if(eval{require HTML::TagCloud;1; }) {2979$cloud= HTML::TagCloud->new;2980foreachmy$ctag(sort keys%ctags_lc) {2981# Pad the title with spaces so that the cloud looks2982# less crammed.2983my$title= esc_html($ctags_lc{$ctag}->{topname});2984$title=~s/ / /g;2985$title=~s/^/ /g;2986$title=~s/$/ /g;2987if(defined$matched&&$matchedeq$ctag) {2988$title=qq(<span class="match">$title</span>);2989}2990$cloud->add($title, href(project=>undef, ctag=>$ctag),2991$ctags_lc{$ctag}->{count});2992}2993}else{2994$cloud= {};2995foreachmy$ctag(keys%ctags_lc) {2996my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2997if(defined$matched&&$matchedeq$ctag) {2998$title=qq(<span class="match">$title</span>);2999}3000$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};3001$cloud->{$ctag}{ctag} =3002$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);3003}3004}3005return$cloud;3006}30073008sub git_show_project_tagcloud {3009my($cloud,$count) =@_;3010if(ref$cloudeq'HTML::TagCloud') {3011return$cloud->html_and_css($count);3012}else{3013my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;3014return3015'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.3016join(', ',map{3017$cloud->{$_}->{'ctag'}3018}splice(@tags,0,$count)) .3019'</div>';3020}3021}30223023sub git_get_project_url_list {3024my$path=shift;30253026$git_dir="$projectroot/$path";3027open my$fd,'<',"$git_dir/cloneurl"3028orreturnwantarray?3029@{ config_to_multi(git_get_project_config('url')) } :3030 config_to_multi(git_get_project_config('url'));3031my@git_project_url_list=map{chomp;$_} <$fd>;3032close$fd;30333034returnwantarray?@git_project_url_list: \@git_project_url_list;3035}30363037sub git_get_projects_list {3038my$filter=shift||'';3039my$paranoid=shift;3040my@list;30413042if(-d $projects_list) {3043# search in directory3044my$dir=$projects_list;3045# remove the trailing "/"3046$dir=~s!/+$!!;3047my$pfxlen=length("$dir");3048my$pfxdepth= ($dir=~tr!/!!);3049# when filtering, search only given subdirectory3050if($filter&& !$paranoid) {3051$dir.="/$filter";3052$dir=~s!/+$!!;3053}30543055 File::Find::find({3056 follow_fast =>1,# follow symbolic links3057 follow_skip =>2,# ignore duplicates3058 dangling_symlinks =>0,# ignore dangling symlinks, silently3059 wanted =>sub{3060# global variables3061our$project_maxdepth;3062our$projectroot;3063# skip project-list toplevel, if we get it.3064return if(m!^[/.]$!);3065# only directories can be git repositories3066return unless(-d $_);3067# need search permission3068return unless(-x $_);3069# don't traverse too deep (Find is super slow on os x)3070# $project_maxdepth excludes depth of $projectroot3071if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {3072$File::Find::prune =1;3073return;3074}30753076my$path=substr($File::Find::name,$pfxlen+1);3077# paranoidly only filter here3078if($paranoid&&$filter&&$path!~m!^\Q$filter\E/!) {3079next;3080}3081# we check related file in $projectroot3082if(check_export_ok("$projectroot/$path")) {3083push@list, { path =>$path};3084$File::Find::prune =1;3085}3086},3087},"$dir");30883089}elsif(-f $projects_list) {3090# read from file(url-encoded):3091# 'git%2Fgit.git Linus+Torvalds'3092# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'3093# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'3094open my$fd,'<',$projects_listorreturn;3095 PROJECT:3096while(my$line= <$fd>) {3097chomp$line;3098my($path,$owner) =split' ',$line;3099$path= unescape($path);3100$owner= unescape($owner);3101if(!defined$path) {3102next;3103}3104# if $filter is rpovided, check if $path begins with $filter3105if($filter&&$path!~m!^\Q$filter\E/!) {3106next;3107}3108if(check_export_ok("$projectroot/$path")) {3109my$pr= {3110 path =>$path3111};3112if($owner) {3113$pr->{'owner'} = to_utf8($owner);3114}3115push@list,$pr;3116}3117}3118close$fd;3119}3120return@list;3121}31223123# written with help of Tree::Trie module (Perl Artistic License, GPL compatible)3124# as side effects it sets 'forks' field to list of forks for forked projects3125sub filter_forks_from_projects_list {3126my$projects=shift;31273128my%trie;# prefix tree of directories (path components)3129# generate trie out of those directories that might contain forks3130foreachmy$pr(@$projects) {3131my$path=$pr->{'path'};3132$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory3133next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'3134next unless($path);# skip '.git' repository: tests, git-instaweb3135next unless(-d "$projectroot/$path");# containing directory exists3136$pr->{'forks'} = [];# there can be 0 or more forks of project31373138# add to trie3139my@dirs=split('/',$path);3140# walk the trie, until either runs out of components or out of trie3141my$ref= \%trie;3142while(scalar@dirs&&3143exists($ref->{$dirs[0]})) {3144$ref=$ref->{shift@dirs};3145}3146# create rest of trie structure from rest of components3147foreachmy$dir(@dirs) {3148$ref=$ref->{$dir} = {};3149}3150# create end marker, store $pr as a data3151$ref->{''} =$prif(!exists$ref->{''});3152}31533154# filter out forks, by finding shortest prefix match for paths3155my@filtered;3156 PROJECT:3157foreachmy$pr(@$projects) {3158# trie lookup3159my$ref= \%trie;3160 DIR:3161foreachmy$dir(split('/',$pr->{'path'})) {3162if(exists$ref->{''}) {3163# found [shortest] prefix, is a fork - skip it3164push@{$ref->{''}{'forks'}},$pr;3165next PROJECT;3166}3167if(!exists$ref->{$dir}) {3168# not in trie, cannot have prefix, not a fork3169push@filtered,$pr;3170next PROJECT;3171}3172# If the dir is there, we just walk one step down the trie.3173$ref=$ref->{$dir};3174}3175# we ran out of trie3176# (shouldn't happen: it's either no match, or end marker)3177push@filtered,$pr;3178}31793180return@filtered;3181}31823183# note: fill_project_list_info must be run first,3184# for 'descr_long' and 'ctags' to be filled3185sub search_projects_list {3186my($projlist,%opts) =@_;3187my$tagfilter=$opts{'tagfilter'};3188my$search_re=$opts{'search_regexp'};31893190return@$projlist3191unless($tagfilter||$search_re);31923193# searching projects require filling to be run before it;3194 fill_project_list_info($projlist,3195$tagfilter?'ctags': (),3196$search_re? ('path','descr') : ());3197my@projects;3198 PROJECT:3199foreachmy$pr(@$projlist) {32003201if($tagfilter) {3202next unlessref($pr->{'ctags'})eq'HASH';3203next unless3204grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};3205}32063207if($search_re) {3208next unless3209$pr->{'path'} =~/$search_re/||3210$pr->{'descr_long'} =~/$search_re/;3211}32123213push@projects,$pr;3214}32153216return@projects;3217}32183219our$gitweb_project_owner=undef;3220sub git_get_project_list_from_file {32213222return if(defined$gitweb_project_owner);32233224$gitweb_project_owner= {};3225# read from file (url-encoded):3226# 'git%2Fgit.git Linus+Torvalds'3227# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'3228# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'3229if(-f $projects_list) {3230open(my$fd,'<',$projects_list);3231while(my$line= <$fd>) {3232chomp$line;3233my($pr,$ow) =split' ',$line;3234$pr= unescape($pr);3235$ow= unescape($ow);3236$gitweb_project_owner->{$pr} = to_utf8($ow);3237}3238close$fd;3239}3240}32413242sub git_get_project_owner {3243my$project=shift;3244my$owner;32453246returnundefunless$project;3247$git_dir="$projectroot/$project";32483249if(!defined$gitweb_project_owner) {3250 git_get_project_list_from_file();3251}32523253if(exists$gitweb_project_owner->{$project}) {3254$owner=$gitweb_project_owner->{$project};3255}3256if(!defined$owner){3257$owner= git_get_project_config('owner');3258}3259if(!defined$owner) {3260$owner= get_file_owner("$git_dir");3261}32623263return$owner;3264}32653266sub git_get_last_activity {3267my($path) =@_;3268my$fd;32693270$git_dir="$projectroot/$path";3271open($fd,"-|", git_cmd(),'for-each-ref',3272'--format=%(committer)',3273'--sort=-committerdate',3274'--count=1',3275map{"refs/$_"} get_branch_refs ())orreturn;3276my$most_recent= <$fd>;3277close$fdorreturn;3278if(defined$most_recent&&3279$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {3280my$timestamp=$1;3281my$age=time-$timestamp;3282return($age, age_string($age));3283}3284return(undef,undef);3285}32863287# Implementation note: when a single remote is wanted, we cannot use 'git3288# remote show -n' because that command always work (assuming it's a remote URL3289# if it's not defined), and we cannot use 'git remote show' because that would3290# try to make a network roundtrip. So the only way to find if that particular3291# remote is defined is to walk the list provided by 'git remote -v' and stop if3292# and when we find what we want.3293sub git_get_remotes_list {3294my$wanted=shift;3295my%remotes= ();32963297open my$fd,'-|', git_cmd(),'remote','-v';3298return unless$fd;3299while(my$remote= <$fd>) {3300chomp$remote;3301$remote=~s!\t(.*?)\s+\((\w+)\)$!!;3302next if$wantedand not$remoteeq$wanted;3303my($url,$key) = ($1,$2);33043305$remotes{$remote} ||= {'heads'=> () };3306$remotes{$remote}{$key} =$url;3307}3308close$fdorreturn;3309returnwantarray?%remotes: \%remotes;3310}33113312# Takes a hash of remotes as first parameter and fills it by adding the3313# available remote heads for each of the indicated remotes.3314sub fill_remote_heads {3315my$remotes=shift;3316my@heads=map{"remotes/$_"}keys%$remotes;3317my@remoteheads= git_get_heads_list(undef,@heads);3318foreachmy$remote(keys%$remotes) {3319$remotes->{$remote}{'heads'} = [grep{3320$_->{'name'} =~s!^$remote/!!3321}@remoteheads];3322}3323}33243325sub git_get_references {3326my$type=shift||"";3327my%refs;3328# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113329# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3330open my$fd,"-|", git_cmd(),"show-ref","--dereference",3331($type? ("--","refs/$type") : ())# use -- <pattern> if $type3332orreturn;33333334while(my$line= <$fd>) {3335chomp$line;3336if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3337if(defined$refs{$1}) {3338push@{$refs{$1}},$2;3339}else{3340$refs{$1} = [$2];3341}3342}3343}3344close$fdorreturn;3345return \%refs;3346}33473348sub git_get_rev_name_tags {3349my$hash=shift||returnundef;33503351open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3352orreturn;3353my$name_rev= <$fd>;3354close$fd;33553356if($name_rev=~ m|^$hash tags/(.*)$|) {3357return$1;3358}else{3359# catches also '$hash undefined' output3360returnundef;3361}3362}33633364## ----------------------------------------------------------------------3365## parse to hash functions33663367sub parse_date {3368my$epoch=shift;3369my$tz=shift||"-0000";33703371my%date;3372my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3373my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3374my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3375$date{'hour'} =$hour;3376$date{'minute'} =$min;3377$date{'mday'} =$mday;3378$date{'day'} =$days[$wday];3379$date{'month'} =$months[$mon];3380$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3381$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3382$date{'mday-time'} =sprintf"%d%s%02d:%02d",3383$mday,$months[$mon],$hour,$min;3384$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",33851900+$year,1+$mon,$mday,$hour,$min,$sec;33863387my($tz_sign,$tz_hour,$tz_min) =3388($tz=~m/^([-+])(\d\d)(\d\d)$/);3389$tz_sign= ($tz_signeq'-'? -1: +1);3390my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3391($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3392$date{'hour_local'} =$hour;3393$date{'minute_local'} =$min;3394$date{'tz_local'} =$tz;3395$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",33961900+$year,$mon+1,$mday,3397$hour,$min,$sec,$tz);3398return%date;3399}34003401sub parse_tag {3402my$tag_id=shift;3403my%tag;3404my@comment;34053406open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3407$tag{'id'} =$tag_id;3408while(my$line= <$fd>) {3409chomp$line;3410if($line=~m/^object ([0-9a-fA-F]{40})$/) {3411$tag{'object'} =$1;3412}elsif($line=~m/^type (.+)$/) {3413$tag{'type'} =$1;3414}elsif($line=~m/^tag (.+)$/) {3415$tag{'name'} =$1;3416}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3417$tag{'author'} =$1;3418$tag{'author_epoch'} =$2;3419$tag{'author_tz'} =$3;3420if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3421$tag{'author_name'} =$1;3422$tag{'author_email'} =$2;3423}else{3424$tag{'author_name'} =$tag{'author'};3425}3426}elsif($line=~m/--BEGIN/) {3427push@comment,$line;3428last;3429}elsif($lineeq"") {3430last;3431}3432}3433push@comment, <$fd>;3434$tag{'comment'} = \@comment;3435close$fdorreturn;3436if(!defined$tag{'name'}) {3437return3438};3439return%tag3440}34413442sub parse_commit_text {3443my($commit_text,$withparents) =@_;3444my@commit_lines=split'\n',$commit_text;3445my%co;34463447pop@commit_lines;# Remove '\0'34483449if(!@commit_lines) {3450return;3451}34523453my$header=shift@commit_lines;3454if($header!~m/^[0-9a-fA-F]{40}/) {3455return;3456}3457($co{'id'},my@parents) =split' ',$header;3458while(my$line=shift@commit_lines) {3459last if$lineeq"\n";3460if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3461$co{'tree'} =$1;3462}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3463push@parents,$1;3464}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3465$co{'author'} = to_utf8($1);3466$co{'author_epoch'} =$2;3467$co{'author_tz'} =$3;3468if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3469$co{'author_name'} =$1;3470$co{'author_email'} =$2;3471}else{3472$co{'author_name'} =$co{'author'};3473}3474}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3475$co{'committer'} = to_utf8($1);3476$co{'committer_epoch'} =$2;3477$co{'committer_tz'} =$3;3478if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3479$co{'committer_name'} =$1;3480$co{'committer_email'} =$2;3481}else{3482$co{'committer_name'} =$co{'committer'};3483}3484}3485}3486if(!defined$co{'tree'}) {3487return;3488};3489$co{'parents'} = \@parents;3490$co{'parent'} =$parents[0];34913492foreachmy$title(@commit_lines) {3493$title=~s/^ //;3494if($titlene"") {3495$co{'title'} = chop_str($title,80,5);3496# remove leading stuff of merges to make the interesting part visible3497if(length($title) >50) {3498$title=~s/^Automatic //;3499$title=~s/^merge (of|with) /Merge ... /i;3500if(length($title) >50) {3501$title=~s/(http|rsync):\/\///;3502}3503if(length($title) >50) {3504$title=~s/(master|www|rsync)\.//;3505}3506if(length($title) >50) {3507$title=~s/kernel.org:?//;3508}3509if(length($title) >50) {3510$title=~s/\/pub\/scm//;3511}3512}3513$co{'title_short'} = chop_str($title,50,5);3514last;3515}3516}3517if(!defined$co{'title'} ||$co{'title'}eq"") {3518$co{'title'} =$co{'title_short'} ='(no commit message)';3519}3520# remove added spaces3521foreachmy$line(@commit_lines) {3522$line=~s/^ //;3523}3524$co{'comment'} = \@commit_lines;35253526my$age=time-$co{'committer_epoch'};3527$co{'age'} =$age;3528$co{'age_string'} = age_string($age);3529my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3530if($age>60*60*24*7*2) {3531$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3532$co{'age_string_age'} =$co{'age_string'};3533}else{3534$co{'age_string_date'} =$co{'age_string'};3535$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3536}3537return%co;3538}35393540sub parse_commit {3541my($commit_id) =@_;3542my%co;35433544local$/="\0";35453546open my$fd,"-|", git_cmd(),"rev-list",3547"--parents",3548"--header",3549"--max-count=1",3550$commit_id,3551"--",3552or die_error(500,"Open git-rev-list failed");3553%co= parse_commit_text(<$fd>,1);3554close$fd;35553556return%co;3557}35583559sub parse_commits {3560my($commit_id,$maxcount,$skip,$filename,@args) =@_;3561my@cos;35623563$maxcount||=1;3564$skip||=0;35653566local$/="\0";35673568open my$fd,"-|", git_cmd(),"rev-list",3569"--header",3570@args,3571("--max-count=".$maxcount),3572("--skip=".$skip),3573@extra_options,3574$commit_id,3575"--",3576($filename? ($filename) : ())3577or die_error(500,"Open git-rev-list failed");3578while(my$line= <$fd>) {3579my%co= parse_commit_text($line);3580push@cos, \%co;3581}3582close$fd;35833584returnwantarray?@cos: \@cos;3585}35863587# parse line of git-diff-tree "raw" output3588sub parse_difftree_raw_line {3589my$line=shift;3590my%res;35913592# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3593# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3594if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3595$res{'from_mode'} =$1;3596$res{'to_mode'} =$2;3597$res{'from_id'} =$3;3598$res{'to_id'} =$4;3599$res{'status'} =$5;3600$res{'similarity'} =$6;3601if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3602($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3603}else{3604$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3605}3606}3607# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3608# combined diff (for merge commit)3609elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3610$res{'nparents'} =length($1);3611$res{'from_mode'} = [split(' ',$2) ];3612$res{'to_mode'} =pop@{$res{'from_mode'}};3613$res{'from_id'} = [split(' ',$3) ];3614$res{'to_id'} =pop@{$res{'from_id'}};3615$res{'status'} = [split('',$4) ];3616$res{'to_file'} = unquote($5);3617}3618# 'c512b523472485aef4fff9e57b229d9d243c967f'3619elsif($line=~m/^([0-9a-fA-F]{40})$/) {3620$res{'commit'} =$1;3621}36223623returnwantarray?%res: \%res;3624}36253626# wrapper: return parsed line of git-diff-tree "raw" output3627# (the argument might be raw line, or parsed info)3628sub parsed_difftree_line {3629my$line_or_ref=shift;36303631if(ref($line_or_ref)eq"HASH") {3632# pre-parsed (or generated by hand)3633return$line_or_ref;3634}else{3635return parse_difftree_raw_line($line_or_ref);3636}3637}36383639# parse line of git-ls-tree output3640sub parse_ls_tree_line {3641my$line=shift;3642my%opts=@_;3643my%res;36443645if($opts{'-l'}) {3646#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3647$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;36483649$res{'mode'} =$1;3650$res{'type'} =$2;3651$res{'hash'} =$3;3652$res{'size'} =$4;3653if($opts{'-z'}) {3654$res{'name'} =$5;3655}else{3656$res{'name'} = unquote($5);3657}3658}else{3659#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3660$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;36613662$res{'mode'} =$1;3663$res{'type'} =$2;3664$res{'hash'} =$3;3665if($opts{'-z'}) {3666$res{'name'} =$4;3667}else{3668$res{'name'} = unquote($4);3669}3670}36713672returnwantarray?%res: \%res;3673}36743675# generates _two_ hashes, references to which are passed as 2 and 3 argument3676sub parse_from_to_diffinfo {3677my($diffinfo,$from,$to,@parents) =@_;36783679if($diffinfo->{'nparents'}) {3680# combined diff3681$from->{'file'} = [];3682$from->{'href'} = [];3683 fill_from_file_info($diffinfo,@parents)3684unlessexists$diffinfo->{'from_file'};3685for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3686$from->{'file'}[$i] =3687defined$diffinfo->{'from_file'}[$i] ?3688$diffinfo->{'from_file'}[$i] :3689$diffinfo->{'to_file'};3690if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3691$from->{'href'}[$i] = href(action=>"blob",3692 hash_base=>$parents[$i],3693 hash=>$diffinfo->{'from_id'}[$i],3694 file_name=>$from->{'file'}[$i]);3695}else{3696$from->{'href'}[$i] =undef;3697}3698}3699}else{3700# ordinary (not combined) diff3701$from->{'file'} =$diffinfo->{'from_file'};3702if($diffinfo->{'status'}ne"A") {# not new (added) file3703$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3704 hash=>$diffinfo->{'from_id'},3705 file_name=>$from->{'file'});3706}else{3707delete$from->{'href'};3708}3709}37103711$to->{'file'} =$diffinfo->{'to_file'};3712if(!is_deleted($diffinfo)) {# file exists in result3713$to->{'href'} = href(action=>"blob", hash_base=>$hash,3714 hash=>$diffinfo->{'to_id'},3715 file_name=>$to->{'file'});3716}else{3717delete$to->{'href'};3718}3719}37203721## ......................................................................3722## parse to array of hashes functions37233724sub git_get_heads_list {3725my($limit,@classes) =@_;3726@classes= get_branch_refs()unless@classes;3727my@patterns=map{"refs/$_"}@classes;3728my@headslist;37293730open my$fd,'-|', git_cmd(),'for-each-ref',3731($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3732'--format=%(objectname) %(refname) %(subject)%00%(committer)',3733@patterns3734orreturn;3735while(my$line= <$fd>) {3736my%ref_item;37373738chomp$line;3739my($refinfo,$committerinfo) =split(/\0/,$line);3740my($hash,$name,$title) =split(' ',$refinfo,3);3741my($committer,$epoch,$tz) =3742($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3743$ref_item{'fullname'} =$name;3744my$strip_refs=join'|',map{quotemeta} get_branch_refs();3745$name=~s!^refs/($strip_refs|remotes)/!!;3746$ref_item{'name'} =$name;3747# for refs neither in 'heads' nor 'remotes' we want to3748# show their ref dir3749my$ref_dir= (defined$1) ?$1:'';3750if($ref_dirne''and$ref_dirne'heads'and$ref_dirne'remotes') {3751$ref_item{'name'} .=' ('.$ref_dir.')';3752}37533754$ref_item{'id'} =$hash;3755$ref_item{'title'} =$title||'(no commit message)';3756$ref_item{'epoch'} =$epoch;3757if($epoch) {3758$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3759}else{3760$ref_item{'age'} ="unknown";3761}37623763push@headslist, \%ref_item;3764}3765close$fd;37663767returnwantarray?@headslist: \@headslist;3768}37693770sub git_get_tags_list {3771my$limit=shift;3772my@tagslist;37733774open my$fd,'-|', git_cmd(),'for-each-ref',3775($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3776'--format=%(objectname) %(objecttype) %(refname) '.3777'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3778'refs/tags'3779orreturn;3780while(my$line= <$fd>) {3781my%ref_item;37823783chomp$line;3784my($refinfo,$creatorinfo) =split(/\0/,$line);3785my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3786my($creator,$epoch,$tz) =3787($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3788$ref_item{'fullname'} =$name;3789$name=~s!^refs/tags/!!;37903791$ref_item{'type'} =$type;3792$ref_item{'id'} =$id;3793$ref_item{'name'} =$name;3794if($typeeq"tag") {3795$ref_item{'subject'} =$title;3796$ref_item{'reftype'} =$reftype;3797$ref_item{'refid'} =$refid;3798}else{3799$ref_item{'reftype'} =$type;3800$ref_item{'refid'} =$id;3801}38023803if($typeeq"tag"||$typeeq"commit") {3804$ref_item{'epoch'} =$epoch;3805if($epoch) {3806$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3807}else{3808$ref_item{'age'} ="unknown";3809}3810}38113812push@tagslist, \%ref_item;3813}3814close$fd;38153816returnwantarray?@tagslist: \@tagslist;3817}38183819## ----------------------------------------------------------------------3820## filesystem-related functions38213822sub get_file_owner {3823my$path=shift;38243825my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3826my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3827if(!defined$gcos) {3828returnundef;3829}3830my$owner=$gcos;3831$owner=~s/[,;].*$//;3832return to_utf8($owner);3833}38343835# assume that file exists3836sub insert_file {3837my$filename=shift;38383839open my$fd,'<',$filename;3840print map{ to_utf8($_) } <$fd>;3841close$fd;3842}38433844## ......................................................................3845## mimetype related functions38463847sub mimetype_guess_file {3848my$filename=shift;3849my$mimemap=shift;3850-r $mimemaporreturnundef;38513852my%mimemap;3853open(my$mh,'<',$mimemap)orreturnundef;3854while(<$mh>) {3855next ifm/^#/;# skip comments3856my($mimetype,@exts) =split(/\s+/);3857foreachmy$ext(@exts) {3858$mimemap{$ext} =$mimetype;3859}3860}3861close($mh);38623863$filename=~/\.([^.]*)$/;3864return$mimemap{$1};3865}38663867sub mimetype_guess {3868my$filename=shift;3869my$mime;3870$filename=~/\./orreturnundef;38713872if($mimetypes_file) {3873my$file=$mimetypes_file;3874if($file!~m!^/!) {# if it is relative path3875# it is relative to project3876$file="$projectroot/$project/$file";3877}3878$mime= mimetype_guess_file($filename,$file);3879}3880$mime||= mimetype_guess_file($filename,'/etc/mime.types');3881return$mime;3882}38833884sub blob_mimetype {3885my$fd=shift;3886my$filename=shift;38873888if($filename) {3889my$mime= mimetype_guess($filename);3890$mimeandreturn$mime;3891}38923893# just in case3894return$default_blob_plain_mimetypeunless$fd;38953896if(-T $fd) {3897return'text/plain';3898}elsif(!$filename) {3899return'application/octet-stream';3900}elsif($filename=~m/\.png$/i) {3901return'image/png';3902}elsif($filename=~m/\.gif$/i) {3903return'image/gif';3904}elsif($filename=~m/\.jpe?g$/i) {3905return'image/jpeg';3906}else{3907return'application/octet-stream';3908}3909}39103911sub blob_contenttype {3912my($fd,$file_name,$type) =@_;39133914$type||= blob_mimetype($fd,$file_name);3915if($typeeq'text/plain'&&defined$default_text_plain_charset) {3916$type.="; charset=$default_text_plain_charset";3917}39183919return$type;3920}39213922# guess file syntax for syntax highlighting; return undef if no highlighting3923# the name of syntax can (in the future) depend on syntax highlighter used3924sub guess_file_syntax {3925my($highlight,$file_name) =@_;3926returnundefunless($highlight&&defined$file_name);3927my$basename= basename($file_name,'.in');3928return$highlight_basename{$basename}3929ifexists$highlight_basename{$basename};39303931$basename=~/\.([^.]*)$/;3932my$ext=$1orreturnundef;3933return$highlight_ext{$ext}3934ifexists$highlight_ext{$ext};39353936returnundef;3937}39383939# run highlighter and return FD of its output,3940# or return original FD if no highlighting3941sub run_highlighter {3942my($fd,$highlight,$syntax) =@_;3943return$fdunless($highlight);39443945close$fd;3946my$syntax_arg= (defined$syntax) ?"--syntax$syntax":"--force";3947open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3948 quote_command($^X,'-CO','-MEncode=decode,FB_DEFAULT','-pse',3949'$_= decode($fe,$_, FB_DEFAULT) if !utf8::decode($_);',3950'--',"-fe=$fallback_encoding")." | ".3951 quote_command($highlight_bin).3952" --replace-tabs=8 --fragment$syntax_arg|"3953or die_error(500,"Couldn't open file or run syntax highlighter");3954return$fd;3955}39563957## ======================================================================3958## functions printing HTML: header, footer, error page39593960sub get_page_title {3961my$title= to_utf8($site_name);39623963unless(defined$project) {3964if(defined$project_filter) {3965$title.=" - projects in '". esc_path($project_filter) ."'";3966}3967return$title;3968}3969$title.=" - ". to_utf8($project);39703971return$titleunless(defined$action);3972$title.="/$action";# $action is US-ASCII (7bit ASCII)39733974return$titleunless(defined$file_name);3975$title.=" - ". esc_path($file_name);3976if($actioneq"tree"&&$file_name!~ m|/$|) {3977$title.="/";3978}39793980return$title;3981}39823983sub get_content_type_html {3984# require explicit support from the UA if we are to send the page as3985# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3986# we have to do this because MSIE sometimes globs '*/*', pretending to3987# support xhtml+xml but choking when it gets what it asked for.3988if(defined$cgi->http('HTTP_ACCEPT') &&3989$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3990$cgi->Accept('application/xhtml+xml') !=0) {3991return'application/xhtml+xml';3992}else{3993return'text/html';3994}3995}39963997sub print_feed_meta {3998if(defined$project) {3999my%href_params= get_feed_info();4000if(!exists$href_params{'-title'}) {4001$href_params{'-title'} ='log';4002}40034004foreachmy$format(qw(RSS Atom)) {4005my$type=lc($format);4006my%link_attr= (4007'-rel'=>'alternate',4008'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),4009'-type'=>"application/$type+xml"4010);40114012$href_params{'extra_options'} =undef;4013$href_params{'action'} =$type;4014$link_attr{'-href'} = href(%href_params);4015print"<link ".4016"rel=\"$link_attr{'-rel'}\"".4017"title=\"$link_attr{'-title'}\"".4018"href=\"$link_attr{'-href'}\"".4019"type=\"$link_attr{'-type'}\"".4020"/>\n";40214022$href_params{'extra_options'} ='--no-merges';4023$link_attr{'-href'} = href(%href_params);4024$link_attr{'-title'} .=' (no merges)';4025print"<link ".4026"rel=\"$link_attr{'-rel'}\"".4027"title=\"$link_attr{'-title'}\"".4028"href=\"$link_attr{'-href'}\"".4029"type=\"$link_attr{'-type'}\"".4030"/>\n";4031}40324033}else{4034printf('<link rel="alternate" title="%sprojects list" '.4035'href="%s" type="text/plain; charset=utf-8" />'."\n",4036 esc_attr($site_name), href(project=>undef, action=>"project_index"));4037printf('<link rel="alternate" title="%sprojects feeds" '.4038'href="%s" type="text/x-opml" />'."\n",4039 esc_attr($site_name), href(project=>undef, action=>"opml"));4040}4041}40424043sub print_header_links {4044my$status=shift;40454046# print out each stylesheet that exist, providing backwards capability4047# for those people who defined $stylesheet in a config file4048if(defined$stylesheet) {4049print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";4050}else{4051foreachmy$stylesheet(@stylesheets) {4052next unless$stylesheet;4053print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";4054}4055}4056 print_feed_meta()4057if($statuseq'200 OK');4058if(defined$favicon) {4059printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);4060}4061}40624063sub print_nav_breadcrumbs_path {4064my$dirprefix=undef;4065while(my$part=shift) {4066$dirprefix.="/"ifdefined$dirprefix;4067$dirprefix.=$part;4068print$cgi->a({-href => href(project =>undef,4069 project_filter =>$dirprefix,4070 action =>"project_list")},4071 esc_html($part)) ." / ";4072}4073}40744075sub print_nav_breadcrumbs {4076my%opts=@_;40774078formy$crumb(@extra_breadcrumbs, [$home_link_str=>$home_link]) {4079print$cgi->a({-href => esc_url($crumb->[1])},$crumb->[0]) ." / ";4080}4081if(defined$project) {4082my@dirname=split'/',$project;4083my$projectbasename=pop@dirname;4084 print_nav_breadcrumbs_path(@dirname);4085print$cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));4086if(defined$action) {4087my$action_print=$action;4088if(defined$opts{-action_extra}) {4089$action_print=$cgi->a({-href => href(action=>$action)},4090$action);4091}4092print" /$action_print";4093}4094if(defined$opts{-action_extra}) {4095print" /$opts{-action_extra}";4096}4097print"\n";4098}elsif(defined$project_filter) {4099 print_nav_breadcrumbs_path(split'/',$project_filter);4100}4101}41024103sub print_search_form {4104if(!defined$searchtext) {4105$searchtext="";4106}4107my$search_hash;4108if(defined$hash_base) {4109$search_hash=$hash_base;4110}elsif(defined$hash) {4111$search_hash=$hash;4112}else{4113$search_hash="HEAD";4114}4115my$action=$my_uri;4116my$use_pathinfo= gitweb_check_feature('pathinfo');4117if($use_pathinfo) {4118$action.="/".esc_url($project);4119}4120print$cgi->start_form(-method=>"get", -action =>$action) .4121"<div class=\"search\">\n".4122(!$use_pathinfo&&4123$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .4124$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".4125$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".4126$cgi->popup_menu(-name =>'st', -default=>'commit',4127-values=> ['commit','grep','author','committer','pickaxe']) .4128" ".$cgi->a({-href => href(action=>"search_help"),4129-title =>"search help"},"?") ." search:\n",4130$cgi->textfield(-name =>"s", -value =>$searchtext, -override =>1) ."\n".4131"<span title=\"Extended regular expression\">".4132$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',4133-checked =>$search_use_regexp) .4134"</span>".4135"</div>".4136$cgi->end_form() ."\n";4137}41384139sub git_header_html {4140my$status=shift||"200 OK";4141my$expires=shift;4142my%opts=@_;41434144my$title= get_page_title();4145my$content_type= get_content_type_html();4146print$cgi->header(-type=>$content_type, -charset =>'utf-8',4147-status=>$status, -expires =>$expires)4148unless($opts{'-no_http_header'});4149my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';4150print<<EOF;4151<?xml version="1.0" encoding="utf-8"?>4152<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4153<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">4154<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->4155<!-- git core binaries version$git_version-->4156<head>4157<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>4158<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>4159<meta name="robots" content="index, nofollow"/>4160<title>$title</title>4161EOF4162# the stylesheet, favicon etc urls won't work correctly with path_info4163# unless we set the appropriate base URL4164if($ENV{'PATH_INFO'}) {4165print"<base href=\"".esc_url($base_url)."\"/>\n";4166}4167 print_header_links($status);41684169if(defined$site_html_head_string) {4170print to_utf8($site_html_head_string);4171}41724173print"</head>\n".4174"<body>\n";41754176if(defined$site_header&& -f $site_header) {4177 insert_file($site_header);4178}41794180print"<div class=\"page_header\">\n";4181if(defined$logo) {4182print$cgi->a({-href => esc_url($logo_url),4183-title =>$logo_label},4184$cgi->img({-src => esc_url($logo),4185-width =>72, -height =>27,4186-alt =>"git",4187-class=>"logo"}));4188}4189 print_nav_breadcrumbs(%opts);4190print"</div>\n";41914192my$have_search= gitweb_check_feature('search');4193if(defined$project&&$have_search) {4194 print_search_form();4195}4196}41974198sub git_footer_html {4199my$feed_class='rss_logo';42004201print"<div class=\"page_footer\">\n";4202if(defined$project) {4203my$descr= git_get_project_description($project);4204if(defined$descr) {4205print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";4206}42074208my%href_params= get_feed_info();4209if(!%href_params) {4210$feed_class.=' generic';4211}4212$href_params{'-title'} ||='log';42134214foreachmy$format(qw(RSS Atom)) {4215$href_params{'action'} =lc($format);4216print$cgi->a({-href => href(%href_params),4217-title =>"$href_params{'-title'}$formatfeed",4218-class=>$feed_class},$format)."\n";4219}42204221}else{4222print$cgi->a({-href => href(project=>undef, action=>"opml",4223 project_filter =>$project_filter),4224-class=>$feed_class},"OPML") ." ";4225print$cgi->a({-href => href(project=>undef, action=>"project_index",4226 project_filter =>$project_filter),4227-class=>$feed_class},"TXT") ."\n";4228}4229print"</div>\n";# class="page_footer"42304231if(defined$t0&& gitweb_check_feature('timed')) {4232print"<div id=\"generating_info\">\n";4233print'This page took '.4234'<span id="generating_time" class="time_span">'.4235 tv_interval($t0, [ gettimeofday() ]).4236' seconds </span>'.4237' and '.4238'<span id="generating_cmd">'.4239$number_of_git_cmds.4240'</span> git commands '.4241" to generate.\n";4242print"</div>\n";# class="page_footer"4243}42444245if(defined$site_footer&& -f $site_footer) {4246 insert_file($site_footer);4247}42484249print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;4250if(defined$action&&4251$actioneq'blame_incremental') {4252print qq!<script type="text/javascript">\n!.4253 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.4254 qq!"!. href() .qq!");\n!.4255 qq!</script>\n!;4256}else{4257my($jstimezone,$tz_cookie,$datetime_class) =4258 gitweb_get_feature('javascript-timezone');42594260print qq!<script type="text/javascript">\n!.4261 qq!window.onload = function () {\n!;4262if(gitweb_check_feature('javascript-actions')) {4263print qq! fixLinks();\n!;4264}4265if($jstimezone&&$tz_cookie&&$datetime_class) {4266print qq! var tz_cookie = { name:'$tz_cookie', expires:14, path:'/'};\n!.# in days4267 qq! onloadTZSetup('$jstimezone', tz_cookie,'$datetime_class');\n!;4268}4269print qq!};\n!.4270 qq!</script>\n!;4271}42724273print"</body>\n".4274"</html>";4275}42764277# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])4278# Example: die_error(404, 'Hash not found')4279# By convention, use the following status codes (as defined in RFC 2616):4280# 400: Invalid or missing CGI parameters, or4281# requested object exists but has wrong type.4282# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on4283# this server or project.4284# 404: Requested object/revision/project doesn't exist.4285# 500: The server isn't configured properly, or4286# an internal error occurred (e.g. failed assertions caused by bugs), or4287# an unknown error occurred (e.g. the git binary died unexpectedly).4288# 503: The server is currently unavailable (because it is overloaded,4289# or down for maintenance). Generally, this is a temporary state.4290sub die_error {4291my$status=shift||500;4292my$error= esc_html(shift) ||"Internal Server Error";4293my$extra=shift;4294my%opts=@_;42954296my%http_responses= (4297400=>'400 Bad Request',4298403=>'403 Forbidden',4299404=>'404 Not Found',4300500=>'500 Internal Server Error',4301503=>'503 Service Unavailable',4302);4303 git_header_html($http_responses{$status},undef,%opts);4304print<<EOF;4305<div class="page_body">4306<br /><br />4307$status-$error4308<br />4309EOF4310if(defined$extra) {4311print"<hr />\n".4312"$extra\n";4313}4314print"</div>\n";43154316 git_footer_html();4317goto DONE_GITWEB4318unless($opts{'-error_handler'});4319}43204321## ----------------------------------------------------------------------4322## functions printing or outputting HTML: navigation43234324sub git_print_page_nav {4325my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;4326$extra=''if!defined$extra;# pager or formats43274328my@navs=qw(summary shortlog log commit commitdiff tree);4329if($suppress) {4330@navs=grep{$_ne$suppress}@navs;4331}43324333my%arg=map{$_=> {action=>$_} }@navs;4334if(defined$head) {4335for(qw(commit commitdiff)) {4336$arg{$_}{'hash'} =$head;4337}4338if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {4339for(qw(shortlog log)) {4340$arg{$_}{'hash'} =$head;4341}4342}4343}43444345$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;4346$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;43474348my@actions= gitweb_get_feature('actions');4349my%repl= (4350'%'=>'%',4351'n'=>$project,# project name4352'f'=>$git_dir,# project path within filesystem4353'h'=>$treehead||'',# current hash ('h' parameter)4354'b'=>$treebase||'',# hash base ('hb' parameter)4355);4356while(@actions) {4357my($label,$link,$pos) =splice(@actions,0,3);4358# insert4359@navs=map{$_eq$pos? ($_,$label) :$_}@navs;4360# munch munch4361$link=~s/%([%nfhb])/$repl{$1}/g;4362$arg{$label}{'_href'} =$link;4363}43644365print"<div class=\"page_nav\">\n".4366(join" | ",4367map{$_eq$current?4368$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4369}@navs);4370print"<br/>\n$extra<br/>\n".4371"</div>\n";4372}43734374# returns a submenu for the navigation of the refs views (tags, heads,4375# remotes) with the current view disabled and the remotes view only4376# available if the feature is enabled4377sub format_ref_views {4378my($current) =@_;4379my@ref_views=qw{tags heads};4380push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4381returnjoin" | ",map{4382$_eq$current?$_:4383$cgi->a({-href => href(action=>$_)},$_)4384}@ref_views4385}43864387sub format_paging_nav {4388my($action,$page,$has_next_link) =@_;4389my$paging_nav;439043914392if($page>0) {4393$paging_nav.=4394$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4395" ⋅ ".4396$cgi->a({-href => href(-replay=>1, page=>$page-1),4397-accesskey =>"p", -title =>"Alt-p"},"prev");4398}else{4399$paging_nav.="first ⋅ prev";4400}44014402if($has_next_link) {4403$paging_nav.=" ⋅ ".4404$cgi->a({-href => href(-replay=>1, page=>$page+1),4405-accesskey =>"n", -title =>"Alt-n"},"next");4406}else{4407$paging_nav.=" ⋅ next";4408}44094410return$paging_nav;4411}44124413## ......................................................................4414## functions printing or outputting HTML: div44154416sub git_print_header_div {4417my($action,$title,$hash,$hash_base) =@_;4418my%args= ();44194420$args{'action'} =$action;4421$args{'hash'} =$hashif$hash;4422$args{'hash_base'} =$hash_baseif$hash_base;44234424print"<div class=\"header\">\n".4425$cgi->a({-href => href(%args), -class=>"title"},4426$title?$title:$action) .4427"\n</div>\n";4428}44294430sub format_repo_url {4431my($name,$url) =@_;4432return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4433}44344435# Group output by placing it in a DIV element and adding a header.4436# Options for start_div() can be provided by passing a hash reference as the4437# first parameter to the function.4438# Options to git_print_header_div() can be provided by passing an array4439# reference. This must follow the options to start_div if they are present.4440# The content can be a scalar, which is output as-is, a scalar reference, which4441# is output after html escaping, an IO handle passed either as *handle or4442# *handle{IO}, or a function reference. In the latter case all following4443# parameters will be taken as argument to the content function call.4444sub git_print_section {4445my($div_args,$header_args,$content);4446my$arg=shift;4447if(ref($arg)eq'HASH') {4448$div_args=$arg;4449$arg=shift;4450}4451if(ref($arg)eq'ARRAY') {4452$header_args=$arg;4453$arg=shift;4454}4455$content=$arg;44564457print$cgi->start_div($div_args);4458 git_print_header_div(@$header_args);44594460if(ref($content)eq'CODE') {4461$content->(@_);4462}elsif(ref($content)eq'SCALAR') {4463print esc_html($$content);4464}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4465print<$content>;4466}elsif(!ref($content) &&defined($content)) {4467print$content;4468}44694470print$cgi->end_div;4471}44724473sub format_timestamp_html {4474my$date=shift;4475my$strtime=$date->{'rfc2822'};44764477my(undef,undef,$datetime_class) =4478 gitweb_get_feature('javascript-timezone');4479if($datetime_class) {4480$strtime= qq!<span class="$datetime_class">$strtime</span>!;4481}44824483my$localtime_format='(%02d:%02d%s)';4484if($date->{'hour_local'} <6) {4485$localtime_format='(<span class="atnight">%02d:%02d</span>%s)';4486}4487$strtime.=' '.4488sprintf($localtime_format,4489$date->{'hour_local'},$date->{'minute_local'},$date->{'tz_local'});44904491return$strtime;4492}44934494# Outputs the author name and date in long form4495sub git_print_authorship {4496my$co=shift;4497my%opts=@_;4498my$tag=$opts{-tag} ||'div';4499my$author=$co->{'author_name'};45004501my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4502print"<$tagclass=\"author_date\">".4503 format_search_author($author,"author", esc_html($author)) .4504" [".format_timestamp_html(\%ad)."]".4505 git_get_avatar($co->{'author_email'}, -pad_before =>1) .4506"</$tag>\n";4507}45084509# Outputs table rows containing the full author or committer information,4510# in the format expected for 'commit' view (& similar).4511# Parameters are a commit hash reference, followed by the list of people4512# to output information for. If the list is empty it defaults to both4513# author and committer.4514sub git_print_authorship_rows {4515my$co=shift;4516# too bad we can't use @people = @_ || ('author', 'committer')4517my@people=@_;4518@people= ('author','committer')unless@people;4519foreachmy$who(@people) {4520my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4521print"<tr><td>$who</td><td>".4522 format_search_author($co->{"${who}_name"},$who,4523 esc_html($co->{"${who}_name"})) ." ".4524 format_search_author($co->{"${who}_email"},$who,4525 esc_html("<".$co->{"${who}_email"} .">")) .4526"</td><td rowspan=\"2\">".4527 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4528"</td></tr>\n".4529"<tr>".4530"<td></td><td>".4531 format_timestamp_html(\%wd) .4532"</td>".4533"</tr>\n";4534}4535}45364537sub git_print_page_path {4538my$name=shift;4539my$type=shift;4540my$hb=shift;454145424543print"<div class=\"page_path\">";4544print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4545-title =>'tree root'}, to_utf8("[$project]"));4546print" / ";4547if(defined$name) {4548my@dirname=split'/',$name;4549my$basename=pop@dirname;4550my$fullname='';45514552foreachmy$dir(@dirname) {4553$fullname.= ($fullname?'/':'') .$dir;4554print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4555 hash_base=>$hb),4556-title =>$fullname}, esc_path($dir));4557print" / ";4558}4559if(defined$type&&$typeeq'blob') {4560print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4561 hash_base=>$hb),4562-title =>$name}, esc_path($basename));4563}elsif(defined$type&&$typeeq'tree') {4564print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4565 hash_base=>$hb),4566-title =>$name}, esc_path($basename));4567print" / ";4568}else{4569print esc_path($basename);4570}4571}4572print"<br/></div>\n";4573}45744575sub git_print_log {4576my$log=shift;4577my%opts=@_;45784579if($opts{'-remove_title'}) {4580# remove title, i.e. first line of log4581shift@$log;4582}4583# remove leading empty lines4584while(defined$log->[0] &&$log->[0]eq"") {4585shift@$log;4586}45874588# print log4589my$skip_blank_line=0;4590foreachmy$line(@$log) {4591if($line=~m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {4592if(!$opts{'-remove_signoff'}) {4593print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4594$skip_blank_line=1;4595}4596next;4597}45984599if($line=~ m,\s*([a-z]*link): (https?://\S+),i) {4600if(!$opts{'-remove_signoff'}) {4601print"<span class=\"signoff\">". esc_html($1) .": ".4602"<a href=\"". esc_html($2) ."\">". esc_html($2) ."</a>".4603"</span><br/>\n";4604$skip_blank_line=1;4605}4606next;4607}46084609# print only one empty line4610# do not print empty line after signoff4611if($lineeq"") {4612next if($skip_blank_line);4613$skip_blank_line=1;4614}else{4615$skip_blank_line=0;4616}46174618print format_log_line_html($line) ."<br/>\n";4619}46204621if($opts{'-final_empty_line'}) {4622# end with single empty line4623print"<br/>\n"unless$skip_blank_line;4624}4625}46264627# return link target (what link points to)4628sub git_get_link_target {4629my$hash=shift;4630my$link_target;46314632# read link4633open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4634orreturn;4635{4636local$/=undef;4637$link_target= <$fd>;4638}4639close$fd4640orreturn;46414642return$link_target;4643}46444645# given link target, and the directory (basedir) the link is in,4646# return target of link relative to top directory (top tree);4647# return undef if it is not possible (including absolute links).4648sub normalize_link_target {4649my($link_target,$basedir) =@_;46504651# absolute symlinks (beginning with '/') cannot be normalized4652return if(substr($link_target,0,1)eq'/');46534654# normalize link target to path from top (root) tree (dir)4655my$path;4656if($basedir) {4657$path=$basedir.'/'.$link_target;4658}else{4659# we are in top (root) tree (dir)4660$path=$link_target;4661}46624663# remove //, /./, and /../4664my@path_parts;4665foreachmy$part(split('/',$path)) {4666# discard '.' and ''4667next if(!$part||$parteq'.');4668# handle '..'4669if($parteq'..') {4670if(@path_parts) {4671pop@path_parts;4672}else{4673# link leads outside repository (outside top dir)4674return;4675}4676}else{4677push@path_parts,$part;4678}4679}4680$path=join('/',@path_parts);46814682return$path;4683}46844685# print tree entry (row of git_tree), but without encompassing <tr> element4686sub git_print_tree_entry {4687my($t,$basedir,$hash_base,$have_blame) =@_;46884689my%base_key= ();4690$base_key{'hash_base'} =$hash_baseifdefined$hash_base;46914692# The format of a table row is: mode list link. Where mode is4693# the mode of the entry, list is the name of the entry, an href,4694# and link is the action links of the entry.46954696print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4697if(exists$t->{'size'}) {4698print"<td class=\"size\">$t->{'size'}</td>\n";4699}4700if($t->{'type'}eq"blob") {4701print"<td class=\"list\">".4702$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4703 file_name=>"$basedir$t->{'name'}",%base_key),4704-class=>"list"}, esc_path($t->{'name'}));4705if(S_ISLNK(oct$t->{'mode'})) {4706my$link_target= git_get_link_target($t->{'hash'});4707if($link_target) {4708my$norm_target= normalize_link_target($link_target,$basedir);4709if(defined$norm_target) {4710print" -> ".4711$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4712 file_name=>$norm_target),4713-title =>$norm_target}, esc_path($link_target));4714}else{4715print" -> ". esc_path($link_target);4716}4717}4718}4719print"</td>\n";4720print"<td class=\"link\">";4721print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4722 file_name=>"$basedir$t->{'name'}",%base_key)},4723"blob");4724if($have_blame) {4725print" | ".4726$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4727 file_name=>"$basedir$t->{'name'}",%base_key)},4728"blame");4729}4730if(defined$hash_base) {4731print" | ".4732$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4733 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4734"history");4735}4736print" | ".4737$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4738 file_name=>"$basedir$t->{'name'}")},4739"raw");4740print"</td>\n";47414742}elsif($t->{'type'}eq"tree") {4743print"<td class=\"list\">";4744print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4745 file_name=>"$basedir$t->{'name'}",4746%base_key)},4747 esc_path($t->{'name'}));4748print"</td>\n";4749print"<td class=\"link\">";4750print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4751 file_name=>"$basedir$t->{'name'}",4752%base_key)},4753"tree");4754if(defined$hash_base) {4755print" | ".4756$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4757 file_name=>"$basedir$t->{'name'}")},4758"history");4759}4760print"</td>\n";4761}else{4762# unknown object: we can only present history for it4763# (this includes 'commit' object, i.e. submodule support)4764print"<td class=\"list\">".4765 esc_path($t->{'name'}) .4766"</td>\n";4767print"<td class=\"link\">";4768if(defined$hash_base) {4769print$cgi->a({-href => href(action=>"history",4770 hash_base=>$hash_base,4771 file_name=>"$basedir$t->{'name'}")},4772"history");4773}4774print"</td>\n";4775}4776}47774778## ......................................................................4779## functions printing large fragments of HTML47804781# get pre-image filenames for merge (combined) diff4782sub fill_from_file_info {4783my($diff,@parents) =@_;47844785$diff->{'from_file'} = [ ];4786$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4787for(my$i=0;$i<$diff->{'nparents'};$i++) {4788if($diff->{'status'}[$i]eq'R'||4789$diff->{'status'}[$i]eq'C') {4790$diff->{'from_file'}[$i] =4791 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4792}4793}47944795return$diff;4796}47974798# is current raw difftree line of file deletion4799sub is_deleted {4800my$diffinfo=shift;48014802return$diffinfo->{'to_id'}eq('0' x 40);4803}48044805# does patch correspond to [previous] difftree raw line4806# $diffinfo - hashref of parsed raw diff format4807# $patchinfo - hashref of parsed patch diff format4808# (the same keys as in $diffinfo)4809sub is_patch_split {4810my($diffinfo,$patchinfo) =@_;48114812returndefined$diffinfo&&defined$patchinfo4813&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4814}481548164817sub git_difftree_body {4818my($difftree,$hash,@parents) =@_;4819my($parent) =$parents[0];4820my$have_blame= gitweb_check_feature('blame');4821print"<div class=\"list_head\">\n";4822if($#{$difftree} >10) {4823print(($#{$difftree} +1) ." files changed:\n");4824}4825print"</div>\n";48264827print"<table class=\"".4828(@parents>1?"combined ":"") .4829"diff_tree\">\n";48304831# header only for combined diff in 'commitdiff' view4832my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4833if($has_header) {4834# table header4835print"<thead><tr>\n".4836"<th></th><th></th>\n";# filename, patchN link4837for(my$i=0;$i<@parents;$i++) {4838my$par=$parents[$i];4839print"<th>".4840$cgi->a({-href => href(action=>"commitdiff",4841 hash=>$hash, hash_parent=>$par),4842-title =>'commitdiff to parent number '.4843($i+1) .': '.substr($par,0,7)},4844$i+1) .4845" </th>\n";4846}4847print"</tr></thead>\n<tbody>\n";4848}48494850my$alternate=1;4851my$patchno=0;4852foreachmy$line(@{$difftree}) {4853my$diff= parsed_difftree_line($line);48544855if($alternate) {4856print"<tr class=\"dark\">\n";4857}else{4858print"<tr class=\"light\">\n";4859}4860$alternate^=1;48614862if(exists$diff->{'nparents'}) {# combined diff48634864 fill_from_file_info($diff,@parents)4865unlessexists$diff->{'from_file'};48664867if(!is_deleted($diff)) {4868# file exists in the result (child) commit4869print"<td>".4870$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4871 file_name=>$diff->{'to_file'},4872 hash_base=>$hash),4873-class=>"list"}, esc_path($diff->{'to_file'})) .4874"</td>\n";4875}else{4876print"<td>".4877 esc_path($diff->{'to_file'}) .4878"</td>\n";4879}48804881if($actioneq'commitdiff') {4882# link to patch4883$patchno++;4884print"<td class=\"link\">".4885$cgi->a({-href => href(-anchor=>"patch$patchno")},4886"patch") .4887" | ".4888"</td>\n";4889}48904891my$has_history=0;4892my$not_deleted=0;4893for(my$i=0;$i<$diff->{'nparents'};$i++) {4894my$hash_parent=$parents[$i];4895my$from_hash=$diff->{'from_id'}[$i];4896my$from_path=$diff->{'from_file'}[$i];4897my$status=$diff->{'status'}[$i];48984899$has_history||= ($statusne'A');4900$not_deleted||= ($statusne'D');49014902if($statuseq'A') {4903print"<td class=\"link\"align=\"right\"> | </td>\n";4904}elsif($statuseq'D') {4905print"<td class=\"link\">".4906$cgi->a({-href => href(action=>"blob",4907 hash_base=>$hash,4908 hash=>$from_hash,4909 file_name=>$from_path)},4910"blob". ($i+1)) .4911" | </td>\n";4912}else{4913if($diff->{'to_id'}eq$from_hash) {4914print"<td class=\"link nochange\">";4915}else{4916print"<td class=\"link\">";4917}4918print$cgi->a({-href => href(action=>"blobdiff",4919 hash=>$diff->{'to_id'},4920 hash_parent=>$from_hash,4921 hash_base=>$hash,4922 hash_parent_base=>$hash_parent,4923 file_name=>$diff->{'to_file'},4924 file_parent=>$from_path)},4925"diff". ($i+1)) .4926" | </td>\n";4927}4928}49294930print"<td class=\"link\">";4931if($not_deleted) {4932print$cgi->a({-href => href(action=>"blob",4933 hash=>$diff->{'to_id'},4934 file_name=>$diff->{'to_file'},4935 hash_base=>$hash)},4936"blob");4937print" | "if($has_history);4938}4939if($has_history) {4940print$cgi->a({-href => href(action=>"history",4941 file_name=>$diff->{'to_file'},4942 hash_base=>$hash)},4943"history");4944}4945print"</td>\n";49464947print"</tr>\n";4948next;# instead of 'else' clause, to avoid extra indent4949}4950# else ordinary diff49514952my($to_mode_oct,$to_mode_str,$to_file_type);4953my($from_mode_oct,$from_mode_str,$from_file_type);4954if($diff->{'to_mode'}ne('0' x 6)) {4955$to_mode_oct=oct$diff->{'to_mode'};4956if(S_ISREG($to_mode_oct)) {# only for regular file4957$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4958}4959$to_file_type= file_type($diff->{'to_mode'});4960}4961if($diff->{'from_mode'}ne('0' x 6)) {4962$from_mode_oct=oct$diff->{'from_mode'};4963if(S_ISREG($from_mode_oct)) {# only for regular file4964$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4965}4966$from_file_type= file_type($diff->{'from_mode'});4967}49684969if($diff->{'status'}eq"A") {# created4970my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4971$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4972$mode_chng.="]</span>";4973print"<td>";4974print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4975 hash_base=>$hash, file_name=>$diff->{'file'}),4976-class=>"list"}, esc_path($diff->{'file'}));4977print"</td>\n";4978print"<td>$mode_chng</td>\n";4979print"<td class=\"link\">";4980if($actioneq'commitdiff') {4981# link to patch4982$patchno++;4983print$cgi->a({-href => href(-anchor=>"patch$patchno")},4984"patch") .4985" | ";4986}4987print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4988 hash_base=>$hash, file_name=>$diff->{'file'})},4989"blob");4990print"</td>\n";49914992}elsif($diff->{'status'}eq"D") {# deleted4993my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4994print"<td>";4995print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4996 hash_base=>$parent, file_name=>$diff->{'file'}),4997-class=>"list"}, esc_path($diff->{'file'}));4998print"</td>\n";4999print"<td>$mode_chng</td>\n";5000print"<td class=\"link\">";5001if($actioneq'commitdiff') {5002# link to patch5003$patchno++;5004print$cgi->a({-href => href(-anchor=>"patch$patchno")},5005"patch") .5006" | ";5007}5008print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},5009 hash_base=>$parent, file_name=>$diff->{'file'})},5010"blob") ." | ";5011if($have_blame) {5012print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,5013 file_name=>$diff->{'file'})},5014"blame") ." | ";5015}5016print$cgi->a({-href => href(action=>"history", hash_base=>$parent,5017 file_name=>$diff->{'file'})},5018"history");5019print"</td>\n";50205021}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed5022my$mode_chnge="";5023if($diff->{'from_mode'} !=$diff->{'to_mode'}) {5024$mode_chnge="<span class=\"file_status mode_chnge\">[changed";5025if($from_file_typene$to_file_type) {5026$mode_chnge.=" from$from_file_typeto$to_file_type";5027}5028if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {5029if($from_mode_str&&$to_mode_str) {5030$mode_chnge.=" mode:$from_mode_str->$to_mode_str";5031}elsif($to_mode_str) {5032$mode_chnge.=" mode:$to_mode_str";5033}5034}5035$mode_chnge.="]</span>\n";5036}5037print"<td>";5038print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},5039 hash_base=>$hash, file_name=>$diff->{'file'}),5040-class=>"list"}, esc_path($diff->{'file'}));5041print"</td>\n";5042print"<td>$mode_chnge</td>\n";5043print"<td class=\"link\">";5044if($actioneq'commitdiff') {5045# link to patch5046$patchno++;5047print$cgi->a({-href => href(-anchor=>"patch$patchno")},5048"patch") .5049" | ";5050}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {5051# "commit" view and modified file (not onlu mode changed)5052print$cgi->a({-href => href(action=>"blobdiff",5053 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},5054 hash_base=>$hash, hash_parent_base=>$parent,5055 file_name=>$diff->{'file'})},5056"diff") .5057" | ";5058}5059print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},5060 hash_base=>$hash, file_name=>$diff->{'file'})},5061"blob") ." | ";5062if($have_blame) {5063print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,5064 file_name=>$diff->{'file'})},5065"blame") ." | ";5066}5067print$cgi->a({-href => href(action=>"history", hash_base=>$hash,5068 file_name=>$diff->{'file'})},5069"history");5070print"</td>\n";50715072}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied5073my%status_name= ('R'=>'moved','C'=>'copied');5074my$nstatus=$status_name{$diff->{'status'}};5075my$mode_chng="";5076if($diff->{'from_mode'} !=$diff->{'to_mode'}) {5077# mode also for directories, so we cannot use $to_mode_str5078$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);5079}5080print"<td>".5081$cgi->a({-href => href(action=>"blob", hash_base=>$hash,5082 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),5083-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".5084"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".5085$cgi->a({-href => href(action=>"blob", hash_base=>$parent,5086 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),5087-class=>"list"}, esc_path($diff->{'from_file'})) .5088" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".5089"<td class=\"link\">";5090if($actioneq'commitdiff') {5091# link to patch5092$patchno++;5093print$cgi->a({-href => href(-anchor=>"patch$patchno")},5094"patch") .5095" | ";5096}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {5097# "commit" view and modified file (not only pure rename or copy)5098print$cgi->a({-href => href(action=>"blobdiff",5099 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},5100 hash_base=>$hash, hash_parent_base=>$parent,5101 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},5102"diff") .5103" | ";5104}5105print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},5106 hash_base=>$parent, file_name=>$diff->{'to_file'})},5107"blob") ." | ";5108if($have_blame) {5109print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,5110 file_name=>$diff->{'to_file'})},5111"blame") ." | ";5112}5113print$cgi->a({-href => href(action=>"history", hash_base=>$hash,5114 file_name=>$diff->{'to_file'})},5115"history");5116print"</td>\n";51175118}# we should not encounter Unmerged (U) or Unknown (X) status5119print"</tr>\n";5120}5121print"</tbody>"if$has_header;5122print"</table>\n";5123}51245125# Print context lines and then rem/add lines in a side-by-side manner.5126sub print_sidebyside_diff_lines {5127my($ctx,$rem,$add) =@_;51285129# print context block before add/rem block5130if(@$ctx) {5131print join'',5132'<div class="chunk_block ctx">',5133'<div class="old">',5134@$ctx,5135'</div>',5136'<div class="new">',5137@$ctx,5138'</div>',5139'</div>';5140}51415142if(!@$add) {5143# pure removal5144print join'',5145'<div class="chunk_block rem">',5146'<div class="old">',5147@$rem,5148'</div>',5149'</div>';5150}elsif(!@$rem) {5151# pure addition5152print join'',5153'<div class="chunk_block add">',5154'<div class="new">',5155@$add,5156'</div>',5157'</div>';5158}else{5159print join'',5160'<div class="chunk_block chg">',5161'<div class="old">',5162@$rem,5163'</div>',5164'<div class="new">',5165@$add,5166'</div>',5167'</div>';5168}5169}51705171# Print context lines and then rem/add lines in inline manner.5172sub print_inline_diff_lines {5173my($ctx,$rem,$add) =@_;51745175print@$ctx,@$rem,@$add;5176}51775178# Format removed and added line, mark changed part and HTML-format them.5179# Implementation is based on contrib/diff-highlight5180sub format_rem_add_lines_pair {5181my($rem,$add,$num_parents) =@_;51825183# We need to untabify lines before split()'ing them;5184# otherwise offsets would be invalid.5185chomp$rem;5186chomp$add;5187$rem= untabify($rem);5188$add= untabify($add);51895190my@rem=split(//,$rem);5191my@add=split(//,$add);5192my($esc_rem,$esc_add);5193# Ignore leading +/- characters for each parent.5194my($prefix_len,$suffix_len) = ($num_parents,0);5195my($prefix_has_nonspace,$suffix_has_nonspace);51965197my$shorter= (@rem<@add) ?@rem:@add;5198while($prefix_len<$shorter) {5199last if($rem[$prefix_len]ne$add[$prefix_len]);52005201$prefix_has_nonspace=1if($rem[$prefix_len] !~/\s/);5202$prefix_len++;5203}52045205while($prefix_len+$suffix_len<$shorter) {5206last if($rem[-1-$suffix_len]ne$add[-1-$suffix_len]);52075208$suffix_has_nonspace=1if($rem[-1-$suffix_len] !~/\s/);5209$suffix_len++;5210}52115212# Mark lines that are different from each other, but have some common5213# part that isn't whitespace. If lines are completely different, don't5214# mark them because that would make output unreadable, especially if5215# diff consists of multiple lines.5216if($prefix_has_nonspace||$suffix_has_nonspace) {5217$esc_rem= esc_html_hl_regions($rem,'marked',5218[$prefix_len,@rem-$suffix_len], -nbsp=>1);5219$esc_add= esc_html_hl_regions($add,'marked',5220[$prefix_len,@add-$suffix_len], -nbsp=>1);5221}else{5222$esc_rem= esc_html($rem, -nbsp=>1);5223$esc_add= esc_html($add, -nbsp=>1);5224}52255226return format_diff_line(\$esc_rem,'rem'),5227 format_diff_line(\$esc_add,'add');5228}52295230# HTML-format diff context, removed and added lines.5231sub format_ctx_rem_add_lines {5232my($ctx,$rem,$add,$num_parents) =@_;5233my(@new_ctx,@new_rem,@new_add);5234my$can_highlight=0;5235my$is_combined= ($num_parents>1);52365237# Highlight if every removed line has a corresponding added line.5238if(@$add>0&&@$add==@$rem) {5239$can_highlight=1;52405241# Highlight lines in combined diff only if the chunk contains5242# diff between the same version, e.g.5243#5244# - a5245# - b5246# + c5247# + d5248#5249# Otherwise the highlightling would be confusing.5250if($is_combined) {5251for(my$i=0;$i<@$add;$i++) {5252my$prefix_rem=substr($rem->[$i],0,$num_parents);5253my$prefix_add=substr($add->[$i],0,$num_parents);52545255$prefix_rem=~s/-/+/g;52565257if($prefix_remne$prefix_add) {5258$can_highlight=0;5259last;5260}5261}5262}5263}52645265if($can_highlight) {5266for(my$i=0;$i<@$add;$i++) {5267my($line_rem,$line_add) = format_rem_add_lines_pair(5268$rem->[$i],$add->[$i],$num_parents);5269push@new_rem,$line_rem;5270push@new_add,$line_add;5271}5272}else{5273@new_rem=map{ format_diff_line($_,'rem') }@$rem;5274@new_add=map{ format_diff_line($_,'add') }@$add;5275}52765277@new_ctx=map{ format_diff_line($_,'ctx') }@$ctx;52785279return(\@new_ctx, \@new_rem, \@new_add);5280}52815282# Print context lines and then rem/add lines.5283sub print_diff_lines {5284my($ctx,$rem,$add,$diff_style,$num_parents) =@_;5285my$is_combined=$num_parents>1;52865287($ctx,$rem,$add) = format_ctx_rem_add_lines($ctx,$rem,$add,5288$num_parents);52895290if($diff_styleeq'sidebyside'&& !$is_combined) {5291 print_sidebyside_diff_lines($ctx,$rem,$add);5292}else{5293# default 'inline' style and unknown styles5294 print_inline_diff_lines($ctx,$rem,$add);5295}5296}52975298sub print_diff_chunk {5299my($diff_style,$num_parents,$from,$to,@chunk) =@_;5300my(@ctx,@rem,@add);53015302# The class of the previous line.5303my$prev_class='';53045305return unless@chunk;53065307# incomplete last line might be among removed or added lines,5308# or both, or among context lines: find which5309for(my$i=1;$i<@chunk;$i++) {5310if($chunk[$i][0]eq'incomplete') {5311$chunk[$i][0] =$chunk[$i-1][0];5312}5313}53145315# guardian5316push@chunk, ["",""];53175318foreachmy$line_info(@chunk) {5319my($class,$line) =@$line_info;53205321# print chunk headers5322if($class&&$classeq'chunk_header') {5323print format_diff_line($line,$class,$from,$to);5324next;5325}53265327## print from accumulator when have some add/rem lines or end5328# of chunk (flush context lines), or when have add and rem5329# lines and new block is reached (otherwise add/rem lines could5330# be reordered)5331if(!$class|| ((@rem||@add) &&$classeq'ctx') ||5332(@rem&&@add&&$classne$prev_class)) {5333 print_diff_lines(\@ctx, \@rem, \@add,5334$diff_style,$num_parents);5335@ctx=@rem=@add= ();5336}53375338## adding lines to accumulator5339# guardian value5340last unless$line;5341# rem, add or change5342if($classeq'rem') {5343push@rem,$line;5344}elsif($classeq'add') {5345push@add,$line;5346}5347# context line5348if($classeq'ctx') {5349push@ctx,$line;5350}53515352$prev_class=$class;5353}5354}53555356sub git_patchset_body {5357my($fd,$diff_style,$difftree,$hash,@hash_parents) =@_;5358my($hash_parent) =$hash_parents[0];53595360my$is_combined= (@hash_parents>1);5361my$patch_idx=0;5362my$patch_number=0;5363my$patch_line;5364my$diffinfo;5365my$to_name;5366my(%from,%to);5367my@chunk;# for side-by-side diff53685369print"<div class=\"patchset\">\n";53705371# skip to first patch5372while($patch_line= <$fd>) {5373chomp$patch_line;53745375last if($patch_line=~m/^diff /);5376}53775378 PATCH:5379while($patch_line) {53805381# parse "git diff" header line5382if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {5383# $1 is from_name, which we do not use5384$to_name= unquote($2);5385$to_name=~s!^b/!!;5386}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {5387# $1 is 'cc' or 'combined', which we do not use5388$to_name= unquote($2);5389}else{5390$to_name=undef;5391}53925393# check if current patch belong to current raw line5394# and parse raw git-diff line if needed5395if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {5396# this is continuation of a split patch5397print"<div class=\"patch cont\">\n";5398}else{5399# advance raw git-diff output if needed5400$patch_idx++ifdefined$diffinfo;54015402# read and prepare patch information5403$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);54045405# compact combined diff output can have some patches skipped5406# find which patch (using pathname of result) we are at now;5407if($is_combined) {5408while($to_namene$diffinfo->{'to_file'}) {5409print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5410 format_diff_cc_simplified($diffinfo,@hash_parents) .5411"</div>\n";# class="patch"54125413$patch_idx++;5414$patch_number++;54155416last if$patch_idx>$#$difftree;5417$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);5418}5419}54205421# modifies %from, %to hashes5422 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);54235424# this is first patch for raw difftree line with $patch_idx index5425# we index @$difftree array from 0, but number patches from 15426print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";5427}54285429# git diff header5430#assert($patch_line =~ m/^diff /) if DEBUG;5431#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed5432$patch_number++;5433# print "git diff" header5434print format_git_diff_header_line($patch_line,$diffinfo,5435 \%from, \%to);54365437# print extended diff header5438print"<div class=\"diff extended_header\">\n";5439 EXTENDED_HEADER:5440while($patch_line= <$fd>) {5441chomp$patch_line;54425443last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);54445445print format_extended_diff_header_line($patch_line,$diffinfo,5446 \%from, \%to);5447}5448print"</div>\n";# class="diff extended_header"54495450# from-file/to-file diff header5451if(!$patch_line) {5452print"</div>\n";# class="patch"5453last PATCH;5454}5455next PATCH if($patch_line=~m/^diff /);5456#assert($patch_line =~ m/^---/) if DEBUG;54575458my$last_patch_line=$patch_line;5459$patch_line= <$fd>;5460chomp$patch_line;5461#assert($patch_line =~ m/^\+\+\+/) if DEBUG;54625463print format_diff_from_to_header($last_patch_line,$patch_line,5464$diffinfo, \%from, \%to,5465@hash_parents);54665467# the patch itself5468 LINE:5469while($patch_line= <$fd>) {5470chomp$patch_line;54715472next PATCH if($patch_line=~m/^diff /);54735474my$class= diff_line_class($patch_line, \%from, \%to);54755476if($classeq'chunk_header') {5477 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5478@chunk= ();5479}54805481push@chunk, [$class,$patch_line];5482}54835484}continue{5485if(@chunk) {5486 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5487@chunk= ();5488}5489print"</div>\n";# class="patch"5490}54915492# for compact combined (--cc) format, with chunk and patch simplification5493# the patchset might be empty, but there might be unprocessed raw lines5494for(++$patch_idxif$patch_number>0;5495$patch_idx<@$difftree;5496++$patch_idx) {5497# read and prepare patch information5498$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);54995500# generate anchor for "patch" links in difftree / whatchanged part5501print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5502 format_diff_cc_simplified($diffinfo,@hash_parents) .5503"</div>\n";# class="patch"55045505$patch_number++;5506}55075508if($patch_number==0) {5509if(@hash_parents>1) {5510print"<div class=\"diff nodifferences\">Trivial merge</div>\n";5511}else{5512print"<div class=\"diff nodifferences\">No differences found</div>\n";5513}5514}55155516print"</div>\n";# class="patchset"5517}55185519# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55205521sub git_project_search_form {5522my($searchtext,$search_use_regexp) =@_;55235524my$limit='';5525if($project_filter) {5526$limit=" in '$project_filter/'";5527}55285529print"<div class=\"projsearch\">\n";5530print$cgi->start_form(-method=>'get', -action =>$my_uri) .5531$cgi->hidden(-name =>'a', -value =>'project_list') ."\n";5532print$cgi->hidden(-name =>'pf', -value =>$project_filter)."\n"5533if(defined$project_filter);5534print$cgi->textfield(-name =>'s', -value =>$searchtext,5535-title =>"Search project by name and description$limit",5536-size =>60) ."\n".5537"<span title=\"Extended regular expression\">".5538$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',5539-checked =>$search_use_regexp) .5540"</span>\n".5541$cgi->submit(-name =>'btnS', -value =>'Search') .5542$cgi->end_form() ."\n".5543$cgi->a({-href => href(project =>undef, searchtext =>undef,5544 project_filter =>$project_filter)},5545 esc_html("List all projects$limit")) ."<br />\n";5546print"</div>\n";5547}55485549# entry for given @keys needs filling if at least one of keys in list5550# is not present in %$project_info5551sub project_info_needs_filling {5552my($project_info,@keys) =@_;55535554# return List::MoreUtils::any { !exists $project_info->{$_} } @keys;5555foreachmy$key(@keys) {5556if(!exists$project_info->{$key}) {5557return1;5558}5559}5560return;5561}55625563# fills project list info (age, description, owner, category, forks, etc.)5564# for each project in the list, removing invalid projects from5565# returned list, or fill only specified info.5566#5567# Invalid projects are removed from the returned list if and only if you5568# ask 'age' or 'age_string' to be filled, because they are the only fields5569# that run unconditionally git command that requires repository, and5570# therefore do always check if project repository is invalid.5571#5572# USAGE:5573# * fill_project_list_info(\@project_list, 'descr_long', 'ctags')5574# ensures that 'descr_long' and 'ctags' fields are filled5575# * @project_list = fill_project_list_info(\@project_list)5576# ensures that all fields are filled (and invalid projects removed)5577#5578# NOTE: modifies $projlist, but does not remove entries from it5579sub fill_project_list_info {5580my($projlist,@wanted_keys) =@_;5581my@projects;5582my$filter_set=sub{return@_; };5583if(@wanted_keys) {5584my%wanted_keys=map{$_=>1}@wanted_keys;5585$filter_set=sub{returngrep{$wanted_keys{$_} }@_; };5586}55875588my$show_ctags= gitweb_check_feature('ctags');5589 PROJECT:5590foreachmy$pr(@$projlist) {5591if(project_info_needs_filling($pr,$filter_set->('age','age_string'))) {5592my(@activity) = git_get_last_activity($pr->{'path'});5593unless(@activity) {5594next PROJECT;5595}5596($pr->{'age'},$pr->{'age_string'}) =@activity;5597}5598if(project_info_needs_filling($pr,$filter_set->('descr','descr_long'))) {5599my$descr= git_get_project_description($pr->{'path'}) ||"";5600$descr= to_utf8($descr);5601$pr->{'descr_long'} =$descr;5602$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);5603}5604if(project_info_needs_filling($pr,$filter_set->('owner'))) {5605$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";5606}5607if($show_ctags&&5608 project_info_needs_filling($pr,$filter_set->('ctags'))) {5609$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});5610}5611if($projects_list_group_categories&&5612 project_info_needs_filling($pr,$filter_set->('category'))) {5613my$cat= git_get_project_category($pr->{'path'}) ||5614$project_list_default_category;5615$pr->{'category'} = to_utf8($cat);5616}56175618push@projects,$pr;5619}56205621return@projects;5622}56235624sub sort_projects_list {5625my($projlist,$order) =@_;56265627sub order_str {5628my$key=shift;5629return sub{$a->{$key}cmp$b->{$key} };5630}56315632sub order_num_then_undef {5633my$key=shift;5634return sub{5635defined$a->{$key} ?5636(defined$b->{$key} ?$a->{$key} <=>$b->{$key} : -1) :5637(defined$b->{$key} ?1:0)5638};5639}56405641my%orderings= (5642 project => order_str('path'),5643 descr => order_str('descr_long'),5644 owner => order_str('owner'),5645 age => order_num_then_undef('age'),5646);56475648my$ordering=$orderings{$order};5649returndefined$ordering?sort$ordering @$projlist:@$projlist;5650}56515652# returns a hash of categories, containing the list of project5653# belonging to each category5654sub build_projlist_by_category {5655my($projlist,$from,$to) =@_;5656my%categories;56575658$from=0unlessdefined$from;5659$to=$#$projlistif(!defined$to||$#$projlist<$to);56605661for(my$i=$from;$i<=$to;$i++) {5662my$pr=$projlist->[$i];5663push@{$categories{$pr->{'category'} }},$pr;5664}56655666returnwantarray?%categories: \%categories;5667}56685669# print 'sort by' <th> element, generating 'sort by $name' replay link5670# if that order is not selected5671sub print_sort_th {5672print format_sort_th(@_);5673}56745675sub format_sort_th {5676my($name,$order,$header) =@_;5677my$sort_th="";5678$header||=ucfirst($name);56795680if($ordereq$name) {5681$sort_th.="<th>$header</th>\n";5682}else{5683$sort_th.="<th>".5684$cgi->a({-href => href(-replay=>1, order=>$name),5685-class=>"header"},$header) .5686"</th>\n";5687}56885689return$sort_th;5690}56915692sub git_project_list_rows {5693my($projlist,$from,$to,$check_forks) =@_;56945695$from=0unlessdefined$from;5696$to=$#$projlistif(!defined$to||$#$projlist<$to);56975698my$alternate=1;5699for(my$i=$from;$i<=$to;$i++) {5700my$pr=$projlist->[$i];57015702if($alternate) {5703print"<tr class=\"dark\">\n";5704}else{5705print"<tr class=\"light\">\n";5706}5707$alternate^=1;57085709if($check_forks) {5710print"<td>";5711if($pr->{'forks'}) {5712my$nforks=scalar@{$pr->{'forks'}};5713if($nforks>0) {5714print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5715-title =>"$nforksforks"},"+");5716}else{5717print$cgi->span({-title =>"$nforksforks"},"+");5718}5719}5720print"</td>\n";5721}5722print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5723-class=>"list"},5724 esc_html_match_hl($pr->{'path'},$search_regexp)) .5725"</td>\n".5726"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5727-class=>"list",5728-title =>$pr->{'descr_long'}},5729$search_regexp5730? esc_html_match_hl_chopped($pr->{'descr_long'},5731$pr->{'descr'},$search_regexp)5732: esc_html($pr->{'descr'})) .5733"</td>\n";5734unless($omit_owner) {5735print"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5736}5737unless($omit_age_column) {5738print"<td class=\"". age_class($pr->{'age'}) ."\">".5739(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n";5740}5741print"<td class=\"link\">".5742$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5743$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5744$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5745$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5746($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5747"</td>\n".5748"</tr>\n";5749}5750}57515752sub git_project_list_body {5753# actually uses global variable $project5754my($projlist,$order,$from,$to,$extra,$no_header) =@_;5755my@projects=@$projlist;57565757my$check_forks= gitweb_check_feature('forks');5758my$show_ctags= gitweb_check_feature('ctags');5759my$tagfilter=$show_ctags?$input_params{'ctag'} :undef;5760$check_forks=undef5761if($tagfilter||$search_regexp);57625763# filtering out forks before filling info allows to do less work5764@projects= filter_forks_from_projects_list(\@projects)5765if($check_forks);5766# search_projects_list pre-fills required info5767@projects= search_projects_list(\@projects,5768'search_regexp'=>$search_regexp,5769'tagfilter'=>$tagfilter)5770if($tagfilter||$search_regexp);5771# fill the rest5772my@all_fields= ('descr','descr_long','ctags','category');5773push@all_fields, ('age','age_string')unless($omit_age_column);5774push@all_fields,'owner'unless($omit_owner);5775@projects= fill_project_list_info(\@projects,@all_fields);57765777$order||=$default_projects_order;5778$from=0unlessdefined$from;5779$to=$#projectsif(!defined$to||$#projects<$to);57805781# short circuit5782if($from>$to) {5783print"<center>\n".5784"<b>No such projects found</b><br />\n".5785"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5786"</center>\n<br />\n";5787return;5788}57895790@projects= sort_projects_list(\@projects,$order);57915792if($show_ctags) {5793my$ctags= git_gather_all_ctags(\@projects);5794my$cloud= git_populate_project_tagcloud($ctags);5795print git_show_project_tagcloud($cloud,64);5796}57975798print"<table class=\"project_list\">\n";5799unless($no_header) {5800print"<tr>\n";5801if($check_forks) {5802print"<th></th>\n";5803}5804 print_sort_th('project',$order,'Project');5805 print_sort_th('descr',$order,'Description');5806 print_sort_th('owner',$order,'Owner')unless$omit_owner;5807 print_sort_th('age',$order,'Last Change')unless$omit_age_column;5808print"<th></th>\n".# for links5809"</tr>\n";5810}58115812if($projects_list_group_categories) {5813# only display categories with projects in the $from-$to window5814@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5815my%categories= build_projlist_by_category(\@projects,$from,$to);5816foreachmy$cat(sort keys%categories) {5817unless($cateq"") {5818print"<tr>\n";5819if($check_forks) {5820print"<td></td>\n";5821}5822print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5823print"</tr>\n";5824}58255826 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5827}5828}else{5829 git_project_list_rows(\@projects,$from,$to,$check_forks);5830}58315832if(defined$extra) {5833print"<tr>\n";5834if($check_forks) {5835print"<td></td>\n";5836}5837print"<td colspan=\"5\">$extra</td>\n".5838"</tr>\n";5839}5840print"</table>\n";5841}58425843sub git_log_body {5844# uses global variable $project5845my($commitlist,$from,$to,$refs,$extra) =@_;58465847$from=0unlessdefined$from;5848$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);58495850for(my$i=0;$i<=$to;$i++) {5851my%co= %{$commitlist->[$i]};5852next if!%co;5853my$commit=$co{'id'};5854my$ref= format_ref_marker($refs,$commit);5855 git_print_header_div('commit',5856"<span class=\"age\">$co{'age_string'}</span>".5857 esc_html($co{'title'}) .$ref,5858$commit);5859print"<div class=\"title_text\">\n".5860"<div class=\"log_link\">\n".5861$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5862" | ".5863$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5864" | ".5865$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5866"<br/>\n".5867"</div>\n";5868 git_print_authorship(\%co, -tag =>'span');5869print"<br/>\n</div>\n";58705871print"<div class=\"log_body\">\n";5872 git_print_log($co{'comment'}, -final_empty_line=>1);5873print"</div>\n";5874}5875if($extra) {5876print"<div class=\"page_nav\">\n";5877print"$extra\n";5878print"</div>\n";5879}5880}58815882sub git_shortlog_body {5883# uses global variable $project5884my($commitlist,$from,$to,$refs,$extra) =@_;58855886$from=0unlessdefined$from;5887$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);58885889print"<table class=\"shortlog\">\n";5890my$alternate=1;5891for(my$i=$from;$i<=$to;$i++) {5892my%co= %{$commitlist->[$i]};5893my$commit=$co{'id'};5894my$ref= format_ref_marker($refs,$commit);5895if($alternate) {5896print"<tr class=\"dark\">\n";5897}else{5898print"<tr class=\"light\">\n";5899}5900$alternate^=1;5901# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5902print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5903 format_author_html('td', \%co,10) ."<td>";5904print format_subject_html($co{'title'},$co{'title_short'},5905 href(action=>"commit", hash=>$commit),$ref);5906print"</td>\n".5907"<td class=\"link\">".5908$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5909$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5910$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5911my$snapshot_links= format_snapshot_links($commit);5912if(defined$snapshot_links) {5913print" | ".$snapshot_links;5914}5915print"</td>\n".5916"</tr>\n";5917}5918if(defined$extra) {5919print"<tr>\n".5920"<td colspan=\"4\">$extra</td>\n".5921"</tr>\n";5922}5923print"</table>\n";5924}59255926sub git_history_body {5927# Warning: assumes constant type (blob or tree) during history5928my($commitlist,$from,$to,$refs,$extra,5929$file_name,$file_hash,$ftype) =@_;59305931$from=0unlessdefined$from;5932$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});59335934print"<table class=\"history\">\n";5935my$alternate=1;5936for(my$i=$from;$i<=$to;$i++) {5937my%co= %{$commitlist->[$i]};5938if(!%co) {5939next;5940}5941my$commit=$co{'id'};59425943my$ref= format_ref_marker($refs,$commit);59445945if($alternate) {5946print"<tr class=\"dark\">\n";5947}else{5948print"<tr class=\"light\">\n";5949}5950$alternate^=1;5951print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5952# shortlog: format_author_html('td', \%co, 10)5953 format_author_html('td', \%co,15,3) ."<td>";5954# originally git_history used chop_str($co{'title'}, 50)5955print format_subject_html($co{'title'},$co{'title_short'},5956 href(action=>"commit", hash=>$commit),$ref);5957print"</td>\n".5958"<td class=\"link\">".5959$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5960$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");59615962if($ftypeeq'blob') {5963print" | ".5964$cgi->a({-href => href(action=>"blob_plain", hash_base=>$commit, file_name=>$file_name)},"raw");59655966my$blob_current=$file_hash;5967my$blob_parent= git_get_hash_by_path($commit,$file_name);5968if(defined$blob_current&&defined$blob_parent&&5969$blob_currentne$blob_parent) {5970print" | ".5971$cgi->a({-href => href(action=>"blobdiff",5972 hash=>$blob_current, hash_parent=>$blob_parent,5973 hash_base=>$hash_base, hash_parent_base=>$commit,5974 file_name=>$file_name)},5975"diff to current");5976}5977}5978print"</td>\n".5979"</tr>\n";5980}5981if(defined$extra) {5982print"<tr>\n".5983"<td colspan=\"4\">$extra</td>\n".5984"</tr>\n";5985}5986print"</table>\n";5987}59885989sub git_tags_body {5990# uses global variable $project5991my($taglist,$from,$to,$extra) =@_;5992$from=0unlessdefined$from;5993$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);59945995print"<table class=\"tags\">\n";5996my$alternate=1;5997for(my$i=$from;$i<=$to;$i++) {5998my$entry=$taglist->[$i];5999my%tag=%$entry;6000my$comment=$tag{'subject'};6001my$comment_short;6002if(defined$comment) {6003$comment_short= chop_str($comment,30,5);6004}6005if($alternate) {6006print"<tr class=\"dark\">\n";6007}else{6008print"<tr class=\"light\">\n";6009}6010$alternate^=1;6011if(defined$tag{'age'}) {6012print"<td><i>$tag{'age'}</i></td>\n";6013}else{6014print"<td></td>\n";6015}6016print"<td>".6017$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),6018-class=>"list name"}, esc_html($tag{'name'})) .6019"</td>\n".6020"<td>";6021if(defined$comment) {6022print format_subject_html($comment,$comment_short,6023 href(action=>"tag", hash=>$tag{'id'}));6024}6025print"</td>\n".6026"<td class=\"selflink\">";6027if($tag{'type'}eq"tag") {6028print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");6029}else{6030print" ";6031}6032print"</td>\n".6033"<td class=\"link\">"." | ".6034$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});6035if($tag{'reftype'}eq"commit") {6036print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .6037" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");6038}elsif($tag{'reftype'}eq"blob") {6039print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");6040}6041print"</td>\n".6042"</tr>";6043}6044if(defined$extra) {6045print"<tr>\n".6046"<td colspan=\"5\">$extra</td>\n".6047"</tr>\n";6048}6049print"</table>\n";6050}60516052sub git_heads_body {6053# uses global variable $project6054my($headlist,$head_at,$from,$to,$extra) =@_;6055$from=0unlessdefined$from;6056$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);60576058print"<table class=\"heads\">\n";6059my$alternate=1;6060for(my$i=$from;$i<=$to;$i++) {6061my$entry=$headlist->[$i];6062my%ref=%$entry;6063my$curr=defined$head_at&&$ref{'id'}eq$head_at;6064if($alternate) {6065print"<tr class=\"dark\">\n";6066}else{6067print"<tr class=\"light\">\n";6068}6069$alternate^=1;6070print"<td><i>$ref{'age'}</i></td>\n".6071($curr?"<td class=\"current_head\">":"<td>") .6072$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),6073-class=>"list name"},esc_html($ref{'name'})) .6074"</td>\n".6075"<td class=\"link\">".6076$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".6077$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".6078$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .6079"</td>\n".6080"</tr>";6081}6082if(defined$extra) {6083print"<tr>\n".6084"<td colspan=\"3\">$extra</td>\n".6085"</tr>\n";6086}6087print"</table>\n";6088}60896090# Display a single remote block6091sub git_remote_block {6092my($remote,$rdata,$limit,$head) =@_;60936094my$heads=$rdata->{'heads'};6095my$fetch=$rdata->{'fetch'};6096my$push=$rdata->{'push'};60976098my$urls_table="<table class=\"projects_list\">\n";60996100if(defined$fetch) {6101if($fetcheq$push) {6102$urls_table.= format_repo_url("URL",$fetch);6103}else{6104$urls_table.= format_repo_url("Fetch URL",$fetch);6105$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;6106}6107}elsif(defined$push) {6108$urls_table.= format_repo_url("Push URL",$push);6109}else{6110$urls_table.= format_repo_url("","No remote URL");6111}61126113$urls_table.="</table>\n";61146115my$dots;6116if(defined$limit&&$limit<@$heads) {6117$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");6118}61196120print$urls_table;6121 git_heads_body($heads,$head,0,$limit,$dots);6122}61236124# Display a list of remote names with the respective fetch and push URLs6125sub git_remotes_list {6126my($remotedata,$limit) =@_;6127print"<table class=\"heads\">\n";6128my$alternate=1;6129my@remotes=sort keys%$remotedata;61306131my$limited=$limit&&$limit<@remotes;61326133$#remotes=$limit-1if$limited;61346135while(my$remote=shift@remotes) {6136my$rdata=$remotedata->{$remote};6137my$fetch=$rdata->{'fetch'};6138my$push=$rdata->{'push'};6139if($alternate) {6140print"<tr class=\"dark\">\n";6141}else{6142print"<tr class=\"light\">\n";6143}6144$alternate^=1;6145print"<td>".6146$cgi->a({-href=> href(action=>'remotes', hash=>$remote),6147-class=>"list name"},esc_html($remote)) .6148"</td>";6149print"<td class=\"link\">".6150(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .6151" | ".6152(defined$push?$cgi->a({-href=>$push},"push") :"push") .6153"</td>";61546155print"</tr>\n";6156}61576158if($limited) {6159print"<tr>\n".6160"<td colspan=\"3\">".6161$cgi->a({-href => href(action=>"remotes")},"...") .6162"</td>\n"."</tr>\n";6163}61646165print"</table>";6166}61676168# Display remote heads grouped by remote, unless there are too many6169# remotes, in which case we only display the remote names6170sub git_remotes_body {6171my($remotedata,$limit,$head) =@_;6172if($limitand$limit<keys%$remotedata) {6173 git_remotes_list($remotedata,$limit);6174}else{6175 fill_remote_heads($remotedata);6176while(my($remote,$rdata) =each%$remotedata) {6177 git_print_section({-class=>"remote", -id=>$remote},6178["remotes",$remote,$remote],sub{6179 git_remote_block($remote,$rdata,$limit,$head);6180});6181}6182}6183}61846185sub git_search_message {6186my%co=@_;61876188my$greptype;6189if($searchtypeeq'commit') {6190$greptype="--grep=";6191}elsif($searchtypeeq'author') {6192$greptype="--author=";6193}elsif($searchtypeeq'committer') {6194$greptype="--committer=";6195}6196$greptype.=$searchtext;6197my@commitlist= parse_commits($hash,101, (100*$page),undef,6198$greptype,'--regexp-ignore-case',6199$search_use_regexp?'--extended-regexp':'--fixed-strings');62006201my$paging_nav='';6202if($page>0) {6203$paging_nav.=6204$cgi->a({-href => href(-replay=>1, page=>undef)},6205"first") .6206" ⋅ ".6207$cgi->a({-href => href(-replay=>1, page=>$page-1),6208-accesskey =>"p", -title =>"Alt-p"},"prev");6209}else{6210$paging_nav.="first ⋅ prev";6211}6212my$next_link='';6213if($#commitlist>=100) {6214$next_link=6215$cgi->a({-href => href(-replay=>1, page=>$page+1),6216-accesskey =>"n", -title =>"Alt-n"},"next");6217$paging_nav.=" ⋅$next_link";6218}else{6219$paging_nav.=" ⋅ next";6220}62216222 git_header_html();62236224 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);6225 git_print_header_div('commit', esc_html($co{'title'}),$hash);6226if($page==0&& !@commitlist) {6227print"<p>No match.</p>\n";6228}else{6229 git_search_grep_body(\@commitlist,0,99,$next_link);6230}62316232 git_footer_html();6233}62346235sub git_search_changes {6236my%co=@_;62376238local$/="\n";6239open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,6240'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",6241($search_use_regexp?'--pickaxe-regex': ())6242or die_error(500,"Open git-log failed");62436244 git_header_html();62456246 git_print_page_nav('','',$hash,$co{'tree'},$hash);6247 git_print_header_div('commit', esc_html($co{'title'}),$hash);62486249print"<table class=\"pickaxe search\">\n";6250my$alternate=1;6251undef%co;6252my@files;6253while(my$line= <$fd>) {6254chomp$line;6255next unless$line;62566257my%set= parse_difftree_raw_line($line);6258if(defined$set{'commit'}) {6259# finish previous commit6260if(%co) {6261print"</td>\n".6262"<td class=\"link\">".6263$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6264"commit") .6265" | ".6266$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6267 hash_base=>$co{'id'})},6268"tree") .6269"</td>\n".6270"</tr>\n";6271}62726273if($alternate) {6274print"<tr class=\"dark\">\n";6275}else{6276print"<tr class=\"light\">\n";6277}6278$alternate^=1;6279%co= parse_commit($set{'commit'});6280my$author= chop_and_escape_str($co{'author_name'},15,5);6281print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6282"<td><i>$author</i></td>\n".6283"<td>".6284$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6285-class=>"list subject"},6286 chop_and_escape_str($co{'title'},50) ."<br/>");6287}elsif(defined$set{'to_id'}) {6288next if($set{'to_id'} =~m/^0{40}$/);62896290print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},6291 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),6292-class=>"list"},6293"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .6294"<br/>\n";6295}6296}6297close$fd;62986299# finish last commit (warning: repetition!)6300if(%co) {6301print"</td>\n".6302"<td class=\"link\">".6303$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6304"commit") .6305" | ".6306$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6307 hash_base=>$co{'id'})},6308"tree") .6309"</td>\n".6310"</tr>\n";6311}63126313print"</table>\n";63146315 git_footer_html();6316}63176318sub git_search_files {6319my%co=@_;63206321local$/="\n";6322open my$fd,"-|", git_cmd(),'grep','-n','-z',6323$search_use_regexp? ('-E','-i') :'-F',6324$searchtext,$co{'tree'}6325or die_error(500,"Open git-grep failed");63266327 git_header_html();63286329 git_print_page_nav('','',$hash,$co{'tree'},$hash);6330 git_print_header_div('commit', esc_html($co{'title'}),$hash);63316332print"<table class=\"grep_search\">\n";6333my$alternate=1;6334my$matches=0;6335my$lastfile='';6336my$file_href;6337while(my$line= <$fd>) {6338chomp$line;6339my($file,$lno,$ltext,$binary);6340last if($matches++>1000);6341if($line=~/^Binary file (.+) matches$/) {6342$file=$1;6343$binary=1;6344}else{6345($file,$lno,$ltext) =split(/\0/,$line,3);6346$file=~s/^$co{'tree'}://;6347}6348if($filene$lastfile) {6349$lastfileand print"</td></tr>\n";6350if($alternate++) {6351print"<tr class=\"dark\">\n";6352}else{6353print"<tr class=\"light\">\n";6354}6355$file_href= href(action=>"blob", hash_base=>$co{'id'},6356 file_name=>$file);6357print"<td class=\"list\">".6358$cgi->a({-href =>$file_href, -class=>"list"}, esc_path($file));6359print"</td><td>\n";6360$lastfile=$file;6361}6362if($binary) {6363print"<div class=\"binary\">Binary file</div>\n";6364}else{6365$ltext= untabify($ltext);6366if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6367$ltext= esc_html($1, -nbsp=>1);6368$ltext.='<span class="match">';6369$ltext.= esc_html($2, -nbsp=>1);6370$ltext.='</span>';6371$ltext.= esc_html($3, -nbsp=>1);6372}else{6373$ltext= esc_html($ltext, -nbsp=>1);6374}6375print"<div class=\"pre\">".6376$cgi->a({-href =>$file_href.'#l'.$lno,6377-class=>"linenr"},sprintf('%4i',$lno)) .6378' '.$ltext."</div>\n";6379}6380}6381if($lastfile) {6382print"</td></tr>\n";6383if($matches>1000) {6384print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6385}6386}else{6387print"<div class=\"diff nodifferences\">No matches found</div>\n";6388}6389close$fd;63906391print"</table>\n";63926393 git_footer_html();6394}63956396sub git_search_grep_body {6397my($commitlist,$from,$to,$extra) =@_;6398$from=0unlessdefined$from;6399$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);64006401print"<table class=\"commit_search\">\n";6402my$alternate=1;6403for(my$i=$from;$i<=$to;$i++) {6404my%co= %{$commitlist->[$i]};6405if(!%co) {6406next;6407}6408my$commit=$co{'id'};6409if($alternate) {6410print"<tr class=\"dark\">\n";6411}else{6412print"<tr class=\"light\">\n";6413}6414$alternate^=1;6415print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6416 format_author_html('td', \%co,15,5) .6417"<td>".6418$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6419-class=>"list subject"},6420 chop_and_escape_str($co{'title'},50) ."<br/>");6421my$comment=$co{'comment'};6422foreachmy$line(@$comment) {6423if($line=~m/^(.*?)($search_regexp)(.*)$/i) {6424my($lead,$match,$trail) = ($1,$2,$3);6425$match= chop_str($match,70,5,'center');6426my$contextlen=int((80-length($match))/2);6427$contextlen=30if($contextlen>30);6428$lead= chop_str($lead,$contextlen,10,'left');6429$trail= chop_str($trail,$contextlen,10,'right');64306431$lead= esc_html($lead);6432$match= esc_html($match);6433$trail= esc_html($trail);64346435print"$lead<span class=\"match\">$match</span>$trail<br />";6436}6437}6438print"</td>\n".6439"<td class=\"link\">".6440$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6441" | ".6442$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .6443" | ".6444$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6445print"</td>\n".6446"</tr>\n";6447}6448if(defined$extra) {6449print"<tr>\n".6450"<td colspan=\"3\">$extra</td>\n".6451"</tr>\n";6452}6453print"</table>\n";6454}64556456## ======================================================================6457## ======================================================================6458## actions64596460sub git_project_list {6461my$order=$input_params{'order'};6462if(defined$order&&$order!~m/none|project|descr|owner|age/) {6463 die_error(400,"Unknown order parameter");6464}64656466my@list= git_get_projects_list($project_filter,$strict_export);6467if(!@list) {6468 die_error(404,"No projects found");6469}64706471 git_header_html();6472if(defined$home_text&& -f $home_text) {6473print"<div class=\"index_include\">\n";6474 insert_file($home_text);6475print"</div>\n";6476}64776478 git_project_search_form($searchtext,$search_use_regexp);6479 git_project_list_body(\@list,$order);6480 git_footer_html();6481}64826483sub git_forks {6484my$order=$input_params{'order'};6485if(defined$order&&$order!~m/none|project|descr|owner|age/) {6486 die_error(400,"Unknown order parameter");6487}64886489my$filter=$project;6490$filter=~s/\.git$//;6491my@list= git_get_projects_list($filter);6492if(!@list) {6493 die_error(404,"No forks found");6494}64956496 git_header_html();6497 git_print_page_nav('','');6498 git_print_header_div('summary',"$projectforks");6499 git_project_list_body(\@list,$order);6500 git_footer_html();6501}65026503sub git_project_index {6504my@projects= git_get_projects_list($project_filter,$strict_export);6505if(!@projects) {6506 die_error(404,"No projects found");6507}65086509print$cgi->header(6510-type =>'text/plain',6511-charset =>'utf-8',6512-content_disposition =>'inline; filename="index.aux"');65136514foreachmy$pr(@projects) {6515if(!exists$pr->{'owner'}) {6516$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");6517}65186519my($path,$owner) = ($pr->{'path'},$pr->{'owner'});6520# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '6521$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6522$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6523$path=~s/ /\+/g;6524$owner=~s/ /\+/g;65256526print"$path$owner\n";6527}6528}65296530sub git_summary {6531my$descr= git_get_project_description($project) ||"none";6532my%co= parse_commit("HEAD");6533my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();6534my$head=$co{'id'};6535my$remote_heads= gitweb_check_feature('remote_heads');65366537my$owner= git_get_project_owner($project);65386539my$refs= git_get_references();6540# These get_*_list functions return one more to allow us to see if6541# there are more ...6542my@taglist= git_get_tags_list(16);6543my@headlist= git_get_heads_list(16);6544my%remotedata=$remote_heads? git_get_remotes_list() : ();6545my@forklist;6546my$check_forks= gitweb_check_feature('forks');65476548if($check_forks) {6549# find forks of a project6550my$filter=$project;6551$filter=~s/\.git$//;6552@forklist= git_get_projects_list($filter);6553# filter out forks of forks6554@forklist= filter_forks_from_projects_list(\@forklist)6555if(@forklist);6556}65576558 git_header_html();6559 git_print_page_nav('summary','',$head);65606561print"<div class=\"title\"> </div>\n";6562print"<table class=\"projects_list\">\n".6563"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n";6564if($ownerand not$omit_owner) {6565print"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";6566}6567if(defined$cd{'rfc2822'}) {6568print"<tr id=\"metadata_lchange\"><td>last change</td>".6569"<td>".format_timestamp_html(\%cd)."</td></tr>\n";6570}65716572# use per project git URL list in $projectroot/$project/cloneurl6573# or make project git URL from git base URL and project name6574my$url_tag="URL";6575my@url_list= git_get_project_url_list($project);6576@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;6577foreachmy$git_url(@url_list) {6578next unless$git_url;6579print format_repo_url($url_tag,$git_url);6580$url_tag="";6581}65826583# Tag cloud6584my$show_ctags= gitweb_check_feature('ctags');6585if($show_ctags) {6586my$ctags= git_get_project_ctags($project);6587if(%$ctags) {6588# without ability to add tags, don't show if there are none6589my$cloud= git_populate_project_tagcloud($ctags);6590print"<tr id=\"metadata_ctags\">".6591"<td>content tags</td>".6592"<td>".git_show_project_tagcloud($cloud,48)."</td>".6593"</tr>\n";6594}6595}65966597print"</table>\n";65986599# If XSS prevention is on, we don't include README.html.6600# TODO: Allow a readme in some safe format.6601if(!$prevent_xss&& -s "$projectroot/$project/README.html") {6602print"<div class=\"title\">readme</div>\n".6603"<div class=\"readme\">\n";6604 insert_file("$projectroot/$project/README.html");6605print"\n</div>\n";# class="readme"6606}66076608# we need to request one more than 16 (0..15) to check if6609# those 16 are all6610my@commitlist=$head? parse_commits($head,17) : ();6611if(@commitlist) {6612 git_print_header_div('shortlog');6613 git_shortlog_body(\@commitlist,0,15,$refs,6614$#commitlist<=15?undef:6615$cgi->a({-href => href(action=>"shortlog")},"..."));6616}66176618if(@taglist) {6619 git_print_header_div('tags');6620 git_tags_body(\@taglist,0,15,6621$#taglist<=15?undef:6622$cgi->a({-href => href(action=>"tags")},"..."));6623}66246625if(@headlist) {6626 git_print_header_div('heads');6627 git_heads_body(\@headlist,$head,0,15,6628$#headlist<=15?undef:6629$cgi->a({-href => href(action=>"heads")},"..."));6630}66316632if(%remotedata) {6633 git_print_header_div('remotes');6634 git_remotes_body(\%remotedata,15,$head);6635}66366637if(@forklist) {6638 git_print_header_div('forks');6639 git_project_list_body(\@forklist,'age',0,15,6640$#forklist<=15?undef:6641$cgi->a({-href => href(action=>"forks")},"..."),6642'no_header');6643}66446645 git_footer_html();6646}66476648sub git_tag {6649my%tag= parse_tag($hash);66506651if(!%tag) {6652 die_error(404,"Unknown tag object");6653}66546655my$head= git_get_head_hash($project);6656 git_header_html();6657 git_print_page_nav('','',$head,undef,$head);6658 git_print_header_div('commit', esc_html($tag{'name'}),$hash);6659print"<div class=\"title_text\">\n".6660"<table class=\"object_header\">\n".6661"<tr>\n".6662"<td>object</td>\n".6663"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6664$tag{'object'}) ."</td>\n".6665"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6666$tag{'type'}) ."</td>\n".6667"</tr>\n";6668if(defined($tag{'author'})) {6669 git_print_authorship_rows(\%tag,'author');6670}6671print"</table>\n\n".6672"</div>\n";6673print"<div class=\"page_body\">";6674my$comment=$tag{'comment'};6675foreachmy$line(@$comment) {6676chomp$line;6677print esc_html($line, -nbsp=>1) ."<br/>\n";6678}6679print"</div>\n";6680 git_footer_html();6681}66826683sub git_blame_common {6684my$format=shift||'porcelain';6685if($formateq'porcelain'&&$input_params{'javascript'}) {6686$format='incremental';6687$action='blame_incremental';# for page title etc6688}66896690# permissions6691 gitweb_check_feature('blame')6692or die_error(403,"Blame view not allowed");66936694# error checking6695 die_error(400,"No file name given")unless$file_name;6696$hash_base||= git_get_head_hash($project);6697 die_error(404,"Couldn't find base commit")unless$hash_base;6698my%co= parse_commit($hash_base)6699or die_error(404,"Commit not found");6700my$ftype="blob";6701if(!defined$hash) {6702$hash= git_get_hash_by_path($hash_base,$file_name,"blob")6703or die_error(404,"Error looking up file");6704}else{6705$ftype= git_get_type($hash);6706if($ftype!~"blob") {6707 die_error(400,"Object is not a blob");6708}6709}67106711my$fd;6712if($formateq'incremental') {6713# get file contents (as base)6714open$fd,"-|", git_cmd(),'cat-file','blob',$hash6715or die_error(500,"Open git-cat-file failed");6716}elsif($formateq'data') {6717# run git-blame --incremental6718open$fd,"-|", git_cmd(),"blame","--incremental",6719$hash_base,"--",$file_name6720or die_error(500,"Open git-blame --incremental failed");6721}else{6722# run git-blame --porcelain6723open$fd,"-|", git_cmd(),"blame",'-p',6724$hash_base,'--',$file_name6725or die_error(500,"Open git-blame --porcelain failed");6726}6727binmode$fd,':utf8';67286729# incremental blame data returns early6730if($formateq'data') {6731print$cgi->header(6732-type=>"text/plain", -charset =>"utf-8",6733-status=>"200 OK");6734local$| =1;# output autoflush6735while(my$line= <$fd>) {6736print to_utf8($line);6737}6738close$fd6739or print"ERROR$!\n";67406741print'END';6742if(defined$t0&& gitweb_check_feature('timed')) {6743print' '.6744 tv_interval($t0, [ gettimeofday() ]).6745' '.$number_of_git_cmds;6746}6747print"\n";67486749return;6750}67516752# page header6753 git_header_html();6754my$formats_nav=6755$cgi->a({-href => href(action=>"blob", -replay=>1)},6756"blob") .6757" | ";6758if($formateq'incremental') {6759$formats_nav.=6760$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},6761"blame") ." (non-incremental)";6762}else{6763$formats_nav.=6764$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},6765"blame") ." (incremental)";6766}6767$formats_nav.=6768" | ".6769$cgi->a({-href => href(action=>"history", -replay=>1)},6770"history") .6771" | ".6772$cgi->a({-href => href(action=>$action, file_name=>$file_name)},6773"HEAD");6774 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6775 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6776 git_print_page_path($file_name,$ftype,$hash_base);67776778# page body6779if($formateq'incremental') {6780print"<noscript>\n<div class=\"error\"><center><b>\n".6781"This page requires JavaScript to run.\nUse ".6782$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},6783'this page').6784" instead.\n".6785"</b></center></div>\n</noscript>\n";67866787print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;6788}67896790print qq!<div class="page_body">\n!;6791print qq!<div id="progress_info">.../ ...</div>\n!6792if($formateq'incremental');6793print qq!<table id="blame_table"class="blame" width="100%">\n!.6794#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.6795 qq!<thead>\n!.6796 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.6797 qq!</thead>\n!.6798 qq!<tbody>\n!;67996800my@rev_color=qw(light dark);6801my$num_colors=scalar(@rev_color);6802my$current_color=0;68036804if($formateq'incremental') {6805my$color_class=$rev_color[$current_color];68066807#contents of a file6808my$linenr=0;6809 LINE:6810while(my$line= <$fd>) {6811chomp$line;6812$linenr++;68136814print qq!<tr id="l$linenr"class="$color_class">!.6815 qq!<td class="sha1"><a href=""> </a></td>!.6816 qq!<td class="linenr">!.6817 qq!<a class="linenr" href="">$linenr</a></td>!;6818print qq!<td class="pre">! . esc_html($line) ."</td>\n";6819print qq!</tr>\n!;6820}68216822}else{# porcelain, i.e. ordinary blame6823my%metainfo= ();# saves information about commits68246825# blame data6826 LINE:6827while(my$line= <$fd>) {6828chomp$line;6829# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]6830# no <lines in group> for subsequent lines in group of lines6831my($full_rev,$orig_lineno,$lineno,$group_size) =6832($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);6833if(!exists$metainfo{$full_rev}) {6834$metainfo{$full_rev} = {'nprevious'=>0};6835}6836my$meta=$metainfo{$full_rev};6837my$data;6838while($data= <$fd>) {6839chomp$data;6840last if($data=~s/^\t//);# contents of line6841if($data=~/^(\S+)(?: (.*))?$/) {6842$meta->{$1} =$2unlessexists$meta->{$1};6843}6844if($data=~/^previous /) {6845$meta->{'nprevious'}++;6846}6847}6848my$short_rev=substr($full_rev,0,8);6849my$author=$meta->{'author'};6850my%date=6851 parse_date($meta->{'author-time'},$meta->{'author-tz'});6852my$date=$date{'iso-tz'};6853if($group_size) {6854$current_color= ($current_color+1) %$num_colors;6855}6856my$tr_class=$rev_color[$current_color];6857$tr_class.=' boundary'if(exists$meta->{'boundary'});6858$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);6859$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);6860print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";6861if($group_size) {6862print"<td class=\"sha1\"";6863print" title=\"". esc_html($author) .",$date\"";6864print" rowspan=\"$group_size\""if($group_size>1);6865print">";6866print$cgi->a({-href => href(action=>"commit",6867 hash=>$full_rev,6868 file_name=>$file_name)},6869 esc_html($short_rev));6870if($group_size>=2) {6871my@author_initials= ($author=~/\b([[:upper:]])\B/g);6872if(@author_initials) {6873print"<br />".6874 esc_html(join('',@author_initials));6875# or join('.', ...)6876}6877}6878print"</td>\n";6879}6880# 'previous' <sha1 of parent commit> <filename at commit>6881if(exists$meta->{'previous'} &&6882$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {6883$meta->{'parent'} =$1;6884$meta->{'file_parent'} = unquote($2);6885}6886my$linenr_commit=6887exists($meta->{'parent'}) ?6888$meta->{'parent'} :$full_rev;6889my$linenr_filename=6890exists($meta->{'file_parent'}) ?6891$meta->{'file_parent'} : unquote($meta->{'filename'});6892my$blamed= href(action =>'blame',6893 file_name =>$linenr_filename,6894 hash_base =>$linenr_commit);6895print"<td class=\"linenr\">";6896print$cgi->a({ -href =>"$blamed#l$orig_lineno",6897-class=>"linenr"},6898 esc_html($lineno));6899print"</td>";6900print"<td class=\"pre\">". esc_html($data) ."</td>\n";6901print"</tr>\n";6902}# end while69036904}69056906# footer6907print"</tbody>\n".6908"</table>\n";# class="blame"6909print"</div>\n";# class="blame_body"6910close$fd6911or print"Reading blob failed\n";69126913 git_footer_html();6914}69156916sub git_blame {6917 git_blame_common();6918}69196920sub git_blame_incremental {6921 git_blame_common('incremental');6922}69236924sub git_blame_data {6925 git_blame_common('data');6926}69276928sub git_tags {6929my$head= git_get_head_hash($project);6930 git_header_html();6931 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6932 git_print_header_div('summary',$project);69336934my@tagslist= git_get_tags_list();6935if(@tagslist) {6936 git_tags_body(\@tagslist);6937}6938 git_footer_html();6939}69406941sub git_heads {6942my$head= git_get_head_hash($project);6943 git_header_html();6944 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6945 git_print_header_div('summary',$project);69466947my@headslist= git_get_heads_list();6948if(@headslist) {6949 git_heads_body(\@headslist,$head);6950}6951 git_footer_html();6952}69536954# used both for single remote view and for list of all the remotes6955sub git_remotes {6956 gitweb_check_feature('remote_heads')6957or die_error(403,"Remote heads view is disabled");69586959my$head= git_get_head_hash($project);6960my$remote=$input_params{'hash'};69616962my$remotedata= git_get_remotes_list($remote);6963 die_error(500,"Unable to get remote information")unlessdefined$remotedata;69646965unless(%$remotedata) {6966 die_error(404,defined$remote?6967"Remote$remotenot found":6968"No remotes found");6969}69706971 git_header_html(undef,undef, -action_extra =>$remote);6972 git_print_page_nav('','',$head,undef,$head,6973 format_ref_views($remote?'':'remotes'));69746975 fill_remote_heads($remotedata);6976if(defined$remote) {6977 git_print_header_div('remotes',"$remoteremote for$project");6978 git_remote_block($remote,$remotedata->{$remote},undef,$head);6979}else{6980 git_print_header_div('summary',"$projectremotes");6981 git_remotes_body($remotedata,undef,$head);6982}69836984 git_footer_html();6985}69866987sub git_blob_plain {6988my$type=shift;6989my$expires;69906991if(!defined$hash) {6992if(defined$file_name) {6993my$base=$hash_base|| git_get_head_hash($project);6994$hash= git_get_hash_by_path($base,$file_name,"blob")6995or die_error(404,"Cannot find file");6996}else{6997 die_error(400,"No file name defined");6998}6999}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {7000# blobs defined by non-textual hash id's can be cached7001$expires="+1d";7002}70037004open my$fd,"-|", git_cmd(),"cat-file","blob",$hash7005or die_error(500,"Open git-cat-file blob '$hash' failed");70067007# content-type (can include charset)7008$type= blob_contenttype($fd,$file_name,$type);70097010# "save as" filename, even when no $file_name is given7011my$save_as="$hash";7012if(defined$file_name) {7013$save_as=$file_name;7014}elsif($type=~m/^text\//) {7015$save_as.='.txt';7016}70177018# With XSS prevention on, blobs of all types except a few known safe7019# ones are served with "Content-Disposition: attachment" to make sure7020# they don't run in our security domain. For certain image types,7021# blob view writes an <img> tag referring to blob_plain view, and we7022# want to be sure not to break that by serving the image as an7023# attachment (though Firefox 3 doesn't seem to care).7024my$sandbox=$prevent_xss&&7025$type!~m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;70267027# serve text/* as text/plain7028if($prevent_xss&&7029($type=~m!^text/[a-z]+\b(.*)$!||7030($type=~m!^[a-z]+/[a-z]\+xml\b(.*)$!&& -T $fd))) {7031my$rest=$1;7032$rest=defined$rest?$rest:'';7033$type="text/plain$rest";7034}70357036print$cgi->header(7037-type =>$type,7038-expires =>$expires,7039-content_disposition =>7040($sandbox?'attachment':'inline')7041.'; filename="'.$save_as.'"');7042local$/=undef;7043binmode STDOUT,':raw';7044print<$fd>;7045binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi7046close$fd;7047}70487049sub git_blob {7050my$expires;70517052if(!defined$hash) {7053if(defined$file_name) {7054my$base=$hash_base|| git_get_head_hash($project);7055$hash= git_get_hash_by_path($base,$file_name,"blob")7056or die_error(404,"Cannot find file");7057}else{7058 die_error(400,"No file name defined");7059}7060}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {7061# blobs defined by non-textual hash id's can be cached7062$expires="+1d";7063}70647065my$have_blame= gitweb_check_feature('blame');7066open my$fd,"-|", git_cmd(),"cat-file","blob",$hash7067or die_error(500,"Couldn't cat$file_name,$hash");7068my$mimetype= blob_mimetype($fd,$file_name);7069# use 'blob_plain' (aka 'raw') view for files that cannot be displayed7070if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {7071close$fd;7072return git_blob_plain($mimetype);7073}7074# we can have blame only for text/* mimetype7075$have_blame&&= ($mimetype=~m!^text/!);70767077my$highlight= gitweb_check_feature('highlight');7078my$syntax= guess_file_syntax($highlight,$file_name);7079$fd= run_highlighter($fd,$highlight,$syntax);70807081 git_header_html(undef,$expires);7082my$formats_nav='';7083if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7084if(defined$file_name) {7085if($have_blame) {7086$formats_nav.=7087$cgi->a({-href => href(action=>"blame", -replay=>1)},7088"blame") .7089" | ";7090}7091$formats_nav.=7092$cgi->a({-href => href(action=>"history", -replay=>1)},7093"history") .7094" | ".7095$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},7096"raw") .7097" | ".7098$cgi->a({-href => href(action=>"blob",7099 hash_base=>"HEAD", file_name=>$file_name)},7100"HEAD");7101}else{7102$formats_nav.=7103$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},7104"raw");7105}7106 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7107 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7108}else{7109print"<div class=\"page_nav\">\n".7110"<br/><br/></div>\n".7111"<div class=\"title\">".esc_html($hash)."</div>\n";7112}7113 git_print_page_path($file_name,"blob",$hash_base);7114print"<div class=\"page_body\">\n";7115if($mimetype=~m!^image/!) {7116print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;7117if($file_name) {7118print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;7119}7120print qq! src="! .7121 href(action=>"blob_plain", hash=>$hash,7122 hash_base=>$hash_base, file_name=>$file_name) .7123 qq!"/>\n!;7124}else{7125my$nr;7126while(my$line= <$fd>) {7127chomp$line;7128$nr++;7129$line= untabify($line);7130printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,7131$nr, esc_attr(href(-replay =>1)),$nr,$nr,7132$highlight? sanitize($line) : esc_html($line, -nbsp=>1);7133}7134}7135close$fd7136or print"Reading blob failed.\n";7137print"</div>";7138 git_footer_html();7139}71407141sub git_tree {7142if(!defined$hash_base) {7143$hash_base="HEAD";7144}7145if(!defined$hash) {7146if(defined$file_name) {7147$hash= git_get_hash_by_path($hash_base,$file_name,"tree");7148}else{7149$hash=$hash_base;7150}7151}7152 die_error(404,"No such tree")unlessdefined($hash);71537154my$show_sizes= gitweb_check_feature('show-sizes');7155my$have_blame= gitweb_check_feature('blame');71567157my@entries= ();7158{7159local$/="\0";7160open my$fd,"-|", git_cmd(),"ls-tree",'-z',7161($show_sizes?'-l': ()),@extra_options,$hash7162or die_error(500,"Open git-ls-tree failed");7163@entries=map{chomp;$_} <$fd>;7164close$fd7165or die_error(404,"Reading tree failed");7166}71677168my$refs= git_get_references();7169my$ref= format_ref_marker($refs,$hash_base);7170 git_header_html();7171my$basedir='';7172if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7173my@views_nav= ();7174if(defined$file_name) {7175push@views_nav,7176$cgi->a({-href => href(action=>"history", -replay=>1)},7177"history"),7178$cgi->a({-href => href(action=>"tree",7179 hash_base=>"HEAD", file_name=>$file_name)},7180"HEAD"),7181}7182my$snapshot_links= format_snapshot_links($hash);7183if(defined$snapshot_links) {7184# FIXME: Should be available when we have no hash base as well.7185push@views_nav,$snapshot_links;7186}7187 git_print_page_nav('tree','',$hash_base,undef,undef,7188join(' | ',@views_nav));7189 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);7190}else{7191undef$hash_base;7192print"<div class=\"page_nav\">\n";7193print"<br/><br/></div>\n";7194print"<div class=\"title\">".esc_html($hash)."</div>\n";7195}7196if(defined$file_name) {7197$basedir=$file_name;7198if($basedirne''&&substr($basedir, -1)ne'/') {7199$basedir.='/';7200}7201 git_print_page_path($file_name,'tree',$hash_base);7202}7203print"<div class=\"page_body\">\n";7204print"<table class=\"tree\">\n";7205my$alternate=1;7206# '..' (top directory) link if possible7207if(defined$hash_base&&7208defined$file_name&&$file_name=~m![^/]+$!) {7209if($alternate) {7210print"<tr class=\"dark\">\n";7211}else{7212print"<tr class=\"light\">\n";7213}7214$alternate^=1;72157216my$up=$file_name;7217$up=~s!/?[^/]+$!!;7218undef$upunless$up;7219# based on git_print_tree_entry7220print'<td class="mode">'. mode_str('040000') ."</td>\n";7221print'<td class="size"> </td>'."\n"if$show_sizes;7222print'<td class="list">';7223print$cgi->a({-href => href(action=>"tree",7224 hash_base=>$hash_base,7225 file_name=>$up)},7226"..");7227print"</td>\n";7228print"<td class=\"link\"></td>\n";72297230print"</tr>\n";7231}7232foreachmy$line(@entries) {7233my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);72347235if($alternate) {7236print"<tr class=\"dark\">\n";7237}else{7238print"<tr class=\"light\">\n";7239}7240$alternate^=1;72417242 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);72437244print"</tr>\n";7245}7246print"</table>\n".7247"</div>";7248 git_footer_html();7249}72507251sub sanitize_for_filename {7252my$name=shift;72537254$name=~s!/!-!g;7255$name=~s/[^[:alnum:]_.-]//g;72567257return$name;7258}72597260sub snapshot_name {7261my($project,$hash) =@_;72627263# path/to/project.git -> project7264# path/to/project/.git -> project7265my$name= to_utf8($project);7266$name=~ s,([^/])/*\.git$,$1,;7267$name= sanitize_for_filename(basename($name));72687269my$ver=$hash;7270if($hash=~/^[0-9a-fA-F]+$/) {7271# shorten SHA-1 hash7272my$full_hash= git_get_full_hash($project,$hash);7273if($full_hash=~/^$hash/&&length($hash) >7) {7274$ver= git_get_short_hash($project,$hash);7275}7276}elsif($hash=~m!^refs/tags/(.*)$!) {7277# tags don't need shortened SHA-1 hash7278$ver=$1;7279}else{7280# branches and other need shortened SHA-1 hash7281my$strip_refs=join'|',map{quotemeta} get_branch_refs();7282if($hash=~m!^refs/($strip_refs|remotes)/(.*)$!) {7283my$ref_dir= (defined$1) ?$1:'';7284$ver=$2;72857286$ref_dir= sanitize_for_filename($ref_dir);7287# for refs neither in heads nor remotes we want to7288# add a ref dir to archive name7289if($ref_dirne''and$ref_dirne'heads'and$ref_dirne'remotes') {7290$ver=$ref_dir.'-'.$ver;7291}7292}7293$ver.='-'. git_get_short_hash($project,$hash);7294}7295# special case of sanitization for filename - we change7296# slashes to dots instead of dashes7297# in case of hierarchical branch names7298$ver=~s!/!.!g;7299$ver=~s/[^[:alnum:]_.-]//g;73007301# name = project-version_string7302$name="$name-$ver";73037304returnwantarray? ($name,$name) :$name;7305}73067307sub exit_if_unmodified_since {7308my($latest_epoch) =@_;7309our$cgi;73107311my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7312if(defined$if_modified) {7313my$since;7314if(eval{require HTTP::Date;1; }) {7315$since= HTTP::Date::str2time($if_modified);7316}elsif(eval{require Time::ParseDate;1; }) {7317$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7318}7319if(defined$since&&$latest_epoch<=$since) {7320my%latest_date= parse_date($latest_epoch);7321print$cgi->header(7322-last_modified =>$latest_date{'rfc2822'},7323-status =>'304 Not Modified');7324goto DONE_GITWEB;7325}7326}7327}73287329sub git_snapshot {7330my$format=$input_params{'snapshot_format'};7331if(!@snapshot_fmts) {7332 die_error(403,"Snapshots not allowed");7333}7334# default to first supported snapshot format7335$format||=$snapshot_fmts[0];7336if($format!~m/^[a-z0-9]+$/) {7337 die_error(400,"Invalid snapshot format parameter");7338}elsif(!exists($known_snapshot_formats{$format})) {7339 die_error(400,"Unknown snapshot format");7340}elsif($known_snapshot_formats{$format}{'disabled'}) {7341 die_error(403,"Snapshot format not allowed");7342}elsif(!grep($_eq$format,@snapshot_fmts)) {7343 die_error(403,"Unsupported snapshot format");7344}73457346my$type= git_get_type("$hash^{}");7347if(!$type) {7348 die_error(404,'Object does not exist');7349}elsif($typeeq'blob') {7350 die_error(400,'Object is not a tree-ish');7351}73527353my($name,$prefix) = snapshot_name($project,$hash);7354my$filename="$name$known_snapshot_formats{$format}{'suffix'}";73557356my%co= parse_commit($hash);7357 exit_if_unmodified_since($co{'committer_epoch'})if%co;73587359my$cmd= quote_command(7360 git_cmd(),'archive',7361"--format=$known_snapshot_formats{$format}{'format'}",7362"--prefix=$prefix/",$hash);7363if(exists$known_snapshot_formats{$format}{'compressor'}) {7364$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});7365}73667367$filename=~s/(["\\])/\\$1/g;7368my%latest_date;7369if(%co) {7370%latest_date= parse_date($co{'committer_epoch'},$co{'committer_tz'});7371}73727373print$cgi->header(7374-type =>$known_snapshot_formats{$format}{'type'},7375-content_disposition =>'inline; filename="'.$filename.'"',7376%co? (-last_modified =>$latest_date{'rfc2822'}) : (),7377-status =>'200 OK');73787379open my$fd,"-|",$cmd7380or die_error(500,"Execute git-archive failed");7381binmode STDOUT,':raw';7382print<$fd>;7383binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi7384close$fd;7385}73867387sub git_log_generic {7388my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;73897390my$head= git_get_head_hash($project);7391if(!defined$base) {7392$base=$head;7393}7394if(!defined$page) {7395$page=0;7396}7397my$refs= git_get_references();73987399my$commit_hash=$base;7400if(defined$parent) {7401$commit_hash="$parent..$base";7402}7403my@commitlist=7404 parse_commits($commit_hash,101, (100*$page),7405defined$file_name? ($file_name,"--full-history") : ());74067407my$ftype;7408if(!defined$file_hash&&defined$file_name) {7409# some commits could have deleted file in question,7410# and not have it in tree, but one of them has to have it7411for(my$i=0;$i<@commitlist;$i++) {7412$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);7413last ifdefined$file_hash;7414}7415}7416if(defined$file_hash) {7417$ftype= git_get_type($file_hash);7418}7419if(defined$file_name&& !defined$ftype) {7420 die_error(500,"Unknown type of object");7421}7422my%co;7423if(defined$file_name) {7424%co= parse_commit($base)7425or die_error(404,"Unknown commit object");7426}742774287429my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);7430my$next_link='';7431if($#commitlist>=100) {7432$next_link=7433$cgi->a({-href => href(-replay=>1, page=>$page+1),7434-accesskey =>"n", -title =>"Alt-n"},"next");7435}7436my$patch_max= gitweb_get_feature('patches');7437if($patch_max&& !defined$file_name) {7438if($patch_max<0||@commitlist<=$patch_max) {7439$paging_nav.=" ⋅ ".7440$cgi->a({-href => href(action=>"patches", -replay=>1)},7441"patches");7442}7443}74447445 git_header_html();7446 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);7447if(defined$file_name) {7448 git_print_header_div('commit', esc_html($co{'title'}),$base);7449}else{7450 git_print_header_div('summary',$project)7451}7452 git_print_page_path($file_name,$ftype,$hash_base)7453if(defined$file_name);74547455$body_subr->(\@commitlist,0,99,$refs,$next_link,7456$file_name,$file_hash,$ftype);74577458 git_footer_html();7459}74607461sub git_log {7462 git_log_generic('log', \&git_log_body,7463$hash,$hash_parent);7464}74657466sub git_commit {7467$hash||=$hash_base||"HEAD";7468my%co= parse_commit($hash)7469or die_error(404,"Unknown commit object");74707471my$parent=$co{'parent'};7472my$parents=$co{'parents'};# listref74737474# we need to prepare $formats_nav before any parameter munging7475my$formats_nav;7476if(!defined$parent) {7477# --root commitdiff7478$formats_nav.='(initial)';7479}elsif(@$parents==1) {7480# single parent commit7481$formats_nav.=7482'(parent: '.7483$cgi->a({-href => href(action=>"commit",7484 hash=>$parent)},7485 esc_html(substr($parent,0,7))) .7486')';7487}else{7488# merge commit7489$formats_nav.=7490'(merge: '.7491join(' ',map{7492$cgi->a({-href => href(action=>"commit",7493 hash=>$_)},7494 esc_html(substr($_,0,7)));7495}@$parents) .7496')';7497}7498if(gitweb_check_feature('patches') &&@$parents<=1) {7499$formats_nav.=" | ".7500$cgi->a({-href => href(action=>"patch", -replay=>1)},7501"patch");7502}75037504if(!defined$parent) {7505$parent="--root";7506}7507my@difftree;7508open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",7509@diff_opts,7510(@$parents<=1?$parent:'-c'),7511$hash,"--"7512or die_error(500,"Open git-diff-tree failed");7513@difftree=map{chomp;$_} <$fd>;7514close$fdor die_error(404,"Reading git-diff-tree failed");75157516# non-textual hash id's can be cached7517my$expires;7518if($hash=~m/^[0-9a-fA-F]{40}$/) {7519$expires="+1d";7520}7521my$refs= git_get_references();7522my$ref= format_ref_marker($refs,$co{'id'});75237524 git_header_html(undef,$expires);7525 git_print_page_nav('commit','',7526$hash,$co{'tree'},$hash,7527$formats_nav);75287529if(defined$co{'parent'}) {7530 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);7531}else{7532 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);7533}7534print"<div class=\"title_text\">\n".7535"<table class=\"object_header\">\n";7536 git_print_authorship_rows(\%co);7537print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";7538print"<tr>".7539"<td>tree</td>".7540"<td class=\"sha1\">".7541$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),7542class=>"list"},$co{'tree'}) .7543"</td>".7544"<td class=\"link\">".7545$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},7546"tree");7547my$snapshot_links= format_snapshot_links($hash);7548if(defined$snapshot_links) {7549print" | ".$snapshot_links;7550}7551print"</td>".7552"</tr>\n";75537554foreachmy$par(@$parents) {7555print"<tr>".7556"<td>parent</td>".7557"<td class=\"sha1\">".7558$cgi->a({-href => href(action=>"commit", hash=>$par),7559class=>"list"},$par) .7560"</td>".7561"<td class=\"link\">".7562$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .7563" | ".7564$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .7565"</td>".7566"</tr>\n";7567}7568print"</table>".7569"</div>\n";75707571print"<div class=\"page_body\">\n";7572 git_print_log($co{'comment'});7573print"</div>\n";75747575 git_difftree_body(\@difftree,$hash,@$parents);75767577 git_footer_html();7578}75797580sub git_object {7581# object is defined by:7582# - hash or hash_base alone7583# - hash_base and file_name7584my$type;75857586# - hash or hash_base alone7587if($hash|| ($hash_base&& !defined$file_name)) {7588my$object_id=$hash||$hash_base;75897590open my$fd,"-|", quote_command(7591 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'7592or die_error(404,"Object does not exist");7593$type= <$fd>;7594defined$type&&chomp$type;7595close$fd7596or die_error(404,"Object does not exist");75977598# - hash_base and file_name7599}elsif($hash_base&&defined$file_name) {7600$file_name=~ s,/+$,,;76017602system(git_cmd(),"cat-file",'-e',$hash_base) ==07603or die_error(404,"Base object does not exist");76047605# here errors should not happen7606open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name7607or die_error(500,"Open git-ls-tree failed");7608my$line= <$fd>;7609close$fd;76107611#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'7612unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {7613 die_error(404,"File or directory for given base does not exist");7614}7615$type=$2;7616$hash=$3;7617}else{7618 die_error(400,"Not enough information to find object");7619}76207621print$cgi->redirect(-uri => href(action=>$type, -full=>1,7622 hash=>$hash, hash_base=>$hash_base,7623 file_name=>$file_name),7624-status =>'302 Found');7625}76267627sub git_blobdiff {7628my$format=shift||'html';7629my$diff_style=$input_params{'diff_style'} ||'inline';76307631my$fd;7632my@difftree;7633my%diffinfo;7634my$expires;76357636# preparing $fd and %diffinfo for git_patchset_body7637# new style URI7638if(defined$hash_base&&defined$hash_parent_base) {7639if(defined$file_name) {7640# read raw output7641open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7642$hash_parent_base,$hash_base,7643"--", (defined$file_parent?$file_parent: ()),$file_name7644or die_error(500,"Open git-diff-tree failed");7645@difftree=map{chomp;$_} <$fd>;7646close$fd7647or die_error(404,"Reading git-diff-tree failed");7648@difftree7649or die_error(404,"Blob diff not found");76507651}elsif(defined$hash&&7652$hash=~/[0-9a-fA-F]{40}/) {7653# try to find filename from $hash76547655# read filtered raw output7656open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7657$hash_parent_base,$hash_base,"--"7658or die_error(500,"Open git-diff-tree failed");7659@difftree=7660# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'7661# $hash == to_id7662grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}7663map{chomp;$_} <$fd>;7664close$fd7665or die_error(404,"Reading git-diff-tree failed");7666@difftree7667or die_error(404,"Blob diff not found");76687669}else{7670 die_error(400,"Missing one of the blob diff parameters");7671}76727673if(@difftree>1) {7674 die_error(400,"Ambiguous blob diff specification");7675}76767677%diffinfo= parse_difftree_raw_line($difftree[0]);7678$file_parent||=$diffinfo{'from_file'} ||$file_name;7679$file_name||=$diffinfo{'to_file'};76807681$hash_parent||=$diffinfo{'from_id'};7682$hash||=$diffinfo{'to_id'};76837684# non-textual hash id's can be cached7685if($hash_base=~m/^[0-9a-fA-F]{40}$/&&7686$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {7687$expires='+1d';7688}76897690# open patch output7691open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7692'-p', ($formateq'html'?"--full-index": ()),7693$hash_parent_base,$hash_base,7694"--", (defined$file_parent?$file_parent: ()),$file_name7695or die_error(500,"Open git-diff-tree failed");7696}76977698# old/legacy style URI -- not generated anymore since 1.4.3.7699if(!%diffinfo) {7700 die_error('404 Not Found',"Missing one of the blob diff parameters")7701}77027703# header7704if($formateq'html') {7705my$formats_nav=7706$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},7707"raw");7708$formats_nav.= diff_style_nav($diff_style);7709 git_header_html(undef,$expires);7710if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7711 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7712 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7713}else{7714print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";7715print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";7716}7717if(defined$file_name) {7718 git_print_page_path($file_name,"blob",$hash_base);7719}else{7720print"<div class=\"page_path\"></div>\n";7721}77227723}elsif($formateq'plain') {7724print$cgi->header(7725-type =>'text/plain',7726-charset =>'utf-8',7727-expires =>$expires,7728-content_disposition =>'inline; filename="'."$file_name".'.patch"');77297730print"X-Git-Url: ".$cgi->self_url() ."\n\n";77317732}else{7733 die_error(400,"Unknown blobdiff format");7734}77357736# patch7737if($formateq'html') {7738print"<div class=\"page_body\">\n";77397740 git_patchset_body($fd,$diff_style,7741[ \%diffinfo],$hash_base,$hash_parent_base);7742close$fd;77437744print"</div>\n";# class="page_body"7745 git_footer_html();77467747}else{7748while(my$line= <$fd>) {7749$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;7750$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;77517752print$line;77537754last if$line=~m!^\+\+\+!;7755}7756local$/=undef;7757print<$fd>;7758close$fd;7759}7760}77617762sub git_blobdiff_plain {7763 git_blobdiff('plain');7764}77657766# assumes that it is added as later part of already existing navigation,7767# so it returns "| foo | bar" rather than just "foo | bar"7768sub diff_style_nav {7769my($diff_style,$is_combined) =@_;7770$diff_style||='inline';77717772return""if($is_combined);77737774my@styles= (inline =>'inline','sidebyside'=>'side by side');7775my%styles=@styles;7776@styles=7777@styles[map{$_*2}0..$#styles/2];77787779returnjoin'',7780map{" | ".$_}7781map{7782$_eq$diff_style?$styles{$_} :7783$cgi->a({-href => href(-replay=>1, diff_style =>$_)},$styles{$_})7784}@styles;7785}77867787sub git_commitdiff {7788my%params=@_;7789my$format=$params{-format} ||'html';7790my$diff_style=$input_params{'diff_style'} ||'inline';77917792my($patch_max) = gitweb_get_feature('patches');7793if($formateq'patch') {7794 die_error(403,"Patch view not allowed")unless$patch_max;7795}77967797$hash||=$hash_base||"HEAD";7798my%co= parse_commit($hash)7799or die_error(404,"Unknown commit object");78007801# choose format for commitdiff for merge7802if(!defined$hash_parent&& @{$co{'parents'}} >1) {7803$hash_parent='--cc';7804}7805# we need to prepare $formats_nav before almost any parameter munging7806my$formats_nav;7807if($formateq'html') {7808$formats_nav=7809$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},7810"raw");7811if($patch_max&& @{$co{'parents'}} <=1) {7812$formats_nav.=" | ".7813$cgi->a({-href => href(action=>"patch", -replay=>1)},7814"patch");7815}7816$formats_nav.= diff_style_nav($diff_style, @{$co{'parents'}} >1);78177818if(defined$hash_parent&&7819$hash_parentne'-c'&&$hash_parentne'--cc') {7820# commitdiff with two commits given7821my$hash_parent_short=$hash_parent;7822if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {7823$hash_parent_short=substr($hash_parent,0,7);7824}7825$formats_nav.=7826' (from';7827for(my$i=0;$i< @{$co{'parents'}};$i++) {7828if($co{'parents'}[$i]eq$hash_parent) {7829$formats_nav.=' parent '. ($i+1);7830last;7831}7832}7833$formats_nav.=': '.7834$cgi->a({-href => href(-replay=>1,7835 hash=>$hash_parent, hash_base=>undef)},7836 esc_html($hash_parent_short)) .7837')';7838}elsif(!$co{'parent'}) {7839# --root commitdiff7840$formats_nav.=' (initial)';7841}elsif(scalar@{$co{'parents'}} ==1) {7842# single parent commit7843$formats_nav.=7844' (parent: '.7845$cgi->a({-href => href(-replay=>1,7846 hash=>$co{'parent'}, hash_base=>undef)},7847 esc_html(substr($co{'parent'},0,7))) .7848')';7849}else{7850# merge commit7851if($hash_parenteq'--cc') {7852$formats_nav.=' | '.7853$cgi->a({-href => href(-replay=>1,7854 hash=>$hash, hash_parent=>'-c')},7855'combined');7856}else{# $hash_parent eq '-c'7857$formats_nav.=' | '.7858$cgi->a({-href => href(-replay=>1,7859 hash=>$hash, hash_parent=>'--cc')},7860'compact');7861}7862$formats_nav.=7863' (merge: '.7864join(' ',map{7865$cgi->a({-href => href(-replay=>1,7866 hash=>$_, hash_base=>undef)},7867 esc_html(substr($_,0,7)));7868} @{$co{'parents'}} ) .7869')';7870}7871}78727873my$hash_parent_param=$hash_parent;7874if(!defined$hash_parent_param) {7875# --cc for multiple parents, --root for parentless7876$hash_parent_param=7877@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';7878}78797880# read commitdiff7881my$fd;7882my@difftree;7883if($formateq'html') {7884open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7885"--no-commit-id","--patch-with-raw","--full-index",7886$hash_parent_param,$hash,"--"7887or die_error(500,"Open git-diff-tree failed");78887889while(my$line= <$fd>) {7890chomp$line;7891# empty line ends raw part of diff-tree output7892last unless$line;7893push@difftree,scalar parse_difftree_raw_line($line);7894}78957896}elsif($formateq'plain') {7897open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7898'-p',$hash_parent_param,$hash,"--"7899or die_error(500,"Open git-diff-tree failed");7900}elsif($formateq'patch') {7901# For commit ranges, we limit the output to the number of7902# patches specified in the 'patches' feature.7903# For single commits, we limit the output to a single patch,7904# diverging from the git-format-patch default.7905my@commit_spec= ();7906if($hash_parent) {7907if($patch_max>0) {7908push@commit_spec,"-$patch_max";7909}7910push@commit_spec,'-n',"$hash_parent..$hash";7911}else{7912if($params{-single}) {7913push@commit_spec,'-1';7914}else{7915if($patch_max>0) {7916push@commit_spec,"-$patch_max";7917}7918push@commit_spec,"-n";7919}7920push@commit_spec,'--root',$hash;7921}7922open$fd,"-|", git_cmd(),"format-patch",@diff_opts,7923'--encoding=utf8','--stdout',@commit_spec7924or die_error(500,"Open git-format-patch failed");7925}else{7926 die_error(400,"Unknown commitdiff format");7927}79287929# non-textual hash id's can be cached7930my$expires;7931if($hash=~m/^[0-9a-fA-F]{40}$/) {7932$expires="+1d";7933}79347935# write commit message7936if($formateq'html') {7937my$refs= git_get_references();7938my$ref= format_ref_marker($refs,$co{'id'});79397940 git_header_html(undef,$expires);7941 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);7942 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);7943print"<div class=\"title_text\">\n".7944"<table class=\"object_header\">\n";7945 git_print_authorship_rows(\%co);7946print"</table>".7947"</div>\n";7948print"<div class=\"page_body\">\n";7949if(@{$co{'comment'}} >1) {7950print"<div class=\"log\">\n";7951 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);7952print"</div>\n";# class="log"7953}79547955}elsif($formateq'plain') {7956my$refs= git_get_references("tags");7957my$tagname= git_get_rev_name_tags($hash);7958my$filename= basename($project) ."-$hash.patch";79597960print$cgi->header(7961-type =>'text/plain',7962-charset =>'utf-8',7963-expires =>$expires,7964-content_disposition =>'inline; filename="'."$filename".'"');7965my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});7966print"From: ". to_utf8($co{'author'}) ."\n";7967print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";7968print"Subject: ". to_utf8($co{'title'}) ."\n";79697970print"X-Git-Tag:$tagname\n"if$tagname;7971print"X-Git-Url: ".$cgi->self_url() ."\n\n";79727973foreachmy$line(@{$co{'comment'}}) {7974print to_utf8($line) ."\n";7975}7976print"---\n\n";7977}elsif($formateq'patch') {7978my$filename= basename($project) ."-$hash.patch";79797980print$cgi->header(7981-type =>'text/plain',7982-charset =>'utf-8',7983-expires =>$expires,7984-content_disposition =>'inline; filename="'."$filename".'"');7985}79867987# write patch7988if($formateq'html') {7989my$use_parents= !defined$hash_parent||7990$hash_parenteq'-c'||$hash_parenteq'--cc';7991 git_difftree_body(\@difftree,$hash,7992$use_parents? @{$co{'parents'}} :$hash_parent);7993print"<br/>\n";79947995 git_patchset_body($fd,$diff_style,7996 \@difftree,$hash,7997$use_parents? @{$co{'parents'}} :$hash_parent);7998close$fd;7999print"</div>\n";# class="page_body"8000 git_footer_html();80018002}elsif($formateq'plain') {8003local$/=undef;8004print<$fd>;8005close$fd8006or print"Reading git-diff-tree failed\n";8007}elsif($formateq'patch') {8008local$/=undef;8009print<$fd>;8010close$fd8011or print"Reading git-format-patch failed\n";8012}8013}80148015sub git_commitdiff_plain {8016 git_commitdiff(-format =>'plain');8017}80188019# format-patch-style patches8020sub git_patch {8021 git_commitdiff(-format =>'patch', -single =>1);8022}80238024sub git_patches {8025 git_commitdiff(-format =>'patch');8026}80278028sub git_history {8029 git_log_generic('history', \&git_history_body,8030$hash_base,$hash_parent_base,8031$file_name,$hash);8032}80338034sub git_search {8035$searchtype||='commit';80368037# check if appropriate features are enabled8038 gitweb_check_feature('search')8039or die_error(403,"Search is disabled");8040if($searchtypeeq'pickaxe') {8041# pickaxe may take all resources of your box and run for several minutes8042# with every query - so decide by yourself how public you make this feature8043 gitweb_check_feature('pickaxe')8044or die_error(403,"Pickaxe search is disabled");8045}8046if($searchtypeeq'grep') {8047# grep search might be potentially CPU-intensive, too8048 gitweb_check_feature('grep')8049or die_error(403,"Grep search is disabled");8050}80518052if(!defined$searchtext) {8053 die_error(400,"Text field is empty");8054}8055if(!defined$hash) {8056$hash= git_get_head_hash($project);8057}8058my%co= parse_commit($hash);8059if(!%co) {8060 die_error(404,"Unknown commit object");8061}8062if(!defined$page) {8063$page=0;8064}80658066if($searchtypeeq'commit'||8067$searchtypeeq'author'||8068$searchtypeeq'committer') {8069 git_search_message(%co);8070}elsif($searchtypeeq'pickaxe') {8071 git_search_changes(%co);8072}elsif($searchtypeeq'grep') {8073 git_search_files(%co);8074}else{8075 die_error(400,"Unknown search type");8076}8077}80788079sub git_search_help {8080 git_header_html();8081 git_print_page_nav('','',$hash,$hash,$hash);8082print<<EOT;8083<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without8084regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,8085the pattern entered is recognized as the POSIX extended8086<a href="https://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case8087insensitive).</p>8088<dl>8089<dt><b>commit</b></dt>8090<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>8091EOT8092my$have_grep= gitweb_check_feature('grep');8093if($have_grep) {8094print<<EOT;8095<dt><b>grep</b></dt>8096<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing8097 a different one) are searched for the given pattern. On large trees, this search can take8098a while and put some strain on the server, so please use it with some consideration. Note that8099due to git-grep peculiarity, currently if regexp mode is turned off, the matches are8100case-sensitive.</dd>8101EOT8102}8103print<<EOT;8104<dt><b>author</b></dt>8105<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>8106<dt><b>committer</b></dt>8107<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>8108EOT8109my$have_pickaxe= gitweb_check_feature('pickaxe');8110if($have_pickaxe) {8111print<<EOT;8112<dt><b>pickaxe</b></dt>8113<dd>All commits that caused the string to appear or disappear from any file (changes that8114added, removed or "modified" the string) will be listed. This search can take a while and8115takes a lot of strain on the server, so please use it wisely. Note that since you may be8116interested even in changes just changing the case as well, this search is case sensitive.</dd>8117EOT8118}8119print"</dl>\n";8120 git_footer_html();8121}81228123sub git_shortlog {8124 git_log_generic('shortlog', \&git_shortlog_body,8125$hash,$hash_parent);8126}81278128## ......................................................................8129## feeds (RSS, Atom; OPML)81308131sub git_feed {8132my$format=shift||'atom';8133my$have_blame= gitweb_check_feature('blame');81348135# Atom: http://www.atomenabled.org/developers/syndication/8136# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ8137if($formatne'rss'&&$formatne'atom') {8138 die_error(400,"Unknown web feed format");8139}81408141# log/feed of current (HEAD) branch, log of given branch, history of file/directory8142my$head=$hash||'HEAD';8143my@commitlist= parse_commits($head,150,0,$file_name);81448145my%latest_commit;8146my%latest_date;8147my$content_type="application/$format+xml";8148if(defined$cgi->http('HTTP_ACCEPT') &&8149$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {8150# browser (feed reader) prefers text/xml8151$content_type='text/xml';8152}8153if(defined($commitlist[0])) {8154%latest_commit= %{$commitlist[0]};8155my$latest_epoch=$latest_commit{'committer_epoch'};8156 exit_if_unmodified_since($latest_epoch);8157%latest_date= parse_date($latest_epoch,$latest_commit{'committer_tz'});8158}8159print$cgi->header(8160-type =>$content_type,8161-charset =>'utf-8',8162%latest_date? (-last_modified =>$latest_date{'rfc2822'}) : (),8163-status =>'200 OK');81648165# Optimization: skip generating the body if client asks only8166# for Last-Modified date.8167return if($cgi->request_method()eq'HEAD');81688169# header variables8170my$title="$site_name-$project/$action";8171my$feed_type='log';8172if(defined$hash) {8173$title.=" - '$hash'";8174$feed_type='branch log';8175if(defined$file_name) {8176$title.=" ::$file_name";8177$feed_type='history';8178}8179}elsif(defined$file_name) {8180$title.=" -$file_name";8181$feed_type='history';8182}8183$title.="$feed_type";8184$title= esc_html($title);8185my$descr= git_get_project_description($project);8186if(defined$descr) {8187$descr= esc_html($descr);8188}else{8189$descr="$project".8190($formateq'rss'?'RSS':'Atom') .8191" feed";8192}8193my$owner= git_get_project_owner($project);8194$owner= esc_html($owner);81958196#header8197my$alt_url;8198if(defined$file_name) {8199$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);8200}elsif(defined$hash) {8201$alt_url= href(-full=>1, action=>"log", hash=>$hash);8202}else{8203$alt_url= href(-full=>1, action=>"summary");8204}8205print qq!<?xml version="1.0" encoding="utf-8"?>\n!;8206if($formateq'rss') {8207print<<XML;8208<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">8209<channel>8210XML8211print"<title>$title</title>\n".8212"<link>$alt_url</link>\n".8213"<description>$descr</description>\n".8214"<language>en</language>\n".8215# project owner is responsible for 'editorial' content8216"<managingEditor>$owner</managingEditor>\n";8217if(defined$logo||defined$favicon) {8218# prefer the logo to the favicon, since RSS8219# doesn't allow both8220my$img= esc_url($logo||$favicon);8221print"<image>\n".8222"<url>$img</url>\n".8223"<title>$title</title>\n".8224"<link>$alt_url</link>\n".8225"</image>\n";8226}8227if(%latest_date) {8228print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";8229print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";8230}8231print"<generator>gitweb v.$version/$git_version</generator>\n";8232}elsif($formateq'atom') {8233print<<XML;8234<feed xmlns="http://www.w3.org/2005/Atom">8235XML8236print"<title>$title</title>\n".8237"<subtitle>$descr</subtitle>\n".8238'<link rel="alternate" type="text/html" href="'.8239$alt_url.'" />'."\n".8240'<link rel="self" type="'.$content_type.'" href="'.8241$cgi->self_url() .'" />'."\n".8242"<id>". href(-full=>1) ."</id>\n".8243# use project owner for feed author8244"<author><name>$owner</name></author>\n";8245if(defined$favicon) {8246print"<icon>". esc_url($favicon) ."</icon>\n";8247}8248if(defined$logo) {8249# not twice as wide as tall: 72 x 27 pixels8250print"<logo>". esc_url($logo) ."</logo>\n";8251}8252if(!%latest_date) {8253# dummy date to keep the feed valid until commits trickle in:8254print"<updated>1970-01-01T00:00:00Z</updated>\n";8255}else{8256print"<updated>$latest_date{'iso-8601'}</updated>\n";8257}8258print"<generator version='$version/$git_version'>gitweb</generator>\n";8259}82608261# contents8262for(my$i=0;$i<=$#commitlist;$i++) {8263my%co= %{$commitlist[$i]};8264my$commit=$co{'id'};8265# we read 150, we always show 30 and the ones more recent than 48 hours8266if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {8267last;8268}8269my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});82708271# get list of changed files8272open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,8273$co{'parent'} ||"--root",8274$co{'id'},"--", (defined$file_name?$file_name: ())8275ornext;8276my@difftree=map{chomp;$_} <$fd>;8277close$fd8278ornext;82798280# print element (entry, item)8281my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);8282if($formateq'rss') {8283print"<item>\n".8284"<title>". esc_html($co{'title'}) ."</title>\n".8285"<author>". esc_html($co{'author'}) ."</author>\n".8286"<pubDate>$cd{'rfc2822'}</pubDate>\n".8287"<guid isPermaLink=\"true\">$co_url</guid>\n".8288"<link>$co_url</link>\n".8289"<description>". esc_html($co{'title'}) ."</description>\n".8290"<content:encoded>".8291"<![CDATA[\n";8292}elsif($formateq'atom') {8293print"<entry>\n".8294"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".8295"<updated>$cd{'iso-8601'}</updated>\n".8296"<author>\n".8297" <name>". esc_html($co{'author_name'}) ."</name>\n";8298if($co{'author_email'}) {8299print" <email>". esc_html($co{'author_email'}) ."</email>\n";8300}8301print"</author>\n".8302# use committer for contributor8303"<contributor>\n".8304" <name>". esc_html($co{'committer_name'}) ."</name>\n";8305if($co{'committer_email'}) {8306print" <email>". esc_html($co{'committer_email'}) ."</email>\n";8307}8308print"</contributor>\n".8309"<published>$cd{'iso-8601'}</published>\n".8310"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".8311"<id>$co_url</id>\n".8312"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".8313"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";8314}8315my$comment=$co{'comment'};8316print"<pre>\n";8317foreachmy$line(@$comment) {8318$line= esc_html($line);8319print"$line\n";8320}8321print"</pre><ul>\n";8322foreachmy$difftree_line(@difftree) {8323my%difftree= parse_difftree_raw_line($difftree_line);8324next if!$difftree{'from_id'};83258326my$file=$difftree{'file'} ||$difftree{'to_file'};83278328print"<li>".8329"[".8330$cgi->a({-href => href(-full=>1, action=>"blobdiff",8331 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},8332 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},8333 file_name=>$file, file_parent=>$difftree{'from_file'}),8334-title =>"diff"},'D');8335if($have_blame) {8336print$cgi->a({-href => href(-full=>1, action=>"blame",8337 file_name=>$file, hash_base=>$commit),8338-title =>"blame"},'B');8339}8340# if this is not a feed of a file history8341if(!defined$file_name||$file_namene$file) {8342print$cgi->a({-href => href(-full=>1, action=>"history",8343 file_name=>$file, hash=>$commit),8344-title =>"history"},'H');8345}8346$file= esc_path($file);8347print"] ".8348"$file</li>\n";8349}8350if($formateq'rss') {8351print"</ul>]]>\n".8352"</content:encoded>\n".8353"</item>\n";8354}elsif($formateq'atom') {8355print"</ul>\n</div>\n".8356"</content>\n".8357"</entry>\n";8358}8359}83608361# end of feed8362if($formateq'rss') {8363print"</channel>\n</rss>\n";8364}elsif($formateq'atom') {8365print"</feed>\n";8366}8367}83688369sub git_rss {8370 git_feed('rss');8371}83728373sub git_atom {8374 git_feed('atom');8375}83768377sub git_opml {8378my@list= git_get_projects_list($project_filter,$strict_export);8379if(!@list) {8380 die_error(404,"No projects found");8381}83828383print$cgi->header(8384-type =>'text/xml',8385-charset =>'utf-8',8386-content_disposition =>'inline; filename="opml.xml"');83878388my$title= esc_html($site_name);8389my$filter=" within subdirectory ";8390if(defined$project_filter) {8391$filter.= esc_html($project_filter);8392}else{8393$filter="";8394}8395print<<XML;8396<?xml version="1.0" encoding="utf-8"?>8397<opml version="1.0">8398<head>8399 <title>$titleOPML Export$filter</title>8400</head>8401<body>8402<outline text="git RSS feeds">8403XML84048405foreachmy$pr(@list) {8406my%proj=%$pr;8407my$head= git_get_head_hash($proj{'path'});8408if(!defined$head) {8409next;8410}8411$git_dir="$projectroot/$proj{'path'}";8412my%co= parse_commit($head);8413if(!%co) {8414next;8415}84168417my$path= esc_html(chop_str($proj{'path'},25,5));8418my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);8419my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);8420print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";8421}8422print<<XML;8423</outline>8424</body>8425</opml>8426XML8427}