1#!/usr/bin/perl 2 3# gitweb - simple web interface to track changes in git repositories 4# 5# (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org> 6# (C) 2005, Christian Gierke 7# 8# This program is licensed under the GPLv2 9 10use5.008; 11use strict; 12use warnings; 13use CGI qw(:standard :escapeHTML -nosticky); 14use CGI::Util qw(unescape); 15use CGI::Carp qw(fatalsToBrowser set_message); 16use Encode; 17use Fcntl ':mode'; 18use File::Find qw(); 19use File::Basename qw(basename); 20use Time::HiRes qw(gettimeofday tv_interval); 21binmode STDOUT,':utf8'; 22 23our$t0= [ gettimeofday() ]; 24our$number_of_git_cmds=0; 25 26BEGIN{ 27 CGI->compile()if$ENV{'MOD_PERL'}; 28} 29 30our$version="++GIT_VERSION++"; 31 32our($my_url,$my_uri,$base_url,$path_info,$home_link); 33sub evaluate_uri { 34our$cgi; 35 36our$my_url=$cgi->url(); 37our$my_uri=$cgi->url(-absolute =>1); 38 39# Base URL for relative URLs in gitweb ($logo, $favicon, ...), 40# needed and used only for URLs with nonempty PATH_INFO 41our$base_url=$my_url; 42 43# When the script is used as DirectoryIndex, the URL does not contain the name 44# of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we 45# have to do it ourselves. We make $path_info global because it's also used 46# later on. 47# 48# Another issue with the script being the DirectoryIndex is that the resulting 49# $my_url data is not the full script URL: this is good, because we want 50# generated links to keep implying the script name if it wasn't explicitly 51# indicated in the URL we're handling, but it means that $my_url cannot be used 52# as base URL. 53# Therefore, if we needed to strip PATH_INFO, then we know that we have 54# to build the base URL ourselves: 55our$path_info= decode_utf8($ENV{"PATH_INFO"}); 56if($path_info) { 57# $path_info has already been URL-decoded by the web server, but 58# $my_url and $my_uri have not. URL-decode them so we can properly 59# strip $path_info. 60$my_url= unescape($my_url); 61$my_uri= unescape($my_uri); 62if($my_url=~ s,\Q$path_info\E$,, && 63$my_uri=~ s,\Q$path_info\E$,, && 64defined$ENV{'SCRIPT_NAME'}) { 65$base_url=$cgi->url(-base =>1) .$ENV{'SCRIPT_NAME'}; 66} 67} 68 69# target of the home link on top of all pages 70our$home_link=$my_uri||"/"; 71} 72 73# core git executable to use 74# this can just be "git" if your webserver has a sensible PATH 75our$GIT="++GIT_BINDIR++/git"; 76 77# absolute fs-path which will be prepended to the project path 78#our $projectroot = "/pub/scm"; 79our$projectroot="++GITWEB_PROJECTROOT++"; 80 81# fs traversing limit for getting project list 82# the number is relative to the projectroot 83our$project_maxdepth="++GITWEB_PROJECT_MAXDEPTH++"; 84 85# string of the home link on top of all pages 86our$home_link_str="++GITWEB_HOME_LINK_STR++"; 87 88# extra breadcrumbs preceding the home link 89our@extra_breadcrumbs= (); 90 91# name of your site or organization to appear in page titles 92# replace this with something more descriptive for clearer bookmarks 93our$site_name="++GITWEB_SITENAME++" 94|| ($ENV{'SERVER_NAME'} ||"Untitled") ." Git"; 95 96# html snippet to include in the <head> section of each page 97our$site_html_head_string="++GITWEB_SITE_HTML_HEAD_STRING++"; 98# filename of html text to include at top of each page 99our$site_header="++GITWEB_SITE_HEADER++"; 100# html text to include at home page 101our$home_text="++GITWEB_HOMETEXT++"; 102# filename of html text to include at bottom of each page 103our$site_footer="++GITWEB_SITE_FOOTER++"; 104 105# URI of stylesheets 106our@stylesheets= ("++GITWEB_CSS++"); 107# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG. 108our$stylesheet=undef; 109# URI of GIT logo (72x27 size) 110our$logo="++GITWEB_LOGO++"; 111# URI of GIT favicon, assumed to be image/png type 112our$favicon="++GITWEB_FAVICON++"; 113# URI of gitweb.js (JavaScript code for gitweb) 114our$javascript="++GITWEB_JS++"; 115 116# URI and label (title) of GIT logo link 117#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/"; 118#our $logo_label = "git documentation"; 119our$logo_url="http://git-scm.com/"; 120our$logo_label="git homepage"; 121 122# source of projects list 123our$projects_list="++GITWEB_LIST++"; 124 125# the width (in characters) of the projects list "Description" column 126our$projects_list_description_width=25; 127 128# group projects by category on the projects list 129# (enabled if this variable evaluates to true) 130our$projects_list_group_categories=0; 131 132# default category if none specified 133# (leave the empty string for no category) 134our$project_list_default_category=""; 135 136# default order of projects list 137# valid values are none, project, descr, owner, and age 138our$default_projects_order="project"; 139 140# show repository only if this file exists 141# (only effective if this variable evaluates to true) 142our$export_ok="++GITWEB_EXPORT_OK++"; 143 144# don't generate age column on the projects list page 145our$omit_age_column=0; 146 147# don't generate information about owners of repositories 148our$omit_owner=0; 149 150# show repository only if this subroutine returns true 151# when given the path to the project, for example: 152# sub { return -e "$_[0]/git-daemon-export-ok"; } 153our$export_auth_hook=undef; 154 155# only allow viewing of repositories also shown on the overview page 156our$strict_export="++GITWEB_STRICT_EXPORT++"; 157 158# list of git base URLs used for URL to where fetch project from, 159# i.e. full URL is "$git_base_url/$project" 160our@git_base_url_list=grep{$_ne''} ("++GITWEB_BASE_URL++"); 161 162# default blob_plain mimetype and default charset for text/plain blob 163our$default_blob_plain_mimetype='text/plain'; 164our$default_text_plain_charset=undef; 165 166# file to use for guessing MIME types before trying /etc/mime.types 167# (relative to the current git repository) 168our$mimetypes_file=undef; 169 170# assume this charset if line contains non-UTF-8 characters; 171# it should be valid encoding (see Encoding::Supported(3pm) for list), 172# for which encoding all byte sequences are valid, for example 173# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it 174# could be even 'utf-8' for the old behavior) 175our$fallback_encoding='latin1'; 176 177# rename detection options for git-diff and git-diff-tree 178# - default is '-M', with the cost proportional to 179# (number of removed files) * (number of new files). 180# - more costly is '-C' (which implies '-M'), with the cost proportional to 181# (number of changed files + number of removed files) * (number of new files) 182# - even more costly is '-C', '--find-copies-harder' with cost 183# (number of files in the original tree) * (number of new files) 184# - one might want to include '-B' option, e.g. '-B', '-M' 185our@diff_opts= ('-M');# taken from git_commit 186 187# Disables features that would allow repository owners to inject script into 188# the gitweb domain. 189our$prevent_xss=0; 190 191# Path to the highlight executable to use (must be the one from 192# http://www.andre-simon.de due to assumptions about parameters and output). 193# Useful if highlight is not installed on your webserver's PATH. 194# [Default: highlight] 195our$highlight_bin="++HIGHLIGHT_BIN++"; 196 197# information about snapshot formats that gitweb is capable of serving 198our%known_snapshot_formats= ( 199# name => { 200# 'display' => display name, 201# 'type' => mime type, 202# 'suffix' => filename suffix, 203# 'format' => --format for git-archive, 204# 'compressor' => [compressor command and arguments] 205# (array reference, optional) 206# 'disabled' => boolean (optional)} 207# 208'tgz'=> { 209'display'=>'tar.gz', 210'type'=>'application/x-gzip', 211'suffix'=>'.tar.gz', 212'format'=>'tar', 213'compressor'=> ['gzip','-n']}, 214 215'tbz2'=> { 216'display'=>'tar.bz2', 217'type'=>'application/x-bzip2', 218'suffix'=>'.tar.bz2', 219'format'=>'tar', 220'compressor'=> ['bzip2']}, 221 222'txz'=> { 223'display'=>'tar.xz', 224'type'=>'application/x-xz', 225'suffix'=>'.tar.xz', 226'format'=>'tar', 227'compressor'=> ['xz'], 228'disabled'=>1}, 229 230'zip'=> { 231'display'=>'zip', 232'type'=>'application/x-zip', 233'suffix'=>'.zip', 234'format'=>'zip'}, 235); 236 237# Aliases so we understand old gitweb.snapshot values in repository 238# configuration. 239our%known_snapshot_format_aliases= ( 240'gzip'=>'tgz', 241'bzip2'=>'tbz2', 242'xz'=>'txz', 243 244# backward compatibility: legacy gitweb config support 245'x-gzip'=>undef,'gz'=>undef, 246'x-bzip2'=>undef,'bz2'=>undef, 247'x-zip'=>undef,''=>undef, 248); 249 250# Pixel sizes for icons and avatars. If the default font sizes or lineheights 251# are changed, it may be appropriate to change these values too via 252# $GITWEB_CONFIG. 253our%avatar_size= ( 254'default'=>16, 255'double'=>32 256); 257 258# Used to set the maximum load that we will still respond to gitweb queries. 259# If server load exceed this value then return "503 server busy" error. 260# If gitweb cannot determined server load, it is taken to be 0. 261# Leave it undefined (or set to 'undef') to turn off load checking. 262our$maxload=300; 263 264# configuration for 'highlight' (http://www.andre-simon.de/) 265# match by basename 266our%highlight_basename= ( 267#'Program' => 'py', 268#'Library' => 'py', 269'SConstruct'=>'py',# SCons equivalent of Makefile 270'Makefile'=>'make', 271); 272# match by extension 273our%highlight_ext= ( 274# main extensions, defining name of syntax; 275# see files in /usr/share/highlight/langDefs/ directory 276(map{$_=>$_}qw(py rb java css js tex bib xml awk bat ini spec tcl sql)), 277# alternate extensions, see /etc/highlight/filetypes.conf 278(map{$_=>'c'}qw(c h)), 279(map{$_=>'sh'}qw(sh bash zsh ksh)), 280(map{$_=>'cpp'}qw(cpp cxx c++ cc)), 281(map{$_=>'php'}qw(php php3 php4 php5 phps)), 282(map{$_=>'pl'}qw(pl perl pm)),# perhaps also 'cgi' 283(map{$_=>'make'}qw(make mak mk)), 284(map{$_=>'xml'}qw(xml xhtml html htm)), 285); 286 287# You define site-wide feature defaults here; override them with 288# $GITWEB_CONFIG as necessary. 289our%feature= ( 290# feature => { 291# 'sub' => feature-sub (subroutine), 292# 'override' => allow-override (boolean), 293# 'default' => [ default options...] (array reference)} 294# 295# if feature is overridable (it means that allow-override has true value), 296# then feature-sub will be called with default options as parameters; 297# return value of feature-sub indicates if to enable specified feature 298# 299# if there is no 'sub' key (no feature-sub), then feature cannot be 300# overridden 301# 302# use gitweb_get_feature(<feature>) to retrieve the <feature> value 303# (an array) or gitweb_check_feature(<feature>) to check if <feature> 304# is enabled 305 306# Enable the 'blame' blob view, showing the last commit that modified 307# each line in the file. This can be very CPU-intensive. 308 309# To enable system wide have in $GITWEB_CONFIG 310# $feature{'blame'}{'default'} = [1]; 311# To have project specific config enable override in $GITWEB_CONFIG 312# $feature{'blame'}{'override'} = 1; 313# and in project config gitweb.blame = 0|1; 314'blame'=> { 315'sub'=>sub{ feature_bool('blame',@_) }, 316'override'=>0, 317'default'=> [0]}, 318 319# Enable the 'snapshot' link, providing a compressed archive of any 320# tree. This can potentially generate high traffic if you have large 321# project. 322 323# Value is a list of formats defined in %known_snapshot_formats that 324# you wish to offer. 325# To disable system wide have in $GITWEB_CONFIG 326# $feature{'snapshot'}{'default'} = []; 327# To have project specific config enable override in $GITWEB_CONFIG 328# $feature{'snapshot'}{'override'} = 1; 329# and in project config, a comma-separated list of formats or "none" 330# to disable. Example: gitweb.snapshot = tbz2,zip; 331'snapshot'=> { 332'sub'=> \&feature_snapshot, 333'override'=>0, 334'default'=> ['tgz']}, 335 336# Enable text search, which will list the commits which match author, 337# committer or commit text to a given string. Enabled by default. 338# Project specific override is not supported. 339# 340# Note that this controls all search features, which means that if 341# it is disabled, then 'grep' and 'pickaxe' search would also be 342# disabled. 343'search'=> { 344'override'=>0, 345'default'=> [1]}, 346 347# Enable grep search, which will list the files in currently selected 348# tree containing the given string. Enabled by default. This can be 349# potentially CPU-intensive, of course. 350# Note that you need to have 'search' feature enabled too. 351 352# To enable system wide have in $GITWEB_CONFIG 353# $feature{'grep'}{'default'} = [1]; 354# To have project specific config enable override in $GITWEB_CONFIG 355# $feature{'grep'}{'override'} = 1; 356# and in project config gitweb.grep = 0|1; 357'grep'=> { 358'sub'=>sub{ feature_bool('grep',@_) }, 359'override'=>0, 360'default'=> [1]}, 361 362# Enable the pickaxe search, which will list the commits that modified 363# a given string in a file. This can be practical and quite faster 364# alternative to 'blame', but still potentially CPU-intensive. 365# Note that you need to have 'search' feature enabled too. 366 367# To enable system wide have in $GITWEB_CONFIG 368# $feature{'pickaxe'}{'default'} = [1]; 369# To have project specific config enable override in $GITWEB_CONFIG 370# $feature{'pickaxe'}{'override'} = 1; 371# and in project config gitweb.pickaxe = 0|1; 372'pickaxe'=> { 373'sub'=>sub{ feature_bool('pickaxe',@_) }, 374'override'=>0, 375'default'=> [1]}, 376 377# Enable showing size of blobs in a 'tree' view, in a separate 378# column, similar to what 'ls -l' does. This cost a bit of IO. 379 380# To disable system wide have in $GITWEB_CONFIG 381# $feature{'show-sizes'}{'default'} = [0]; 382# To have project specific config enable override in $GITWEB_CONFIG 383# $feature{'show-sizes'}{'override'} = 1; 384# and in project config gitweb.showsizes = 0|1; 385'show-sizes'=> { 386'sub'=>sub{ feature_bool('showsizes',@_) }, 387'override'=>0, 388'default'=> [1]}, 389 390# Make gitweb use an alternative format of the URLs which can be 391# more readable and natural-looking: project name is embedded 392# directly in the path and the query string contains other 393# auxiliary information. All gitweb installations recognize 394# URL in either format; this configures in which formats gitweb 395# generates links. 396 397# To enable system wide have in $GITWEB_CONFIG 398# $feature{'pathinfo'}{'default'} = [1]; 399# Project specific override is not supported. 400 401# Note that you will need to change the default location of CSS, 402# favicon, logo and possibly other files to an absolute URL. Also, 403# if gitweb.cgi serves as your indexfile, you will need to force 404# $my_uri to contain the script name in your $GITWEB_CONFIG. 405'pathinfo'=> { 406'override'=>0, 407'default'=> [0]}, 408 409# Make gitweb consider projects in project root subdirectories 410# to be forks of existing projects. Given project $projname.git, 411# projects matching $projname/*.git will not be shown in the main 412# projects list, instead a '+' mark will be added to $projname 413# there and a 'forks' view will be enabled for the project, listing 414# all the forks. If project list is taken from a file, forks have 415# to be listed after the main project. 416 417# To enable system wide have in $GITWEB_CONFIG 418# $feature{'forks'}{'default'} = [1]; 419# Project specific override is not supported. 420'forks'=> { 421'override'=>0, 422'default'=> [0]}, 423 424# Insert custom links to the action bar of all project pages. 425# This enables you mainly to link to third-party scripts integrating 426# into gitweb; e.g. git-browser for graphical history representation 427# or custom web-based repository administration interface. 428 429# The 'default' value consists of a list of triplets in the form 430# (label, link, position) where position is the label after which 431# to insert the link and link is a format string where %n expands 432# to the project name, %f to the project path within the filesystem, 433# %h to the current hash (h gitweb parameter) and %b to the current 434# hash base (hb gitweb parameter); %% expands to %. 435 436# To enable system wide have in $GITWEB_CONFIG e.g. 437# $feature{'actions'}{'default'} = [('graphiclog', 438# '/git-browser/by-commit.html?r=%n', 'summary')]; 439# Project specific override is not supported. 440'actions'=> { 441'override'=>0, 442'default'=> []}, 443 444# Allow gitweb scan project content tags of project repository, 445# and display the popular Web 2.0-ish "tag cloud" near the projects 446# list. Note that this is something COMPLETELY different from the 447# normal Git tags. 448 449# gitweb by itself can show existing tags, but it does not handle 450# tagging itself; you need to do it externally, outside gitweb. 451# The format is described in git_get_project_ctags() subroutine. 452# You may want to install the HTML::TagCloud Perl module to get 453# a pretty tag cloud instead of just a list of tags. 454 455# To enable system wide have in $GITWEB_CONFIG 456# $feature{'ctags'}{'default'} = [1]; 457# Project specific override is not supported. 458 459# In the future whether ctags editing is enabled might depend 460# on the value, but using 1 should always mean no editing of ctags. 461'ctags'=> { 462'override'=>0, 463'default'=> [0]}, 464 465# The maximum number of patches in a patchset generated in patch 466# view. Set this to 0 or undef to disable patch view, or to a 467# negative number to remove any limit. 468 469# To disable system wide have in $GITWEB_CONFIG 470# $feature{'patches'}{'default'} = [0]; 471# To have project specific config enable override in $GITWEB_CONFIG 472# $feature{'patches'}{'override'} = 1; 473# and in project config gitweb.patches = 0|n; 474# where n is the maximum number of patches allowed in a patchset. 475'patches'=> { 476'sub'=> \&feature_patches, 477'override'=>0, 478'default'=> [16]}, 479 480# Avatar support. When this feature is enabled, views such as 481# shortlog or commit will display an avatar associated with 482# the email of the committer(s) and/or author(s). 483 484# Currently available providers are gravatar and picon. 485# If an unknown provider is specified, the feature is disabled. 486 487# Gravatar depends on Digest::MD5. 488# Picon currently relies on the indiana.edu database. 489 490# To enable system wide have in $GITWEB_CONFIG 491# $feature{'avatar'}{'default'} = ['<provider>']; 492# where <provider> is either gravatar or picon. 493# To have project specific config enable override in $GITWEB_CONFIG 494# $feature{'avatar'}{'override'} = 1; 495# and in project config gitweb.avatar = <provider>; 496'avatar'=> { 497'sub'=> \&feature_avatar, 498'override'=>0, 499'default'=> ['']}, 500 501# Enable displaying how much time and how many git commands 502# it took to generate and display page. Disabled by default. 503# Project specific override is not supported. 504'timed'=> { 505'override'=>0, 506'default'=> [0]}, 507 508# Enable turning some links into links to actions which require 509# JavaScript to run (like 'blame_incremental'). Not enabled by 510# default. Project specific override is currently not supported. 511'javascript-actions'=> { 512'override'=>0, 513'default'=> [0]}, 514 515# Enable and configure ability to change common timezone for dates 516# in gitweb output via JavaScript. Enabled by default. 517# Project specific override is not supported. 518'javascript-timezone'=> { 519'override'=>0, 520'default'=> [ 521'local',# default timezone: 'utc', 'local', or '(-|+)HHMM' format, 522# or undef to turn off this feature 523'gitweb_tz',# name of cookie where to store selected timezone 524'datetime',# CSS class used to mark up dates for manipulation 525]}, 526 527# Syntax highlighting support. This is based on Daniel Svensson's 528# and Sham Chukoury's work in gitweb-xmms2.git. 529# It requires the 'highlight' program present in $PATH, 530# and therefore is disabled by default. 531 532# To enable system wide have in $GITWEB_CONFIG 533# $feature{'highlight'}{'default'} = [1]; 534 535'highlight'=> { 536'sub'=>sub{ feature_bool('highlight',@_) }, 537'override'=>0, 538'default'=> [0]}, 539 540# Enable displaying of remote heads in the heads list 541 542# To enable system wide have in $GITWEB_CONFIG 543# $feature{'remote_heads'}{'default'} = [1]; 544# To have project specific config enable override in $GITWEB_CONFIG 545# $feature{'remote_heads'}{'override'} = 1; 546# and in project config gitweb.remoteheads = 0|1; 547'remote_heads'=> { 548'sub'=>sub{ feature_bool('remote_heads',@_) }, 549'override'=>0, 550'default'=> [0]}, 551); 552 553sub gitweb_get_feature { 554my($name) =@_; 555return unlessexists$feature{$name}; 556my($sub,$override,@defaults) = ( 557$feature{$name}{'sub'}, 558$feature{$name}{'override'}, 559@{$feature{$name}{'default'}}); 560# project specific override is possible only if we have project 561our$git_dir;# global variable, declared later 562if(!$override|| !defined$git_dir) { 563return@defaults; 564} 565if(!defined$sub) { 566warn"feature$nameis not overridable"; 567return@defaults; 568} 569return$sub->(@defaults); 570} 571 572# A wrapper to check if a given feature is enabled. 573# With this, you can say 574# 575# my $bool_feat = gitweb_check_feature('bool_feat'); 576# gitweb_check_feature('bool_feat') or somecode; 577# 578# instead of 579# 580# my ($bool_feat) = gitweb_get_feature('bool_feat'); 581# (gitweb_get_feature('bool_feat'))[0] or somecode; 582# 583sub gitweb_check_feature { 584return(gitweb_get_feature(@_))[0]; 585} 586 587 588sub feature_bool { 589my$key=shift; 590my($val) = git_get_project_config($key,'--bool'); 591 592if(!defined$val) { 593return($_[0]); 594}elsif($valeq'true') { 595return(1); 596}elsif($valeq'false') { 597return(0); 598} 599} 600 601sub feature_snapshot { 602my(@fmts) =@_; 603 604my($val) = git_get_project_config('snapshot'); 605 606if($val) { 607@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 608} 609 610return@fmts; 611} 612 613sub feature_patches { 614my@val= (git_get_project_config('patches','--int')); 615 616if(@val) { 617return@val; 618} 619 620return($_[0]); 621} 622 623sub feature_avatar { 624my@val= (git_get_project_config('avatar')); 625 626return@val?@val:@_; 627} 628 629# checking HEAD file with -e is fragile if the repository was 630# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 631# and then pruned. 632sub check_head_link { 633my($dir) =@_; 634my$headfile="$dir/HEAD"; 635return((-e $headfile) || 636(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 637} 638 639sub check_export_ok { 640my($dir) =@_; 641return(check_head_link($dir) && 642(!$export_ok|| -e "$dir/$export_ok") && 643(!$export_auth_hook||$export_auth_hook->($dir))); 644} 645 646# process alternate names for backward compatibility 647# filter out unsupported (unknown) snapshot formats 648sub filter_snapshot_fmts { 649my@fmts=@_; 650 651@fmts=map{ 652exists$known_snapshot_format_aliases{$_} ? 653$known_snapshot_format_aliases{$_} :$_}@fmts; 654@fmts=grep{ 655exists$known_snapshot_formats{$_} && 656!$known_snapshot_formats{$_}{'disabled'}}@fmts; 657} 658 659# If it is set to code reference, it is code that it is to be run once per 660# request, allowing updating configurations that change with each request, 661# while running other code in config file only once. 662# 663# Otherwise, if it is false then gitweb would process config file only once; 664# if it is true then gitweb config would be run for each request. 665our$per_request_config=1; 666 667# read and parse gitweb config file given by its parameter. 668# returns true on success, false on recoverable error, allowing 669# to chain this subroutine, using first file that exists. 670# dies on errors during parsing config file, as it is unrecoverable. 671sub read_config_file { 672my$filename=shift; 673return unlessdefined$filename; 674# die if there are errors parsing config file 675if(-e $filename) { 676do$filename; 677die$@if$@; 678return1; 679} 680return; 681} 682 683our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM,$GITWEB_CONFIG_COMMON); 684sub evaluate_gitweb_config { 685our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 686our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 687our$GITWEB_CONFIG_COMMON=$ENV{'GITWEB_CONFIG_COMMON'} ||"++GITWEB_CONFIG_COMMON++"; 688 689# Protect against duplications of file names, to not read config twice. 690# Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so 691# there possibility of duplication of filename there doesn't matter. 692$GITWEB_CONFIG=""if($GITWEB_CONFIGeq$GITWEB_CONFIG_COMMON); 693$GITWEB_CONFIG_SYSTEM=""if($GITWEB_CONFIG_SYSTEMeq$GITWEB_CONFIG_COMMON); 694 695# Common system-wide settings for convenience. 696# Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM. 697 read_config_file($GITWEB_CONFIG_COMMON); 698 699# Use first config file that exists. This means use the per-instance 700# GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG. 701 read_config_file($GITWEB_CONFIG)andreturn; 702 read_config_file($GITWEB_CONFIG_SYSTEM); 703} 704 705# Get loadavg of system, to compare against $maxload. 706# Currently it requires '/proc/loadavg' present to get loadavg; 707# if it is not present it returns 0, which means no load checking. 708sub get_loadavg { 709if( -e '/proc/loadavg'){ 710open my$fd,'<','/proc/loadavg' 711orreturn0; 712my@load=split(/\s+/,scalar<$fd>); 713close$fd; 714 715# The first three columns measure CPU and IO utilization of the last one, 716# five, and 10 minute periods. The fourth column shows the number of 717# currently running processes and the total number of processes in the m/n 718# format. The last column displays the last process ID used. 719return$load[0] ||0; 720} 721# additional checks for load average should go here for things that don't export 722# /proc/loadavg 723 724return0; 725} 726 727# version of the core git binary 728our$git_version; 729sub evaluate_git_version { 730our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 731$number_of_git_cmds++; 732} 733 734sub check_loadavg { 735if(defined$maxload&& get_loadavg() >$maxload) { 736 die_error(503,"The load average on the server is too high"); 737} 738} 739 740# ====================================================================== 741# input validation and dispatch 742 743# input parameters can be collected from a variety of sources (presently, CGI 744# and PATH_INFO), so we define an %input_params hash that collects them all 745# together during validation: this allows subsequent uses (e.g. href()) to be 746# agnostic of the parameter origin 747 748our%input_params= (); 749 750# input parameters are stored with the long parameter name as key. This will 751# also be used in the href subroutine to convert parameters to their CGI 752# equivalent, and since the href() usage is the most frequent one, we store 753# the name -> CGI key mapping here, instead of the reverse. 754# 755# XXX: Warning: If you touch this, check the search form for updating, 756# too. 757 758our@cgi_param_mapping= ( 759 project =>"p", 760 action =>"a", 761 file_name =>"f", 762 file_parent =>"fp", 763 hash =>"h", 764 hash_parent =>"hp", 765 hash_base =>"hb", 766 hash_parent_base =>"hpb", 767 page =>"pg", 768 order =>"o", 769 searchtext =>"s", 770 searchtype =>"st", 771 snapshot_format =>"sf", 772 extra_options =>"opt", 773 search_use_regexp =>"sr", 774 ctag =>"by_tag", 775 diff_style =>"ds", 776 project_filter =>"pf", 777# this must be last entry (for manipulation from JavaScript) 778 javascript =>"js" 779); 780our%cgi_param_mapping=@cgi_param_mapping; 781 782# we will also need to know the possible actions, for validation 783our%actions= ( 784"blame"=> \&git_blame, 785"blame_incremental"=> \&git_blame_incremental, 786"blame_data"=> \&git_blame_data, 787"blobdiff"=> \&git_blobdiff, 788"blobdiff_plain"=> \&git_blobdiff_plain, 789"blob"=> \&git_blob, 790"blob_plain"=> \&git_blob_plain, 791"commitdiff"=> \&git_commitdiff, 792"commitdiff_plain"=> \&git_commitdiff_plain, 793"commit"=> \&git_commit, 794"forks"=> \&git_forks, 795"heads"=> \&git_heads, 796"history"=> \&git_history, 797"log"=> \&git_log, 798"patch"=> \&git_patch, 799"patches"=> \&git_patches, 800"remotes"=> \&git_remotes, 801"rss"=> \&git_rss, 802"atom"=> \&git_atom, 803"search"=> \&git_search, 804"search_help"=> \&git_search_help, 805"shortlog"=> \&git_shortlog, 806"summary"=> \&git_summary, 807"tag"=> \&git_tag, 808"tags"=> \&git_tags, 809"tree"=> \&git_tree, 810"snapshot"=> \&git_snapshot, 811"object"=> \&git_object, 812# those below don't need $project 813"opml"=> \&git_opml, 814"project_list"=> \&git_project_list, 815"project_index"=> \&git_project_index, 816); 817 818# finally, we have the hash of allowed extra_options for the commands that 819# allow them 820our%allowed_options= ( 821"--no-merges"=> [qw(rss atom log shortlog history)], 822); 823 824# fill %input_params with the CGI parameters. All values except for 'opt' 825# should be single values, but opt can be an array. We should probably 826# build an array of parameters that can be multi-valued, but since for the time 827# being it's only this one, we just single it out 828sub evaluate_query_params { 829our$cgi; 830 831while(my($name,$symbol) =each%cgi_param_mapping) { 832if($symboleq'opt') { 833$input_params{$name} = [map{ decode_utf8($_) }$cgi->param($symbol) ]; 834}else{ 835$input_params{$name} = decode_utf8($cgi->param($symbol)); 836} 837} 838} 839 840# now read PATH_INFO and update the parameter list for missing parameters 841sub evaluate_path_info { 842return ifdefined$input_params{'project'}; 843return if!$path_info; 844$path_info=~ s,^/+,,; 845return if!$path_info; 846 847# find which part of PATH_INFO is project 848my$project=$path_info; 849$project=~ s,/+$,,; 850while($project&& !check_head_link("$projectroot/$project")) { 851$project=~ s,/*[^/]*$,,; 852} 853return unless$project; 854$input_params{'project'} =$project; 855 856# do not change any parameters if an action is given using the query string 857return if$input_params{'action'}; 858$path_info=~ s,^\Q$project\E/*,,; 859 860# next, check if we have an action 861my$action=$path_info; 862$action=~ s,/.*$,,; 863if(exists$actions{$action}) { 864$path_info=~ s,^$action/*,,; 865$input_params{'action'} =$action; 866} 867 868# list of actions that want hash_base instead of hash, but can have no 869# pathname (f) parameter 870my@wants_base= ( 871'tree', 872'history', 873); 874 875# we want to catch, among others 876# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 877my($parentrefname,$parentpathname,$refname,$pathname) = 878($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/); 879 880# first, analyze the 'current' part 881if(defined$pathname) { 882# we got "branch:filename" or "branch:dir/" 883# we could use git_get_type(branch:pathname), but: 884# - it needs $git_dir 885# - it does a git() call 886# - the convention of terminating directories with a slash 887# makes it superfluous 888# - embedding the action in the PATH_INFO would make it even 889# more superfluous 890$pathname=~ s,^/+,,; 891if(!$pathname||substr($pathname, -1)eq"/") { 892$input_params{'action'} ||="tree"; 893$pathname=~ s,/$,,; 894}else{ 895# the default action depends on whether we had parent info 896# or not 897if($parentrefname) { 898$input_params{'action'} ||="blobdiff_plain"; 899}else{ 900$input_params{'action'} ||="blob_plain"; 901} 902} 903$input_params{'hash_base'} ||=$refname; 904$input_params{'file_name'} ||=$pathname; 905}elsif(defined$refname) { 906# we got "branch". In this case we have to choose if we have to 907# set hash or hash_base. 908# 909# Most of the actions without a pathname only want hash to be 910# set, except for the ones specified in @wants_base that want 911# hash_base instead. It should also be noted that hand-crafted 912# links having 'history' as an action and no pathname or hash 913# set will fail, but that happens regardless of PATH_INFO. 914if(defined$parentrefname) { 915# if there is parent let the default be 'shortlog' action 916# (for http://git.example.com/repo.git/A..B links); if there 917# is no parent, dispatch will detect type of object and set 918# action appropriately if required (if action is not set) 919$input_params{'action'} ||="shortlog"; 920} 921if($input_params{'action'} && 922grep{$_eq$input_params{'action'} }@wants_base) { 923$input_params{'hash_base'} ||=$refname; 924}else{ 925$input_params{'hash'} ||=$refname; 926} 927} 928 929# next, handle the 'parent' part, if present 930if(defined$parentrefname) { 931# a missing pathspec defaults to the 'current' filename, allowing e.g. 932# someproject/blobdiff/oldrev..newrev:/filename 933if($parentpathname) { 934$parentpathname=~ s,^/+,,; 935$parentpathname=~ s,/$,,; 936$input_params{'file_parent'} ||=$parentpathname; 937}else{ 938$input_params{'file_parent'} ||=$input_params{'file_name'}; 939} 940# we assume that hash_parent_base is wanted if a path was specified, 941# or if the action wants hash_base instead of hash 942if(defined$input_params{'file_parent'} || 943grep{$_eq$input_params{'action'} }@wants_base) { 944$input_params{'hash_parent_base'} ||=$parentrefname; 945}else{ 946$input_params{'hash_parent'} ||=$parentrefname; 947} 948} 949 950# for the snapshot action, we allow URLs in the form 951# $project/snapshot/$hash.ext 952# where .ext determines the snapshot and gets removed from the 953# passed $refname to provide the $hash. 954# 955# To be able to tell that $refname includes the format extension, we 956# require the following two conditions to be satisfied: 957# - the hash input parameter MUST have been set from the $refname part 958# of the URL (i.e. they must be equal) 959# - the snapshot format MUST NOT have been defined already (e.g. from 960# CGI parameter sf) 961# It's also useless to try any matching unless $refname has a dot, 962# so we check for that too 963if(defined$input_params{'action'} && 964$input_params{'action'}eq'snapshot'&& 965defined$refname&&index($refname,'.') != -1&& 966$refnameeq$input_params{'hash'} && 967!defined$input_params{'snapshot_format'}) { 968# We loop over the known snapshot formats, checking for 969# extensions. Allowed extensions are both the defined suffix 970# (which includes the initial dot already) and the snapshot 971# format key itself, with a prepended dot 972while(my($fmt,$opt) =each%known_snapshot_formats) { 973my$hash=$refname; 974unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 975next; 976} 977my$sfx=$1; 978# a valid suffix was found, so set the snapshot format 979# and reset the hash parameter 980$input_params{'snapshot_format'} =$fmt; 981$input_params{'hash'} =$hash; 982# we also set the format suffix to the one requested 983# in the URL: this way a request for e.g. .tgz returns 984# a .tgz instead of a .tar.gz 985$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 986last; 987} 988} 989} 990 991our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 992$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 993$searchtext,$search_regexp,$project_filter); 994sub evaluate_and_validate_params { 995our$action=$input_params{'action'}; 996if(defined$action) { 997if(!is_valid_action($action)) { 998 die_error(400,"Invalid action parameter"); 999}1000}10011002# parameters which are pathnames1003our$project=$input_params{'project'};1004if(defined$project) {1005if(!is_valid_project($project)) {1006undef$project;1007 die_error(404,"No such project");1008}1009}10101011our$project_filter=$input_params{'project_filter'};1012if(defined$project_filter) {1013if(!is_valid_pathname($project_filter)) {1014 die_error(404,"Invalid project_filter parameter");1015}1016}10171018our$file_name=$input_params{'file_name'};1019if(defined$file_name) {1020if(!is_valid_pathname($file_name)) {1021 die_error(400,"Invalid file parameter");1022}1023}10241025our$file_parent=$input_params{'file_parent'};1026if(defined$file_parent) {1027if(!is_valid_pathname($file_parent)) {1028 die_error(400,"Invalid file parent parameter");1029}1030}10311032# parameters which are refnames1033our$hash=$input_params{'hash'};1034if(defined$hash) {1035if(!is_valid_refname($hash)) {1036 die_error(400,"Invalid hash parameter");1037}1038}10391040our$hash_parent=$input_params{'hash_parent'};1041if(defined$hash_parent) {1042if(!is_valid_refname($hash_parent)) {1043 die_error(400,"Invalid hash parent parameter");1044}1045}10461047our$hash_base=$input_params{'hash_base'};1048if(defined$hash_base) {1049if(!is_valid_refname($hash_base)) {1050 die_error(400,"Invalid hash base parameter");1051}1052}10531054our@extra_options= @{$input_params{'extra_options'}};1055# @extra_options is always defined, since it can only be (currently) set from1056# CGI, and $cgi->param() returns the empty array in array context if the param1057# is not set1058foreachmy$opt(@extra_options) {1059if(not exists$allowed_options{$opt}) {1060 die_error(400,"Invalid option parameter");1061}1062if(not grep(/^$action$/, @{$allowed_options{$opt}})) {1063 die_error(400,"Invalid option parameter for this action");1064}1065}10661067our$hash_parent_base=$input_params{'hash_parent_base'};1068if(defined$hash_parent_base) {1069if(!is_valid_refname($hash_parent_base)) {1070 die_error(400,"Invalid hash parent base parameter");1071}1072}10731074# other parameters1075our$page=$input_params{'page'};1076if(defined$page) {1077if($page=~m/[^0-9]/) {1078 die_error(400,"Invalid page parameter");1079}1080}10811082our$searchtype=$input_params{'searchtype'};1083if(defined$searchtype) {1084if($searchtype=~m/[^a-z]/) {1085 die_error(400,"Invalid searchtype parameter");1086}1087}10881089our$search_use_regexp=$input_params{'search_use_regexp'};10901091our$searchtext=$input_params{'searchtext'};1092our$search_regexp=undef;1093if(defined$searchtext) {1094if(length($searchtext) <2) {1095 die_error(403,"At least two characters are required for search parameter");1096}1097if($search_use_regexp) {1098$search_regexp=$searchtext;1099if(!eval{qr/$search_regexp/;1; }) {1100(my$error=$@) =~s/ at \S+ line \d+.*\n?//;1101 die_error(400,"Invalid search regexp '$search_regexp'",1102 esc_html($error));1103}1104}else{1105$search_regexp=quotemeta$searchtext;1106}1107}1108}11091110# path to the current git repository1111our$git_dir;1112sub evaluate_git_dir {1113our$git_dir="$projectroot/$project"if$project;1114}11151116our(@snapshot_fmts,$git_avatar);1117sub configure_gitweb_features {1118# list of supported snapshot formats1119our@snapshot_fmts= gitweb_get_feature('snapshot');1120@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);11211122# check that the avatar feature is set to a known provider name,1123# and for each provider check if the dependencies are satisfied.1124# if the provider name is invalid or the dependencies are not met,1125# reset $git_avatar to the empty string.1126our($git_avatar) = gitweb_get_feature('avatar');1127if($git_avatareq'gravatar') {1128$git_avatar=''unless(eval{require Digest::MD5;1; });1129}elsif($git_avatareq'picon') {1130# no dependencies1131}else{1132$git_avatar='';1133}1134}11351136# custom error handler: 'die <message>' is Internal Server Error1137sub handle_errors_html {1138my$msg=shift;# it is already HTML escaped11391140# to avoid infinite loop where error occurs in die_error,1141# change handler to default handler, disabling handle_errors_html1142 set_message("Error occurred when inside die_error:\n$msg");11431144# you cannot jump out of die_error when called as error handler;1145# the subroutine set via CGI::Carp::set_message is called _after_1146# HTTP headers are already written, so it cannot write them itself1147 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1148}1149set_message(\&handle_errors_html);11501151# dispatch1152sub dispatch {1153if(!defined$action) {1154if(defined$hash) {1155$action= git_get_type($hash);1156$actionor die_error(404,"Object does not exist");1157}elsif(defined$hash_base&&defined$file_name) {1158$action= git_get_type("$hash_base:$file_name");1159$actionor die_error(404,"File or directory does not exist");1160}elsif(defined$project) {1161$action='summary';1162}else{1163$action='project_list';1164}1165}1166if(!defined($actions{$action})) {1167 die_error(400,"Unknown action");1168}1169if($action!~m/^(?:opml|project_list|project_index)$/&&1170!$project) {1171 die_error(400,"Project needed");1172}1173$actions{$action}->();1174}11751176sub reset_timer {1177our$t0= [ gettimeofday() ]1178ifdefined$t0;1179our$number_of_git_cmds=0;1180}11811182our$first_request=1;1183sub run_request {1184 reset_timer();11851186 evaluate_uri();1187if($first_request) {1188 evaluate_gitweb_config();1189 evaluate_git_version();1190}1191if($per_request_config) {1192if(ref($per_request_config)eq'CODE') {1193$per_request_config->();1194}elsif(!$first_request) {1195 evaluate_gitweb_config();1196}1197}1198 check_loadavg();11991200# $projectroot and $projects_list might be set in gitweb config file1201$projects_list||=$projectroot;12021203 evaluate_query_params();1204 evaluate_path_info();1205 evaluate_and_validate_params();1206 evaluate_git_dir();12071208 configure_gitweb_features();12091210 dispatch();1211}12121213our$is_last_request=sub{1};1214our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1215our$CGI='CGI';1216our$cgi;1217sub configure_as_fcgi {1218require CGI::Fast;1219our$CGI='CGI::Fast';12201221my$request_number=0;1222# let each child service 100 requests1223our$is_last_request=sub{ ++$request_number>100};1224}1225sub evaluate_argv {1226my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1227 configure_as_fcgi()1228if$script_name=~/\.fcgi$/;12291230return unless(@ARGV);12311232require Getopt::Long;1233 Getopt::Long::GetOptions(1234'fastcgi|fcgi|f'=> \&configure_as_fcgi,1235'nproc|n=i'=>sub{1236my($arg,$val) =@_;1237return unlesseval{require FCGI::ProcManager;1; };1238my$proc_manager= FCGI::ProcManager->new({1239 n_processes =>$val,1240});1241our$pre_listen_hook=sub{$proc_manager->pm_manage() };1242our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1243our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1244},1245);1246}12471248sub run {1249 evaluate_argv();12501251$first_request=1;1252$pre_listen_hook->()1253if$pre_listen_hook;12541255 REQUEST:1256while($cgi=$CGI->new()) {1257$pre_dispatch_hook->()1258if$pre_dispatch_hook;12591260 run_request();12611262$post_dispatch_hook->()1263if$post_dispatch_hook;1264$first_request=0;12651266last REQUEST if($is_last_request->());1267}12681269 DONE_GITWEB:12701;1271}12721273run();12741275if(defined caller) {1276# wrapped in a subroutine processing requests,1277# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1278return;1279}else{1280# pure CGI script, serving single request1281exit;1282}12831284## ======================================================================1285## action links12861287# possible values of extra options1288# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1289# -replay => 1 - start from a current view (replay with modifications)1290# -path_info => 0|1 - don't use/use path_info URL (if possible)1291# -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone1292sub href {1293my%params=@_;1294# default is to use -absolute url() i.e. $my_uri1295my$href=$params{-full} ?$my_url:$my_uri;12961297# implicit -replay, must be first of implicit params1298$params{-replay} =1if(keys%params==1&&$params{-anchor});12991300$params{'project'} =$projectunlessexists$params{'project'};13011302if($params{-replay}) {1303while(my($name,$symbol) =each%cgi_param_mapping) {1304if(!exists$params{$name}) {1305$params{$name} =$input_params{$name};1306}1307}1308}13091310my$use_pathinfo= gitweb_check_feature('pathinfo');1311if(defined$params{'project'} &&1312(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1313# try to put as many parameters as possible in PATH_INFO:1314# - project name1315# - action1316# - hash_parent or hash_parent_base:/file_parent1317# - hash or hash_base:/filename1318# - the snapshot_format as an appropriate suffix13191320# When the script is the root DirectoryIndex for the domain,1321# $href here would be something like http://gitweb.example.com/1322# Thus, we strip any trailing / from $href, to spare us double1323# slashes in the final URL1324$href=~ s,/$,,;13251326# Then add the project name, if present1327$href.="/".esc_path_info($params{'project'});1328delete$params{'project'};13291330# since we destructively absorb parameters, we keep this1331# boolean that remembers if we're handling a snapshot1332my$is_snapshot=$params{'action'}eq'snapshot';13331334# Summary just uses the project path URL, any other action is1335# added to the URL1336if(defined$params{'action'}) {1337$href.="/".esc_path_info($params{'action'})1338unless$params{'action'}eq'summary';1339delete$params{'action'};1340}13411342# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1343# stripping nonexistent or useless pieces1344$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1345||$params{'hash_parent'} ||$params{'hash'});1346if(defined$params{'hash_base'}) {1347if(defined$params{'hash_parent_base'}) {1348$href.= esc_path_info($params{'hash_parent_base'});1349# skip the file_parent if it's the same as the file_name1350if(defined$params{'file_parent'}) {1351if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1352delete$params{'file_parent'};1353}elsif($params{'file_parent'} !~/\.\./) {1354$href.=":/".esc_path_info($params{'file_parent'});1355delete$params{'file_parent'};1356}1357}1358$href.="..";1359delete$params{'hash_parent'};1360delete$params{'hash_parent_base'};1361}elsif(defined$params{'hash_parent'}) {1362$href.= esc_path_info($params{'hash_parent'})."..";1363delete$params{'hash_parent'};1364}13651366$href.= esc_path_info($params{'hash_base'});1367if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1368$href.=":/".esc_path_info($params{'file_name'});1369delete$params{'file_name'};1370}1371delete$params{'hash'};1372delete$params{'hash_base'};1373}elsif(defined$params{'hash'}) {1374$href.= esc_path_info($params{'hash'});1375delete$params{'hash'};1376}13771378# If the action was a snapshot, we can absorb the1379# snapshot_format parameter too1380if($is_snapshot) {1381my$fmt=$params{'snapshot_format'};1382# snapshot_format should always be defined when href()1383# is called, but just in case some code forgets, we1384# fall back to the default1385$fmt||=$snapshot_fmts[0];1386$href.=$known_snapshot_formats{$fmt}{'suffix'};1387delete$params{'snapshot_format'};1388}1389}13901391# now encode the parameters explicitly1392my@result= ();1393for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1394my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1395if(defined$params{$name}) {1396if(ref($params{$name})eq"ARRAY") {1397foreachmy$par(@{$params{$name}}) {1398push@result,$symbol."=". esc_param($par);1399}1400}else{1401push@result,$symbol."=". esc_param($params{$name});1402}1403}1404}1405$href.="?".join(';',@result)ifscalar@result;14061407# final transformation: trailing spaces must be escaped (URI-encoded)1408$href=~s/(\s+)$/CGI::escape($1)/e;14091410if($params{-anchor}) {1411$href.="#".esc_param($params{-anchor});1412}14131414return$href;1415}141614171418## ======================================================================1419## validation, quoting/unquoting and escaping14201421sub is_valid_action {1422my$input=shift;1423returnundefunlessexists$actions{$input};1424return1;1425}14261427sub is_valid_project {1428my$input=shift;14291430return unlessdefined$input;1431if(!is_valid_pathname($input) ||1432!(-d "$projectroot/$input") ||1433!check_export_ok("$projectroot/$input") ||1434($strict_export&& !project_in_list($input))) {1435returnundef;1436}else{1437return1;1438}1439}14401441sub is_valid_pathname {1442my$input=shift;14431444returnundefunlessdefined$input;1445# no '.' or '..' as elements of path, i.e. no '.' nor '..'1446# at the beginning, at the end, and between slashes.1447# also this catches doubled slashes1448if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1449returnundef;1450}1451# no null characters1452if($input=~m!\0!) {1453returnundef;1454}1455return1;1456}14571458sub is_valid_ref_format {1459my$input=shift;14601461returnundefunlessdefined$input;1462# restrictions on ref name according to git-check-ref-format1463if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1464returnundef;1465}1466return1;1467}14681469sub is_valid_refname {1470my$input=shift;14711472returnundefunlessdefined$input;1473# textual hashes are O.K.1474if($input=~m/^[0-9a-fA-F]{40}$/) {1475return1;1476}1477# it must be correct pathname1478 is_valid_pathname($input)orreturnundef;1479# check git-check-ref-format restrictions1480 is_valid_ref_format($input)orreturnundef;1481return1;1482}14831484# decode sequences of octets in utf8 into Perl's internal form,1485# which is utf-8 with utf8 flag set if needed. gitweb writes out1486# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1487sub to_utf8 {1488my$str=shift;1489returnundefunlessdefined$str;14901491if(utf8::is_utf8($str) || utf8::decode($str)) {1492return$str;1493}else{1494return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1495}1496}14971498# quote unsafe chars, but keep the slash, even when it's not1499# correct, but quoted slashes look too horrible in bookmarks1500sub esc_param {1501my$str=shift;1502returnundefunlessdefined$str;1503$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1504$str=~s/ /\+/g;1505return$str;1506}15071508# the quoting rules for path_info fragment are slightly different1509sub esc_path_info {1510my$str=shift;1511returnundefunlessdefined$str;15121513# path_info doesn't treat '+' as space (specially), but '?' must be escaped1514$str=~s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;15151516return$str;1517}15181519# quote unsafe chars in whole URL, so some characters cannot be quoted1520sub esc_url {1521my$str=shift;1522returnundefunlessdefined$str;1523$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1524$str=~s/ /\+/g;1525return$str;1526}15271528# quote unsafe characters in HTML attributes1529sub esc_attr {15301531# for XHTML conformance escaping '"' to '"' is not enough1532return esc_html(@_);1533}15341535# replace invalid utf8 character with SUBSTITUTION sequence1536sub esc_html {1537my$str=shift;1538my%opts=@_;15391540returnundefunlessdefined$str;15411542$str= to_utf8($str);1543$str=$cgi->escapeHTML($str);1544if($opts{'-nbsp'}) {1545$str=~s/ / /g;1546}1547$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1548return$str;1549}15501551# quote control characters and escape filename to HTML1552sub esc_path {1553my$str=shift;1554my%opts=@_;15551556returnundefunlessdefined$str;15571558$str= to_utf8($str);1559$str=$cgi->escapeHTML($str);1560if($opts{'-nbsp'}) {1561$str=~s/ / /g;1562}1563$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1564return$str;1565}15661567# Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)1568sub sanitize {1569my$str=shift;15701571returnundefunlessdefined$str;15721573$str= to_utf8($str);1574$str=~ s|([[:cntrl:]])|(index("\t\n\r",$1) != -1?$1: quot_cec($1))|eg;1575return$str;1576}15771578# Make control characters "printable", using character escape codes (CEC)1579sub quot_cec {1580my$cntrl=shift;1581my%opts=@_;1582my%es= (# character escape codes, aka escape sequences1583"\t"=>'\t',# tab (HT)1584"\n"=>'\n',# line feed (LF)1585"\r"=>'\r',# carrige return (CR)1586"\f"=>'\f',# form feed (FF)1587"\b"=>'\b',# backspace (BS)1588"\a"=>'\a',# alarm (bell) (BEL)1589"\e"=>'\e',# escape (ESC)1590"\013"=>'\v',# vertical tab (VT)1591"\000"=>'\0',# nul character (NUL)1592);1593my$chr= ( (exists$es{$cntrl})1594?$es{$cntrl}1595:sprintf('\%2x',ord($cntrl)) );1596if($opts{-nohtml}) {1597return$chr;1598}else{1599return"<span class=\"cntrl\">$chr</span>";1600}1601}16021603# Alternatively use unicode control pictures codepoints,1604# Unicode "printable representation" (PR)1605sub quot_upr {1606my$cntrl=shift;1607my%opts=@_;16081609my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1610if($opts{-nohtml}) {1611return$chr;1612}else{1613return"<span class=\"cntrl\">$chr</span>";1614}1615}16161617# git may return quoted and escaped filenames1618sub unquote {1619my$str=shift;16201621sub unq {1622my$seq=shift;1623my%es= (# character escape codes, aka escape sequences1624't'=>"\t",# tab (HT, TAB)1625'n'=>"\n",# newline (NL)1626'r'=>"\r",# return (CR)1627'f'=>"\f",# form feed (FF)1628'b'=>"\b",# backspace (BS)1629'a'=>"\a",# alarm (bell) (BEL)1630'e'=>"\e",# escape (ESC)1631'v'=>"\013",# vertical tab (VT)1632);16331634if($seq=~m/^[0-7]{1,3}$/) {1635# octal char sequence1636returnchr(oct($seq));1637}elsif(exists$es{$seq}) {1638# C escape sequence, aka character escape code1639return$es{$seq};1640}1641# quoted ordinary character1642return$seq;1643}16441645if($str=~m/^"(.*)"$/) {1646# needs unquoting1647$str=$1;1648$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1649}1650return$str;1651}16521653# escape tabs (convert tabs to spaces)1654sub untabify {1655my$line=shift;16561657while((my$pos=index($line,"\t")) != -1) {1658if(my$count= (8- ($pos%8))) {1659my$spaces=' ' x $count;1660$line=~s/\t/$spaces/;1661}1662}16631664return$line;1665}16661667sub project_in_list {1668my$project=shift;1669my@list= git_get_projects_list();1670return@list&&scalar(grep{$_->{'path'}eq$project}@list);1671}16721673## ----------------------------------------------------------------------1674## HTML aware string manipulation16751676# Try to chop given string on a word boundary between position1677# $len and $len+$add_len. If there is no word boundary there,1678# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1679# (marking chopped part) would be longer than given string.1680sub chop_str {1681my$str=shift;1682my$len=shift;1683my$add_len=shift||10;1684my$where=shift||'right';# 'left' | 'center' | 'right'16851686# Make sure perl knows it is utf8 encoded so we don't1687# cut in the middle of a utf8 multibyte char.1688$str= to_utf8($str);16891690# allow only $len chars, but don't cut a word if it would fit in $add_len1691# if it doesn't fit, cut it if it's still longer than the dots we would add1692# remove chopped character entities entirely16931694# when chopping in the middle, distribute $len into left and right part1695# return early if chopping wouldn't make string shorter1696if($whereeq'center') {1697return$strif($len+5>=length($str));# filler is length 51698$len=int($len/2);1699}else{1700return$strif($len+4>=length($str));# filler is length 41701}17021703# regexps: ending and beginning with word part up to $add_len1704my$endre=qr/.{$len}\w{0,$add_len}/;1705my$begre=qr/\w{0,$add_len}.{$len}/;17061707if($whereeq'left') {1708$str=~m/^(.*?)($begre)$/;1709my($lead,$body) = ($1,$2);1710if(length($lead) >4) {1711$lead=" ...";1712}1713return"$lead$body";17141715}elsif($whereeq'center') {1716$str=~m/^($endre)(.*)$/;1717my($left,$str) = ($1,$2);1718$str=~m/^(.*?)($begre)$/;1719my($mid,$right) = ($1,$2);1720if(length($mid) >5) {1721$mid=" ... ";1722}1723return"$left$mid$right";17241725}else{1726$str=~m/^($endre)(.*)$/;1727my$body=$1;1728my$tail=$2;1729if(length($tail) >4) {1730$tail="... ";1731}1732return"$body$tail";1733}1734}17351736# takes the same arguments as chop_str, but also wraps a <span> around the1737# result with a title attribute if it does get chopped. Additionally, the1738# string is HTML-escaped.1739sub chop_and_escape_str {1740my($str) =@_;17411742my$chopped= chop_str(@_);1743$str= to_utf8($str);1744if($choppedeq$str) {1745return esc_html($chopped);1746}else{1747$str=~s/[[:cntrl:]]/?/g;1748return$cgi->span({-title=>$str}, esc_html($chopped));1749}1750}17511752# Highlight selected fragments of string, using given CSS class,1753# and escape HTML. It is assumed that fragments do not overlap.1754# Regions are passed as list of pairs (array references).1755#1756# Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns1757# '<span class="mark">foo</span>bar'1758sub esc_html_hl_regions {1759my($str,$css_class,@sel) =@_;1760my%opts=grep{ref($_)ne'ARRAY'}@sel;1761@sel=grep{ref($_)eq'ARRAY'}@sel;1762return esc_html($str,%opts)unless@sel;17631764my$out='';1765my$pos=0;17661767formy$s(@sel) {1768my($begin,$end) =@$s;17691770# Don't create empty <span> elements.1771next if$end<=$begin;17721773my$escaped= esc_html(substr($str,$begin,$end-$begin),1774%opts);17751776$out.= esc_html(substr($str,$pos,$begin-$pos),%opts)1777if($begin-$pos>0);1778$out.=$cgi->span({-class=>$css_class},$escaped);17791780$pos=$end;1781}1782$out.= esc_html(substr($str,$pos),%opts)1783if($pos<length($str));17841785return$out;1786}17871788# return positions of beginning and end of each match1789sub matchpos_list {1790my($str,$regexp) =@_;1791return unless(defined$str&&defined$regexp);17921793my@matches;1794while($str=~/$regexp/g) {1795push@matches, [$-[0],$+[0]];1796}1797return@matches;1798}17991800# highlight match (if any), and escape HTML1801sub esc_html_match_hl {1802my($str,$regexp) =@_;1803return esc_html($str)unlessdefined$regexp;18041805my@matches= matchpos_list($str,$regexp);1806return esc_html($str)unless@matches;18071808return esc_html_hl_regions($str,'match',@matches);1809}181018111812# highlight match (if any) of shortened string, and escape HTML1813sub esc_html_match_hl_chopped {1814my($str,$chopped,$regexp) =@_;1815return esc_html_match_hl($str,$regexp)unlessdefined$chopped;18161817my@matches= matchpos_list($str,$regexp);1818return esc_html($chopped)unless@matches;18191820# filter matches so that we mark chopped string1821my$tail="... ";# see chop_str1822unless($chopped=~s/\Q$tail\E$//) {1823$tail='';1824}1825my$chop_len=length($chopped);1826my$tail_len=length($tail);1827my@filtered;18281829formy$m(@matches) {1830if($m->[0] >$chop_len) {1831push@filtered, [$chop_len,$chop_len+$tail_len]if($tail_len>0);1832last;1833}elsif($m->[1] >$chop_len) {1834push@filtered, [$m->[0],$chop_len+$tail_len];1835last;1836}1837push@filtered,$m;1838}18391840return esc_html_hl_regions($chopped.$tail,'match',@filtered);1841}18421843## ----------------------------------------------------------------------1844## functions returning short strings18451846# CSS class for given age value (in seconds)1847sub age_class {1848my$age=shift;18491850if(!defined$age) {1851return"noage";1852}elsif($age<60*60*2) {1853return"age0";1854}elsif($age<60*60*24*2) {1855return"age1";1856}else{1857return"age2";1858}1859}18601861# convert age in seconds to "nn units ago" string1862sub age_string {1863my$age=shift;1864my$age_str;18651866if($age>60*60*24*365*2) {1867$age_str= (int$age/60/60/24/365);1868$age_str.=" years ago";1869}elsif($age>60*60*24*(365/12)*2) {1870$age_str=int$age/60/60/24/(365/12);1871$age_str.=" months ago";1872}elsif($age>60*60*24*7*2) {1873$age_str=int$age/60/60/24/7;1874$age_str.=" weeks ago";1875}elsif($age>60*60*24*2) {1876$age_str=int$age/60/60/24;1877$age_str.=" days ago";1878}elsif($age>60*60*2) {1879$age_str=int$age/60/60;1880$age_str.=" hours ago";1881}elsif($age>60*2) {1882$age_str=int$age/60;1883$age_str.=" min ago";1884}elsif($age>2) {1885$age_str=int$age;1886$age_str.=" sec ago";1887}else{1888$age_str.=" right now";1889}1890return$age_str;1891}18921893useconstant{1894 S_IFINVALID =>0030000,1895 S_IFGITLINK =>0160000,1896};18971898# submodule/subproject, a commit object reference1899sub S_ISGITLINK {1900my$mode=shift;19011902return(($mode& S_IFMT) == S_IFGITLINK)1903}19041905# convert file mode in octal to symbolic file mode string1906sub mode_str {1907my$mode=oct shift;19081909if(S_ISGITLINK($mode)) {1910return'm---------';1911}elsif(S_ISDIR($mode& S_IFMT)) {1912return'drwxr-xr-x';1913}elsif(S_ISLNK($mode)) {1914return'lrwxrwxrwx';1915}elsif(S_ISREG($mode)) {1916# git cares only about the executable bit1917if($mode& S_IXUSR) {1918return'-rwxr-xr-x';1919}else{1920return'-rw-r--r--';1921};1922}else{1923return'----------';1924}1925}19261927# convert file mode in octal to file type string1928sub file_type {1929my$mode=shift;19301931if($mode!~m/^[0-7]+$/) {1932return$mode;1933}else{1934$mode=oct$mode;1935}19361937if(S_ISGITLINK($mode)) {1938return"submodule";1939}elsif(S_ISDIR($mode& S_IFMT)) {1940return"directory";1941}elsif(S_ISLNK($mode)) {1942return"symlink";1943}elsif(S_ISREG($mode)) {1944return"file";1945}else{1946return"unknown";1947}1948}19491950# convert file mode in octal to file type description string1951sub file_type_long {1952my$mode=shift;19531954if($mode!~m/^[0-7]+$/) {1955return$mode;1956}else{1957$mode=oct$mode;1958}19591960if(S_ISGITLINK($mode)) {1961return"submodule";1962}elsif(S_ISDIR($mode& S_IFMT)) {1963return"directory";1964}elsif(S_ISLNK($mode)) {1965return"symlink";1966}elsif(S_ISREG($mode)) {1967if($mode& S_IXUSR) {1968return"executable";1969}else{1970return"file";1971};1972}else{1973return"unknown";1974}1975}197619771978## ----------------------------------------------------------------------1979## functions returning short HTML fragments, or transforming HTML fragments1980## which don't belong to other sections19811982# format line of commit message.1983sub format_log_line_html {1984my$line=shift;19851986$line= esc_html($line, -nbsp=>1);1987$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1988$cgi->a({-href => href(action=>"object", hash=>$1),1989-class=>"text"},$1);1990}eg;19911992return$line;1993}19941995# format marker of refs pointing to given object19961997# the destination action is chosen based on object type and current context:1998# - for annotated tags, we choose the tag view unless it's the current view1999# already, in which case we go to shortlog view2000# - for other refs, we keep the current view if we're in history, shortlog or2001# log view, and select shortlog otherwise2002sub format_ref_marker {2003my($refs,$id) =@_;2004my$markers='';20052006if(defined$refs->{$id}) {2007foreachmy$ref(@{$refs->{$id}}) {2008# this code exploits the fact that non-lightweight tags are the2009# only indirect objects, and that they are the only objects for which2010# we want to use tag instead of shortlog as action2011my($type,$name) =qw();2012my$indirect= ($ref=~s/\^\{\}$//);2013# e.g. tags/v2.6.11 or heads/next2014if($ref=~m!^(.*?)s?/(.*)$!) {2015$type=$1;2016$name=$2;2017}else{2018$type="ref";2019$name=$ref;2020}20212022my$class=$type;2023$class.=" indirect"if$indirect;20242025my$dest_action="shortlog";20262027if($indirect) {2028$dest_action="tag"unless$actioneq"tag";2029}elsif($action=~/^(history|(short)?log)$/) {2030$dest_action=$action;2031}20322033my$dest="";2034$dest.="refs/"unless$ref=~ m!^refs/!;2035$dest.=$ref;20362037my$link=$cgi->a({2038-href => href(2039 action=>$dest_action,2040 hash=>$dest2041)},$name);20422043$markers.=" <span class=\"".esc_attr($class)."\"title=\"".esc_attr($ref)."\">".2044$link."</span>";2045}2046}20472048if($markers) {2049return' <span class="refs">'.$markers.'</span>';2050}else{2051return"";2052}2053}20542055# format, perhaps shortened and with markers, title line2056sub format_subject_html {2057my($long,$short,$href,$extra) =@_;2058$extra=''unlessdefined($extra);20592060if(length($short) <length($long)) {2061$long=~s/[[:cntrl:]]/?/g;2062return$cgi->a({-href =>$href, -class=>"list subject",2063-title => to_utf8($long)},2064 esc_html($short)) .$extra;2065}else{2066return$cgi->a({-href =>$href, -class=>"list subject"},2067 esc_html($long)) .$extra;2068}2069}20702071# Rather than recomputing the url for an email multiple times, we cache it2072# after the first hit. This gives a visible benefit in views where the avatar2073# for the same email is used repeatedly (e.g. shortlog).2074# The cache is shared by all avatar engines (currently gravatar only), which2075# are free to use it as preferred. Since only one avatar engine is used for any2076# given page, there's no risk for cache conflicts.2077our%avatar_cache= ();20782079# Compute the picon url for a given email, by using the picon search service over at2080# http://www.cs.indiana.edu/picons/search.html2081sub picon_url {2082my$email=lc shift;2083if(!$avatar_cache{$email}) {2084my($user,$domain) =split('@',$email);2085$avatar_cache{$email} =2086"//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".2087"$domain/$user/".2088"users+domains+unknown/up/single";2089}2090return$avatar_cache{$email};2091}20922093# Compute the gravatar url for a given email, if it's not in the cache already.2094# Gravatar stores only the part of the URL before the size, since that's the2095# one computationally more expensive. This also allows reuse of the cache for2096# different sizes (for this particular engine).2097sub gravatar_url {2098my$email=lc shift;2099my$size=shift;2100$avatar_cache{$email} ||=2101"//www.gravatar.com/avatar/".2102 Digest::MD5::md5_hex($email) ."?s=";2103return$avatar_cache{$email} .$size;2104}21052106# Insert an avatar for the given $email at the given $size if the feature2107# is enabled.2108sub git_get_avatar {2109my($email,%opts) =@_;2110my$pre_white= ($opts{-pad_before} ?" ":"");2111my$post_white= ($opts{-pad_after} ?" ":"");2112$opts{-size} ||='default';2113my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};2114my$url="";2115if($git_avatareq'gravatar') {2116$url= gravatar_url($email,$size);2117}elsif($git_avatareq'picon') {2118$url= picon_url($email);2119}2120# Other providers can be added by extending the if chain, defining $url2121# as needed. If no variant puts something in $url, we assume avatars2122# are completely disabled/unavailable.2123if($url) {2124return$pre_white.2125"<img width=\"$size\"".2126"class=\"avatar\"".2127"src=\"".esc_url($url)."\"".2128"alt=\"\"".2129"/>".$post_white;2130}else{2131return"";2132}2133}21342135sub format_search_author {2136my($author,$searchtype,$displaytext) =@_;2137my$have_search= gitweb_check_feature('search');21382139if($have_search) {2140my$performed="";2141if($searchtypeeq'author') {2142$performed="authored";2143}elsif($searchtypeeq'committer') {2144$performed="committed";2145}21462147return$cgi->a({-href => href(action=>"search", hash=>$hash,2148 searchtext=>$author,2149 searchtype=>$searchtype),class=>"list",2150 title=>"Search for commits$performedby$author"},2151$displaytext);21522153}else{2154return$displaytext;2155}2156}21572158# format the author name of the given commit with the given tag2159# the author name is chopped and escaped according to the other2160# optional parameters (see chop_str).2161sub format_author_html {2162my$tag=shift;2163my$co=shift;2164my$author= chop_and_escape_str($co->{'author_name'},@_);2165return"<$tagclass=\"author\">".2166 format_search_author($co->{'author_name'},"author",2167 git_get_avatar($co->{'author_email'}, -pad_after =>1) .2168$author) .2169"</$tag>";2170}21712172# format git diff header line, i.e. "diff --(git|combined|cc) ..."2173sub format_git_diff_header_line {2174my$line=shift;2175my$diffinfo=shift;2176my($from,$to) =@_;21772178if($diffinfo->{'nparents'}) {2179# combined diff2180$line=~s!^(diff (.*?) )"?.*$!$1!;2181if($to->{'href'}) {2182$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2183 esc_path($to->{'file'}));2184}else{# file was deleted (no href)2185$line.= esc_path($to->{'file'});2186}2187}else{2188# "ordinary" diff2189$line=~s!^(diff (.*?) )"?a/.*$!$1!;2190if($from->{'href'}) {2191$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},2192'a/'. esc_path($from->{'file'}));2193}else{# file was added (no href)2194$line.='a/'. esc_path($from->{'file'});2195}2196$line.=' ';2197if($to->{'href'}) {2198$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2199'b/'. esc_path($to->{'file'}));2200}else{# file was deleted2201$line.='b/'. esc_path($to->{'file'});2202}2203}22042205return"<div class=\"diff header\">$line</div>\n";2206}22072208# format extended diff header line, before patch itself2209sub format_extended_diff_header_line {2210my$line=shift;2211my$diffinfo=shift;2212my($from,$to) =@_;22132214# match <path>2215if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {2216$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},2217 esc_path($from->{'file'}));2218}2219if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {2220$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},2221 esc_path($to->{'file'}));2222}2223# match single <mode>2224if($line=~m/\s(\d{6})$/) {2225$line.='<span class="info"> ('.2226 file_type_long($1) .2227')</span>';2228}2229# match <hash>2230if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {2231# can match only for combined diff2232$line='index ';2233for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2234if($from->{'href'}[$i]) {2235$line.=$cgi->a({-href=>$from->{'href'}[$i],2236-class=>"hash"},2237substr($diffinfo->{'from_id'}[$i],0,7));2238}else{2239$line.='0' x 7;2240}2241# separator2242$line.=','if($i<$diffinfo->{'nparents'} -1);2243}2244$line.='..';2245if($to->{'href'}) {2246$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2247substr($diffinfo->{'to_id'},0,7));2248}else{2249$line.='0' x 7;2250}22512252}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {2253# can match only for ordinary diff2254my($from_link,$to_link);2255if($from->{'href'}) {2256$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},2257substr($diffinfo->{'from_id'},0,7));2258}else{2259$from_link='0' x 7;2260}2261if($to->{'href'}) {2262$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2263substr($diffinfo->{'to_id'},0,7));2264}else{2265$to_link='0' x 7;2266}2267my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});2268$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;2269}22702271return$line."<br/>\n";2272}22732274# format from-file/to-file diff header2275sub format_diff_from_to_header {2276my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2277my$line;2278my$result='';22792280$line=$from_line;2281#assert($line =~ m/^---/) if DEBUG;2282# no extra formatting for "^--- /dev/null"2283if(!$diffinfo->{'nparents'}) {2284# ordinary (single parent) diff2285if($line=~m!^--- "?a/!) {2286if($from->{'href'}) {2287$line='--- a/'.2288$cgi->a({-href=>$from->{'href'}, -class=>"path"},2289 esc_path($from->{'file'}));2290}else{2291$line='--- a/'.2292 esc_path($from->{'file'});2293}2294}2295$result.= qq!<div class="diff from_file">$line</div>\n!;22962297}else{2298# combined diff (merge commit)2299for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2300if($from->{'href'}[$i]) {2301$line='--- '.2302$cgi->a({-href=>href(action=>"blobdiff",2303 hash_parent=>$diffinfo->{'from_id'}[$i],2304 hash_parent_base=>$parents[$i],2305 file_parent=>$from->{'file'}[$i],2306 hash=>$diffinfo->{'to_id'},2307 hash_base=>$hash,2308 file_name=>$to->{'file'}),2309-class=>"path",2310-title=>"diff". ($i+1)},2311$i+1) .2312'/'.2313$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2314 esc_path($from->{'file'}[$i]));2315}else{2316$line='--- /dev/null';2317}2318$result.= qq!<div class="diff from_file">$line</div>\n!;2319}2320}23212322$line=$to_line;2323#assert($line =~ m/^\+\+\+/) if DEBUG;2324# no extra formatting for "^+++ /dev/null"2325if($line=~m!^\+\+\+ "?b/!) {2326if($to->{'href'}) {2327$line='+++ b/'.2328$cgi->a({-href=>$to->{'href'}, -class=>"path"},2329 esc_path($to->{'file'}));2330}else{2331$line='+++ b/'.2332 esc_path($to->{'file'});2333}2334}2335$result.= qq!<div class="diff to_file">$line</div>\n!;23362337return$result;2338}23392340# create note for patch simplified by combined diff2341sub format_diff_cc_simplified {2342my($diffinfo,@parents) =@_;2343my$result='';23442345$result.="<div class=\"diff header\">".2346"diff --cc ";2347if(!is_deleted($diffinfo)) {2348$result.=$cgi->a({-href => href(action=>"blob",2349 hash_base=>$hash,2350 hash=>$diffinfo->{'to_id'},2351 file_name=>$diffinfo->{'to_file'}),2352-class=>"path"},2353 esc_path($diffinfo->{'to_file'}));2354}else{2355$result.= esc_path($diffinfo->{'to_file'});2356}2357$result.="</div>\n".# class="diff header"2358"<div class=\"diff nodifferences\">".2359"Simple merge".2360"</div>\n";# class="diff nodifferences"23612362return$result;2363}23642365sub diff_line_class {2366my($line,$from,$to) =@_;23672368# ordinary diff2369my$num_sign=1;2370# combined diff2371if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2372$num_sign=scalar@{$from->{'href'}};2373}23742375my@diff_line_classifier= (2376{ regexp =>qr/^\@\@{$num_sign} /,class=>"chunk_header"},2377{ regexp =>qr/^\\/,class=>"incomplete"},2378{ regexp =>qr/^ {$num_sign}/,class=>"ctx"},2379# classifier for context must come before classifier add/rem,2380# or we would have to use more complicated regexp, for example2381# qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;2382{ regexp =>qr/^[+ ]{$num_sign}/,class=>"add"},2383{ regexp =>qr/^[- ]{$num_sign}/,class=>"rem"},2384);2385formy$clsfy(@diff_line_classifier) {2386return$clsfy->{'class'}2387if($line=~$clsfy->{'regexp'});2388}23892390# fallback2391return"";2392}23932394# assumes that $from and $to are defined and correctly filled,2395# and that $line holds a line of chunk header for unified diff2396sub format_unidiff_chunk_header {2397my($line,$from,$to) =@_;23982399my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2400$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;24012402$from_lines=0unlessdefined$from_lines;2403$to_lines=0unlessdefined$to_lines;24042405if($from->{'href'}) {2406$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2407-class=>"list"},$from_text);2408}2409if($to->{'href'}) {2410$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2411-class=>"list"},$to_text);2412}2413$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2414"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2415return$line;2416}24172418# assumes that $from and $to are defined and correctly filled,2419# and that $line holds a line of chunk header for combined diff2420sub format_cc_diff_chunk_header {2421my($line,$from,$to) =@_;24222423my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2424my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);24252426@from_text=split(' ',$ranges);2427for(my$i=0;$i<@from_text; ++$i) {2428($from_start[$i],$from_nlines[$i]) =2429(split(',',substr($from_text[$i],1)),0);2430}24312432$to_text=pop@from_text;2433$to_start=pop@from_start;2434$to_nlines=pop@from_nlines;24352436$line="<span class=\"chunk_info\">$prefix";2437for(my$i=0;$i<@from_text; ++$i) {2438if($from->{'href'}[$i]) {2439$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2440-class=>"list"},$from_text[$i]);2441}else{2442$line.=$from_text[$i];2443}2444$line.=" ";2445}2446if($to->{'href'}) {2447$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2448-class=>"list"},$to_text);2449}else{2450$line.=$to_text;2451}2452$line.="$prefix</span>".2453"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2454return$line;2455}24562457# process patch (diff) line (not to be used for diff headers),2458# returning HTML-formatted (but not wrapped) line.2459# If the line is passed as a reference, it is treated as HTML and not2460# esc_html()'ed.2461sub format_diff_line {2462my($line,$diff_class,$from,$to) =@_;24632464if(ref($line)) {2465$line=$$line;2466}else{2467chomp$line;2468$line= untabify($line);24692470if($from&&$to&&$line=~m/^\@{2} /) {2471$line= format_unidiff_chunk_header($line,$from,$to);2472}elsif($from&&$to&&$line=~m/^\@{3}/) {2473$line= format_cc_diff_chunk_header($line,$from,$to);2474}else{2475$line= esc_html($line, -nbsp=>1);2476}2477}24782479my$diff_classes="diff";2480$diff_classes.="$diff_class"if($diff_class);2481$line="<div class=\"$diff_classes\">$line</div>\n";24822483return$line;2484}24852486# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2487# linked. Pass the hash of the tree/commit to snapshot.2488sub format_snapshot_links {2489my($hash) =@_;2490my$num_fmts=@snapshot_fmts;2491if($num_fmts>1) {2492# A parenthesized list of links bearing format names.2493# e.g. "snapshot (_tar.gz_ _zip_)"2494return"snapshot (".join(' ',map2495$cgi->a({2496-href => href(2497 action=>"snapshot",2498 hash=>$hash,2499 snapshot_format=>$_2500)2501},$known_snapshot_formats{$_}{'display'})2502,@snapshot_fmts) .")";2503}elsif($num_fmts==1) {2504# A single "snapshot" link whose tooltip bears the format name.2505# i.e. "_snapshot_"2506my($fmt) =@snapshot_fmts;2507return2508$cgi->a({2509-href => href(2510 action=>"snapshot",2511 hash=>$hash,2512 snapshot_format=>$fmt2513),2514-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2515},"snapshot");2516}else{# $num_fmts == 02517returnundef;2518}2519}25202521## ......................................................................2522## functions returning values to be passed, perhaps after some2523## transformation, to other functions; e.g. returning arguments to href()25242525# returns hash to be passed to href to generate gitweb URL2526# in -title key it returns description of link2527sub get_feed_info {2528my$format=shift||'Atom';2529my%res= (action =>lc($format));25302531# feed links are possible only for project views2532return unless(defined$project);2533# some views should link to OPML, or to generic project feed,2534# or don't have specific feed yet (so they should use generic)2535return if(!$action||$action=~/^(?:tags|heads|forks|tag|search)$/x);25362537my$branch;2538# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2539# from tag links; this also makes possible to detect branch links2540if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2541(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2542$branch=$1;2543}2544# find log type for feed description (title)2545my$type='log';2546if(defined$file_name) {2547$type="history of$file_name";2548$type.="/"if($actioneq'tree');2549$type.=" on '$branch'"if(defined$branch);2550}else{2551$type="log of$branch"if(defined$branch);2552}25532554$res{-title} =$type;2555$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2556$res{'file_name'} =$file_name;25572558return%res;2559}25602561## ----------------------------------------------------------------------2562## git utility subroutines, invoking git commands25632564# returns path to the core git executable and the --git-dir parameter as list2565sub git_cmd {2566$number_of_git_cmds++;2567return$GIT,'--git-dir='.$git_dir;2568}25692570# quote the given arguments for passing them to the shell2571# quote_command("command", "arg 1", "arg with ' and ! characters")2572# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2573# Try to avoid using this function wherever possible.2574sub quote_command {2575returnjoin(' ',2576map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2577}25782579# get HEAD ref of given project as hash2580sub git_get_head_hash {2581return git_get_full_hash(shift,'HEAD');2582}25832584sub git_get_full_hash {2585return git_get_hash(@_);2586}25872588sub git_get_short_hash {2589return git_get_hash(@_,'--short=7');2590}25912592sub git_get_hash {2593my($project,$hash,@options) =@_;2594my$o_git_dir=$git_dir;2595my$retval=undef;2596$git_dir="$projectroot/$project";2597if(open my$fd,'-|', git_cmd(),'rev-parse',2598'--verify','-q',@options,$hash) {2599$retval= <$fd>;2600chomp$retvalifdefined$retval;2601close$fd;2602}2603if(defined$o_git_dir) {2604$git_dir=$o_git_dir;2605}2606return$retval;2607}26082609# get type of given object2610sub git_get_type {2611my$hash=shift;26122613open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2614my$type= <$fd>;2615close$fdorreturn;2616chomp$type;2617return$type;2618}26192620# repository configuration2621our$config_file='';2622our%config;26232624# store multiple values for single key as anonymous array reference2625# single values stored directly in the hash, not as [ <value> ]2626sub hash_set_multi {2627my($hash,$key,$value) =@_;26282629if(!exists$hash->{$key}) {2630$hash->{$key} =$value;2631}elsif(!ref$hash->{$key}) {2632$hash->{$key} = [$hash->{$key},$value];2633}else{2634push@{$hash->{$key}},$value;2635}2636}26372638# return hash of git project configuration2639# optionally limited to some section, e.g. 'gitweb'2640sub git_parse_project_config {2641my$section_regexp=shift;2642my%config;26432644local$/="\0";26452646open my$fh,"-|", git_cmd(),"config",'-z','-l',2647orreturn;26482649while(my$keyval= <$fh>) {2650chomp$keyval;2651my($key,$value) =split(/\n/,$keyval,2);26522653 hash_set_multi(\%config,$key,$value)2654if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2655}2656close$fh;26572658return%config;2659}26602661# convert config value to boolean: 'true' or 'false'2662# no value, number > 0, 'true' and 'yes' values are true2663# rest of values are treated as false (never as error)2664sub config_to_bool {2665my$val=shift;26662667return1if!defined$val;# section.key26682669# strip leading and trailing whitespace2670$val=~s/^\s+//;2671$val=~s/\s+$//;26722673return(($val=~/^\d+$/&&$val) ||# section.key = 12674($val=~/^(?:true|yes)$/i));# section.key = true2675}26762677# convert config value to simple decimal number2678# an optional value suffix of 'k', 'm', or 'g' will cause the value2679# to be multiplied by 1024, 1048576, or 10737418242680sub config_to_int {2681my$val=shift;26822683# strip leading and trailing whitespace2684$val=~s/^\s+//;2685$val=~s/\s+$//;26862687if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2688$unit=lc($unit);2689# unknown unit is treated as 12690return$num* ($uniteq'g'?1073741824:2691$uniteq'm'?1048576:2692$uniteq'k'?1024:1);2693}2694return$val;2695}26962697# convert config value to array reference, if needed2698sub config_to_multi {2699my$val=shift;27002701returnref($val) ?$val: (defined($val) ? [$val] : []);2702}27032704sub git_get_project_config {2705my($key,$type) =@_;27062707return unlessdefined$git_dir;27082709# key sanity check2710return unless($key);2711# only subsection, if exists, is case sensitive,2712# and not lowercased by 'git config -z -l'2713if(my($hi,$mi,$lo) = ($key=~/^([^.]*)\.(.*)\.([^.]*)$/)) {2714$lo=~s/_//g;2715$key=join(".",lc($hi),$mi,lc($lo));2716return if($lo=~/\W/||$hi=~/\W/);2717}else{2718$key=lc($key);2719$key=~s/_//g;2720return if($key=~/\W/);2721}2722$key=~s/^gitweb\.//;27232724# type sanity check2725if(defined$type) {2726$type=~s/^--//;2727$type=undef2728unless($typeeq'bool'||$typeeq'int');2729}27302731# get config2732if(!defined$config_file||2733$config_filene"$git_dir/config") {2734%config= git_parse_project_config('gitweb');2735$config_file="$git_dir/config";2736}27372738# check if config variable (key) exists2739return unlessexists$config{"gitweb.$key"};27402741# ensure given type2742if(!defined$type) {2743return$config{"gitweb.$key"};2744}elsif($typeeq'bool') {2745# backward compatibility: 'git config --bool' returns true/false2746return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2747}elsif($typeeq'int') {2748return config_to_int($config{"gitweb.$key"});2749}2750return$config{"gitweb.$key"};2751}27522753# get hash of given path at given ref2754sub git_get_hash_by_path {2755my$base=shift;2756my$path=shift||returnundef;2757my$type=shift;27582759$path=~ s,/+$,,;27602761open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2762or die_error(500,"Open git-ls-tree failed");2763my$line= <$fd>;2764close$fdorreturnundef;27652766if(!defined$line) {2767# there is no tree or hash given by $path at $base2768returnundef;2769}27702771#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2772$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2773if(defined$type&&$typene$2) {2774# type doesn't match2775returnundef;2776}2777return$3;2778}27792780# get path of entry with given hash at given tree-ish (ref)2781# used to get 'from' filename for combined diff (merge commit) for renames2782sub git_get_path_by_hash {2783my$base=shift||return;2784my$hash=shift||return;27852786local$/="\0";27872788open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2789orreturnundef;2790while(my$line= <$fd>) {2791chomp$line;27922793#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2794#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2795if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2796close$fd;2797return$1;2798}2799}2800close$fd;2801returnundef;2802}28032804## ......................................................................2805## git utility functions, directly accessing git repository28062807# get the value of config variable either from file named as the variable2808# itself in the repository ($GIT_DIR/$name file), or from gitweb.$name2809# configuration variable in the repository config file.2810sub git_get_file_or_project_config {2811my($path,$name) =@_;28122813$git_dir="$projectroot/$path";2814open my$fd,'<',"$git_dir/$name"2815orreturn git_get_project_config($name);2816my$conf= <$fd>;2817close$fd;2818if(defined$conf) {2819chomp$conf;2820}2821return$conf;2822}28232824sub git_get_project_description {2825my$path=shift;2826return git_get_file_or_project_config($path,'description');2827}28282829sub git_get_project_category {2830my$path=shift;2831return git_get_file_or_project_config($path,'category');2832}283328342835# supported formats:2836# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2837# - if its contents is a number, use it as tag weight,2838# - otherwise add a tag with weight 12839# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2840# the same value multiple times increases tag weight2841# * `gitweb.ctag' multi-valued repo config variable2842sub git_get_project_ctags {2843my$project=shift;2844my$ctags= {};28452846$git_dir="$projectroot/$project";2847if(opendir my$dh,"$git_dir/ctags") {2848my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2849foreachmy$tagfile(@files) {2850open my$ct,'<',$tagfile2851ornext;2852my$val= <$ct>;2853chomp$valif$val;2854close$ct;28552856(my$ctag=$tagfile) =~ s#.*/##;2857if($val=~/^\d+$/) {2858$ctags->{$ctag} =$val;2859}else{2860$ctags->{$ctag} =1;2861}2862}2863closedir$dh;28642865}elsif(open my$fh,'<',"$git_dir/ctags") {2866while(my$line= <$fh>) {2867chomp$line;2868$ctags->{$line}++if$line;2869}2870close$fh;28712872}else{2873my$taglist= config_to_multi(git_get_project_config('ctag'));2874foreachmy$tag(@$taglist) {2875$ctags->{$tag}++;2876}2877}28782879return$ctags;2880}28812882# return hash, where keys are content tags ('ctags'),2883# and values are sum of weights of given tag in every project2884sub git_gather_all_ctags {2885my$projects=shift;2886my$ctags= {};28872888foreachmy$p(@$projects) {2889foreachmy$ct(keys%{$p->{'ctags'}}) {2890$ctags->{$ct} +=$p->{'ctags'}->{$ct};2891}2892}28932894return$ctags;2895}28962897sub git_populate_project_tagcloud {2898my$ctags=shift;28992900# First, merge different-cased tags; tags vote on casing2901my%ctags_lc;2902foreach(keys%$ctags) {2903$ctags_lc{lc$_}->{count} +=$ctags->{$_};2904if(not$ctags_lc{lc$_}->{topcount}2905or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2906$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2907$ctags_lc{lc$_}->{topname} =$_;2908}2909}29102911my$cloud;2912my$matched=$input_params{'ctag'};2913if(eval{require HTML::TagCloud;1; }) {2914$cloud= HTML::TagCloud->new;2915foreachmy$ctag(sort keys%ctags_lc) {2916# Pad the title with spaces so that the cloud looks2917# less crammed.2918my$title= esc_html($ctags_lc{$ctag}->{topname});2919$title=~s/ / /g;2920$title=~s/^/ /g;2921$title=~s/$/ /g;2922if(defined$matched&&$matchedeq$ctag) {2923$title=qq(<span class="match">$title</span>);2924}2925$cloud->add($title, href(project=>undef, ctag=>$ctag),2926$ctags_lc{$ctag}->{count});2927}2928}else{2929$cloud= {};2930foreachmy$ctag(keys%ctags_lc) {2931my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2932if(defined$matched&&$matchedeq$ctag) {2933$title=qq(<span class="match">$title</span>);2934}2935$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};2936$cloud->{$ctag}{ctag} =2937$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);2938}2939}2940return$cloud;2941}29422943sub git_show_project_tagcloud {2944my($cloud,$count) =@_;2945if(ref$cloudeq'HTML::TagCloud') {2946return$cloud->html_and_css($count);2947}else{2948my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;2949return2950'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.2951join(', ',map{2952$cloud->{$_}->{'ctag'}2953}splice(@tags,0,$count)) .2954'</div>';2955}2956}29572958sub git_get_project_url_list {2959my$path=shift;29602961$git_dir="$projectroot/$path";2962open my$fd,'<',"$git_dir/cloneurl"2963orreturnwantarray?2964@{ config_to_multi(git_get_project_config('url')) } :2965 config_to_multi(git_get_project_config('url'));2966my@git_project_url_list=map{chomp;$_} <$fd>;2967close$fd;29682969returnwantarray?@git_project_url_list: \@git_project_url_list;2970}29712972sub git_get_projects_list {2973my$filter=shift||'';2974my$paranoid=shift;2975my@list;29762977if(-d $projects_list) {2978# search in directory2979my$dir=$projects_list;2980# remove the trailing "/"2981$dir=~s!/+$!!;2982my$pfxlen=length("$dir");2983my$pfxdepth= ($dir=~tr!/!!);2984# when filtering, search only given subdirectory2985if($filter&& !$paranoid) {2986$dir.="/$filter";2987$dir=~s!/+$!!;2988}29892990 File::Find::find({2991 follow_fast =>1,# follow symbolic links2992 follow_skip =>2,# ignore duplicates2993 dangling_symlinks =>0,# ignore dangling symlinks, silently2994 wanted =>sub{2995# global variables2996our$project_maxdepth;2997our$projectroot;2998# skip project-list toplevel, if we get it.2999return if(m!^[/.]$!);3000# only directories can be git repositories3001return unless(-d $_);3002# don't traverse too deep (Find is super slow on os x)3003# $project_maxdepth excludes depth of $projectroot3004if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {3005$File::Find::prune =1;3006return;3007}30083009my$path=substr($File::Find::name,$pfxlen+1);3010# paranoidly only filter here3011if($paranoid&&$filter&&$path!~m!^\Q$filter\E/!) {3012next;3013}3014# we check related file in $projectroot3015if(check_export_ok("$projectroot/$path")) {3016push@list, { path =>$path};3017$File::Find::prune =1;3018}3019},3020},"$dir");30213022}elsif(-f $projects_list) {3023# read from file(url-encoded):3024# 'git%2Fgit.git Linus+Torvalds'3025# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'3026# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'3027open my$fd,'<',$projects_listorreturn;3028 PROJECT:3029while(my$line= <$fd>) {3030chomp$line;3031my($path,$owner) =split' ',$line;3032$path= unescape($path);3033$owner= unescape($owner);3034if(!defined$path) {3035next;3036}3037# if $filter is rpovided, check if $path begins with $filter3038if($filter&&$path!~m!^\Q$filter\E/!) {3039next;3040}3041if(check_export_ok("$projectroot/$path")) {3042my$pr= {3043 path =>$path3044};3045if($owner) {3046$pr->{'owner'} = to_utf8($owner);3047}3048push@list,$pr;3049}3050}3051close$fd;3052}3053return@list;3054}30553056# written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)3057# as side effects it sets 'forks' field to list of forks for forked projects3058sub filter_forks_from_projects_list {3059my$projects=shift;30603061my%trie;# prefix tree of directories (path components)3062# generate trie out of those directories that might contain forks3063foreachmy$pr(@$projects) {3064my$path=$pr->{'path'};3065$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory3066next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'3067next unless($path);# skip '.git' repository: tests, git-instaweb3068next unless(-d "$projectroot/$path");# containing directory exists3069$pr->{'forks'} = [];# there can be 0 or more forks of project30703071# add to trie3072my@dirs=split('/',$path);3073# walk the trie, until either runs out of components or out of trie3074my$ref= \%trie;3075while(scalar@dirs&&3076exists($ref->{$dirs[0]})) {3077$ref=$ref->{shift@dirs};3078}3079# create rest of trie structure from rest of components3080foreachmy$dir(@dirs) {3081$ref=$ref->{$dir} = {};3082}3083# create end marker, store $pr as a data3084$ref->{''} =$prif(!exists$ref->{''});3085}30863087# filter out forks, by finding shortest prefix match for paths3088my@filtered;3089 PROJECT:3090foreachmy$pr(@$projects) {3091# trie lookup3092my$ref= \%trie;3093 DIR:3094foreachmy$dir(split('/',$pr->{'path'})) {3095if(exists$ref->{''}) {3096# found [shortest] prefix, is a fork - skip it3097push@{$ref->{''}{'forks'}},$pr;3098next PROJECT;3099}3100if(!exists$ref->{$dir}) {3101# not in trie, cannot have prefix, not a fork3102push@filtered,$pr;3103next PROJECT;3104}3105# If the dir is there, we just walk one step down the trie.3106$ref=$ref->{$dir};3107}3108# we ran out of trie3109# (shouldn't happen: it's either no match, or end marker)3110push@filtered,$pr;3111}31123113return@filtered;3114}31153116# note: fill_project_list_info must be run first,3117# for 'descr_long' and 'ctags' to be filled3118sub search_projects_list {3119my($projlist,%opts) =@_;3120my$tagfilter=$opts{'tagfilter'};3121my$search_re=$opts{'search_regexp'};31223123return@$projlist3124unless($tagfilter||$search_re);31253126# searching projects require filling to be run before it;3127 fill_project_list_info($projlist,3128$tagfilter?'ctags': (),3129$search_re? ('path','descr') : ());3130my@projects;3131 PROJECT:3132foreachmy$pr(@$projlist) {31333134if($tagfilter) {3135next unlessref($pr->{'ctags'})eq'HASH';3136next unless3137grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};3138}31393140if($search_re) {3141next unless3142$pr->{'path'} =~/$search_re/||3143$pr->{'descr_long'} =~/$search_re/;3144}31453146push@projects,$pr;3147}31483149return@projects;3150}31513152our$gitweb_project_owner=undef;3153sub git_get_project_list_from_file {31543155return if(defined$gitweb_project_owner);31563157$gitweb_project_owner= {};3158# read from file (url-encoded):3159# 'git%2Fgit.git Linus+Torvalds'3160# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'3161# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'3162if(-f $projects_list) {3163open(my$fd,'<',$projects_list);3164while(my$line= <$fd>) {3165chomp$line;3166my($pr,$ow) =split' ',$line;3167$pr= unescape($pr);3168$ow= unescape($ow);3169$gitweb_project_owner->{$pr} = to_utf8($ow);3170}3171close$fd;3172}3173}31743175sub git_get_project_owner {3176my$project=shift;3177my$owner;31783179returnundefunless$project;3180$git_dir="$projectroot/$project";31813182if(!defined$gitweb_project_owner) {3183 git_get_project_list_from_file();3184}31853186if(exists$gitweb_project_owner->{$project}) {3187$owner=$gitweb_project_owner->{$project};3188}3189if(!defined$owner){3190$owner= git_get_project_config('owner');3191}3192if(!defined$owner) {3193$owner= get_file_owner("$git_dir");3194}31953196return$owner;3197}31983199sub git_get_last_activity {3200my($path) =@_;3201my$fd;32023203$git_dir="$projectroot/$path";3204open($fd,"-|", git_cmd(),'for-each-ref',3205'--format=%(committer)',3206'--sort=-committerdate',3207'--count=1',3208'refs/heads')orreturn;3209my$most_recent= <$fd>;3210close$fdorreturn;3211if(defined$most_recent&&3212$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {3213my$timestamp=$1;3214my$age=time-$timestamp;3215return($age, age_string($age));3216}3217return(undef,undef);3218}32193220# Implementation note: when a single remote is wanted, we cannot use 'git3221# remote show -n' because that command always work (assuming it's a remote URL3222# if it's not defined), and we cannot use 'git remote show' because that would3223# try to make a network roundtrip. So the only way to find if that particular3224# remote is defined is to walk the list provided by 'git remote -v' and stop if3225# and when we find what we want.3226sub git_get_remotes_list {3227my$wanted=shift;3228my%remotes= ();32293230open my$fd,'-|', git_cmd(),'remote','-v';3231return unless$fd;3232while(my$remote= <$fd>) {3233chomp$remote;3234$remote=~s!\t(.*?)\s+\((\w+)\)$!!;3235next if$wantedand not$remoteeq$wanted;3236my($url,$key) = ($1,$2);32373238$remotes{$remote} ||= {'heads'=> () };3239$remotes{$remote}{$key} =$url;3240}3241close$fdorreturn;3242returnwantarray?%remotes: \%remotes;3243}32443245# Takes a hash of remotes as first parameter and fills it by adding the3246# available remote heads for each of the indicated remotes.3247sub fill_remote_heads {3248my$remotes=shift;3249my@heads=map{"remotes/$_"}keys%$remotes;3250my@remoteheads= git_get_heads_list(undef,@heads);3251foreachmy$remote(keys%$remotes) {3252$remotes->{$remote}{'heads'} = [grep{3253$_->{'name'} =~s!^$remote/!!3254}@remoteheads];3255}3256}32573258sub git_get_references {3259my$type=shift||"";3260my%refs;3261# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113262# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3263open my$fd,"-|", git_cmd(),"show-ref","--dereference",3264($type? ("--","refs/$type") : ())# use -- <pattern> if $type3265orreturn;32663267while(my$line= <$fd>) {3268chomp$line;3269if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3270if(defined$refs{$1}) {3271push@{$refs{$1}},$2;3272}else{3273$refs{$1} = [$2];3274}3275}3276}3277close$fdorreturn;3278return \%refs;3279}32803281sub git_get_rev_name_tags {3282my$hash=shift||returnundef;32833284open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3285orreturn;3286my$name_rev= <$fd>;3287close$fd;32883289if($name_rev=~ m|^$hash tags/(.*)$|) {3290return$1;3291}else{3292# catches also '$hash undefined' output3293returnundef;3294}3295}32963297## ----------------------------------------------------------------------3298## parse to hash functions32993300sub parse_date {3301my$epoch=shift;3302my$tz=shift||"-0000";33033304my%date;3305my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3306my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3307my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3308$date{'hour'} =$hour;3309$date{'minute'} =$min;3310$date{'mday'} =$mday;3311$date{'day'} =$days[$wday];3312$date{'month'} =$months[$mon];3313$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3314$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3315$date{'mday-time'} =sprintf"%d%s%02d:%02d",3316$mday,$months[$mon],$hour,$min;3317$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",33181900+$year,1+$mon,$mday,$hour,$min,$sec;33193320my($tz_sign,$tz_hour,$tz_min) =3321($tz=~m/^([-+])(\d\d)(\d\d)$/);3322$tz_sign= ($tz_signeq'-'? -1: +1);3323my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3324($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3325$date{'hour_local'} =$hour;3326$date{'minute_local'} =$min;3327$date{'tz_local'} =$tz;3328$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",33291900+$year,$mon+1,$mday,3330$hour,$min,$sec,$tz);3331return%date;3332}33333334sub parse_tag {3335my$tag_id=shift;3336my%tag;3337my@comment;33383339open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3340$tag{'id'} =$tag_id;3341while(my$line= <$fd>) {3342chomp$line;3343if($line=~m/^object ([0-9a-fA-F]{40})$/) {3344$tag{'object'} =$1;3345}elsif($line=~m/^type (.+)$/) {3346$tag{'type'} =$1;3347}elsif($line=~m/^tag (.+)$/) {3348$tag{'name'} =$1;3349}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3350$tag{'author'} =$1;3351$tag{'author_epoch'} =$2;3352$tag{'author_tz'} =$3;3353if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3354$tag{'author_name'} =$1;3355$tag{'author_email'} =$2;3356}else{3357$tag{'author_name'} =$tag{'author'};3358}3359}elsif($line=~m/--BEGIN/) {3360push@comment,$line;3361last;3362}elsif($lineeq"") {3363last;3364}3365}3366push@comment, <$fd>;3367$tag{'comment'} = \@comment;3368close$fdorreturn;3369if(!defined$tag{'name'}) {3370return3371};3372return%tag3373}33743375sub parse_commit_text {3376my($commit_text,$withparents) =@_;3377my@commit_lines=split'\n',$commit_text;3378my%co;33793380pop@commit_lines;# Remove '\0'33813382if(!@commit_lines) {3383return;3384}33853386my$header=shift@commit_lines;3387if($header!~m/^[0-9a-fA-F]{40}/) {3388return;3389}3390($co{'id'},my@parents) =split' ',$header;3391while(my$line=shift@commit_lines) {3392last if$lineeq"\n";3393if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3394$co{'tree'} =$1;3395}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3396push@parents,$1;3397}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3398$co{'author'} = to_utf8($1);3399$co{'author_epoch'} =$2;3400$co{'author_tz'} =$3;3401if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3402$co{'author_name'} =$1;3403$co{'author_email'} =$2;3404}else{3405$co{'author_name'} =$co{'author'};3406}3407}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3408$co{'committer'} = to_utf8($1);3409$co{'committer_epoch'} =$2;3410$co{'committer_tz'} =$3;3411if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3412$co{'committer_name'} =$1;3413$co{'committer_email'} =$2;3414}else{3415$co{'committer_name'} =$co{'committer'};3416}3417}3418}3419if(!defined$co{'tree'}) {3420return;3421};3422$co{'parents'} = \@parents;3423$co{'parent'} =$parents[0];34243425foreachmy$title(@commit_lines) {3426$title=~s/^ //;3427if($titlene"") {3428$co{'title'} = chop_str($title,80,5);3429# remove leading stuff of merges to make the interesting part visible3430if(length($title) >50) {3431$title=~s/^Automatic //;3432$title=~s/^merge (of|with) /Merge ... /i;3433if(length($title) >50) {3434$title=~s/(http|rsync):\/\///;3435}3436if(length($title) >50) {3437$title=~s/(master|www|rsync)\.//;3438}3439if(length($title) >50) {3440$title=~s/kernel.org:?//;3441}3442if(length($title) >50) {3443$title=~s/\/pub\/scm//;3444}3445}3446$co{'title_short'} = chop_str($title,50,5);3447last;3448}3449}3450if(!defined$co{'title'} ||$co{'title'}eq"") {3451$co{'title'} =$co{'title_short'} ='(no commit message)';3452}3453# remove added spaces3454foreachmy$line(@commit_lines) {3455$line=~s/^ //;3456}3457$co{'comment'} = \@commit_lines;34583459my$age=time-$co{'committer_epoch'};3460$co{'age'} =$age;3461$co{'age_string'} = age_string($age);3462my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3463if($age>60*60*24*7*2) {3464$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3465$co{'age_string_age'} =$co{'age_string'};3466}else{3467$co{'age_string_date'} =$co{'age_string'};3468$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3469}3470return%co;3471}34723473sub parse_commit {3474my($commit_id) =@_;3475my%co;34763477local$/="\0";34783479open my$fd,"-|", git_cmd(),"rev-list",3480"--parents",3481"--header",3482"--max-count=1",3483$commit_id,3484"--",3485or die_error(500,"Open git-rev-list failed");3486%co= parse_commit_text(<$fd>,1);3487close$fd;34883489return%co;3490}34913492sub parse_commits {3493my($commit_id,$maxcount,$skip,$filename,@args) =@_;3494my@cos;34953496$maxcount||=1;3497$skip||=0;34983499local$/="\0";35003501open my$fd,"-|", git_cmd(),"rev-list",3502"--header",3503@args,3504("--max-count=".$maxcount),3505("--skip=".$skip),3506@extra_options,3507$commit_id,3508"--",3509($filename? ($filename) : ())3510or die_error(500,"Open git-rev-list failed");3511while(my$line= <$fd>) {3512my%co= parse_commit_text($line);3513push@cos, \%co;3514}3515close$fd;35163517returnwantarray?@cos: \@cos;3518}35193520# parse line of git-diff-tree "raw" output3521sub parse_difftree_raw_line {3522my$line=shift;3523my%res;35243525# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3526# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3527if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3528$res{'from_mode'} =$1;3529$res{'to_mode'} =$2;3530$res{'from_id'} =$3;3531$res{'to_id'} =$4;3532$res{'status'} =$5;3533$res{'similarity'} =$6;3534if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3535($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3536}else{3537$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3538}3539}3540# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3541# combined diff (for merge commit)3542elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3543$res{'nparents'} =length($1);3544$res{'from_mode'} = [split(' ',$2) ];3545$res{'to_mode'} =pop@{$res{'from_mode'}};3546$res{'from_id'} = [split(' ',$3) ];3547$res{'to_id'} =pop@{$res{'from_id'}};3548$res{'status'} = [split('',$4) ];3549$res{'to_file'} = unquote($5);3550}3551# 'c512b523472485aef4fff9e57b229d9d243c967f'3552elsif($line=~m/^([0-9a-fA-F]{40})$/) {3553$res{'commit'} =$1;3554}35553556returnwantarray?%res: \%res;3557}35583559# wrapper: return parsed line of git-diff-tree "raw" output3560# (the argument might be raw line, or parsed info)3561sub parsed_difftree_line {3562my$line_or_ref=shift;35633564if(ref($line_or_ref)eq"HASH") {3565# pre-parsed (or generated by hand)3566return$line_or_ref;3567}else{3568return parse_difftree_raw_line($line_or_ref);3569}3570}35713572# parse line of git-ls-tree output3573sub parse_ls_tree_line {3574my$line=shift;3575my%opts=@_;3576my%res;35773578if($opts{'-l'}) {3579#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3580$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;35813582$res{'mode'} =$1;3583$res{'type'} =$2;3584$res{'hash'} =$3;3585$res{'size'} =$4;3586if($opts{'-z'}) {3587$res{'name'} =$5;3588}else{3589$res{'name'} = unquote($5);3590}3591}else{3592#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3593$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;35943595$res{'mode'} =$1;3596$res{'type'} =$2;3597$res{'hash'} =$3;3598if($opts{'-z'}) {3599$res{'name'} =$4;3600}else{3601$res{'name'} = unquote($4);3602}3603}36043605returnwantarray?%res: \%res;3606}36073608# generates _two_ hashes, references to which are passed as 2 and 3 argument3609sub parse_from_to_diffinfo {3610my($diffinfo,$from,$to,@parents) =@_;36113612if($diffinfo->{'nparents'}) {3613# combined diff3614$from->{'file'} = [];3615$from->{'href'} = [];3616 fill_from_file_info($diffinfo,@parents)3617unlessexists$diffinfo->{'from_file'};3618for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3619$from->{'file'}[$i] =3620defined$diffinfo->{'from_file'}[$i] ?3621$diffinfo->{'from_file'}[$i] :3622$diffinfo->{'to_file'};3623if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3624$from->{'href'}[$i] = href(action=>"blob",3625 hash_base=>$parents[$i],3626 hash=>$diffinfo->{'from_id'}[$i],3627 file_name=>$from->{'file'}[$i]);3628}else{3629$from->{'href'}[$i] =undef;3630}3631}3632}else{3633# ordinary (not combined) diff3634$from->{'file'} =$diffinfo->{'from_file'};3635if($diffinfo->{'status'}ne"A") {# not new (added) file3636$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3637 hash=>$diffinfo->{'from_id'},3638 file_name=>$from->{'file'});3639}else{3640delete$from->{'href'};3641}3642}36433644$to->{'file'} =$diffinfo->{'to_file'};3645if(!is_deleted($diffinfo)) {# file exists in result3646$to->{'href'} = href(action=>"blob", hash_base=>$hash,3647 hash=>$diffinfo->{'to_id'},3648 file_name=>$to->{'file'});3649}else{3650delete$to->{'href'};3651}3652}36533654## ......................................................................3655## parse to array of hashes functions36563657sub git_get_heads_list {3658my($limit,@classes) =@_;3659@classes= ('heads')unless@classes;3660my@patterns=map{"refs/$_"}@classes;3661my@headslist;36623663open my$fd,'-|', git_cmd(),'for-each-ref',3664($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3665'--format=%(objectname) %(refname) %(subject)%00%(committer)',3666@patterns3667orreturn;3668while(my$line= <$fd>) {3669my%ref_item;36703671chomp$line;3672my($refinfo,$committerinfo) =split(/\0/,$line);3673my($hash,$name,$title) =split(' ',$refinfo,3);3674my($committer,$epoch,$tz) =3675($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3676$ref_item{'fullname'} =$name;3677$name=~s!^refs/(?:head|remote)s/!!;36783679$ref_item{'name'} =$name;3680$ref_item{'id'} =$hash;3681$ref_item{'title'} =$title||'(no commit message)';3682$ref_item{'epoch'} =$epoch;3683if($epoch) {3684$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3685}else{3686$ref_item{'age'} ="unknown";3687}36883689push@headslist, \%ref_item;3690}3691close$fd;36923693returnwantarray?@headslist: \@headslist;3694}36953696sub git_get_tags_list {3697my$limit=shift;3698my@tagslist;36993700open my$fd,'-|', git_cmd(),'for-each-ref',3701($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3702'--format=%(objectname) %(objecttype) %(refname) '.3703'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3704'refs/tags'3705orreturn;3706while(my$line= <$fd>) {3707my%ref_item;37083709chomp$line;3710my($refinfo,$creatorinfo) =split(/\0/,$line);3711my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3712my($creator,$epoch,$tz) =3713($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3714$ref_item{'fullname'} =$name;3715$name=~s!^refs/tags/!!;37163717$ref_item{'type'} =$type;3718$ref_item{'id'} =$id;3719$ref_item{'name'} =$name;3720if($typeeq"tag") {3721$ref_item{'subject'} =$title;3722$ref_item{'reftype'} =$reftype;3723$ref_item{'refid'} =$refid;3724}else{3725$ref_item{'reftype'} =$type;3726$ref_item{'refid'} =$id;3727}37283729if($typeeq"tag"||$typeeq"commit") {3730$ref_item{'epoch'} =$epoch;3731if($epoch) {3732$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3733}else{3734$ref_item{'age'} ="unknown";3735}3736}37373738push@tagslist, \%ref_item;3739}3740close$fd;37413742returnwantarray?@tagslist: \@tagslist;3743}37443745## ----------------------------------------------------------------------3746## filesystem-related functions37473748sub get_file_owner {3749my$path=shift;37503751my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3752my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3753if(!defined$gcos) {3754returnundef;3755}3756my$owner=$gcos;3757$owner=~s/[,;].*$//;3758return to_utf8($owner);3759}37603761# assume that file exists3762sub insert_file {3763my$filename=shift;37643765open my$fd,'<',$filename;3766print map{ to_utf8($_) } <$fd>;3767close$fd;3768}37693770## ......................................................................3771## mimetype related functions37723773sub mimetype_guess_file {3774my$filename=shift;3775my$mimemap=shift;3776-r $mimemaporreturnundef;37773778my%mimemap;3779open(my$mh,'<',$mimemap)orreturnundef;3780while(<$mh>) {3781next ifm/^#/;# skip comments3782my($mimetype,@exts) =split(/\s+/);3783foreachmy$ext(@exts) {3784$mimemap{$ext} =$mimetype;3785}3786}3787close($mh);37883789$filename=~/\.([^.]*)$/;3790return$mimemap{$1};3791}37923793sub mimetype_guess {3794my$filename=shift;3795my$mime;3796$filename=~/\./orreturnundef;37973798if($mimetypes_file) {3799my$file=$mimetypes_file;3800if($file!~m!^/!) {# if it is relative path3801# it is relative to project3802$file="$projectroot/$project/$file";3803}3804$mime= mimetype_guess_file($filename,$file);3805}3806$mime||= mimetype_guess_file($filename,'/etc/mime.types');3807return$mime;3808}38093810sub blob_mimetype {3811my$fd=shift;3812my$filename=shift;38133814if($filename) {3815my$mime= mimetype_guess($filename);3816$mimeandreturn$mime;3817}38183819# just in case3820return$default_blob_plain_mimetypeunless$fd;38213822if(-T $fd) {3823return'text/plain';3824}elsif(!$filename) {3825return'application/octet-stream';3826}elsif($filename=~m/\.png$/i) {3827return'image/png';3828}elsif($filename=~m/\.gif$/i) {3829return'image/gif';3830}elsif($filename=~m/\.jpe?g$/i) {3831return'image/jpeg';3832}else{3833return'application/octet-stream';3834}3835}38363837sub blob_contenttype {3838my($fd,$file_name,$type) =@_;38393840$type||= blob_mimetype($fd,$file_name);3841if($typeeq'text/plain'&&defined$default_text_plain_charset) {3842$type.="; charset=$default_text_plain_charset";3843}38443845return$type;3846}38473848# guess file syntax for syntax highlighting; return undef if no highlighting3849# the name of syntax can (in the future) depend on syntax highlighter used3850sub guess_file_syntax {3851my($highlight,$mimetype,$file_name) =@_;3852returnundefunless($highlight&&defined$file_name);3853my$basename= basename($file_name,'.in');3854return$highlight_basename{$basename}3855ifexists$highlight_basename{$basename};38563857$basename=~/\.([^.]*)$/;3858my$ext=$1orreturnundef;3859return$highlight_ext{$ext}3860ifexists$highlight_ext{$ext};38613862returnundef;3863}38643865# run highlighter and return FD of its output,3866# or return original FD if no highlighting3867sub run_highlighter {3868my($fd,$highlight,$syntax) =@_;3869return$fdunless($highlight&&defined$syntax);38703871close$fd;3872open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3873 quote_command($highlight_bin).3874" --replace-tabs=8 --fragment --syntax$syntax|"3875or die_error(500,"Couldn't open file or run syntax highlighter");3876return$fd;3877}38783879## ======================================================================3880## functions printing HTML: header, footer, error page38813882sub get_page_title {3883my$title= to_utf8($site_name);38843885unless(defined$project) {3886if(defined$project_filter) {3887$title.=" - projects in '". esc_path($project_filter) ."'";3888}3889return$title;3890}3891$title.=" - ". to_utf8($project);38923893return$titleunless(defined$action);3894$title.="/$action";# $action is US-ASCII (7bit ASCII)38953896return$titleunless(defined$file_name);3897$title.=" - ". esc_path($file_name);3898if($actioneq"tree"&&$file_name!~ m|/$|) {3899$title.="/";3900}39013902return$title;3903}39043905sub get_content_type_html {3906# require explicit support from the UA if we are to send the page as3907# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3908# we have to do this because MSIE sometimes globs '*/*', pretending to3909# support xhtml+xml but choking when it gets what it asked for.3910if(defined$cgi->http('HTTP_ACCEPT') &&3911$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3912$cgi->Accept('application/xhtml+xml') !=0) {3913return'application/xhtml+xml';3914}else{3915return'text/html';3916}3917}39183919sub print_feed_meta {3920if(defined$project) {3921my%href_params= get_feed_info();3922if(!exists$href_params{'-title'}) {3923$href_params{'-title'} ='log';3924}39253926foreachmy$format(qw(RSS Atom)) {3927my$type=lc($format);3928my%link_attr= (3929'-rel'=>'alternate',3930'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3931'-type'=>"application/$type+xml"3932);39333934$href_params{'extra_options'} =undef;3935$href_params{'action'} =$type;3936$link_attr{'-href'} = href(%href_params);3937print"<link ".3938"rel=\"$link_attr{'-rel'}\"".3939"title=\"$link_attr{'-title'}\"".3940"href=\"$link_attr{'-href'}\"".3941"type=\"$link_attr{'-type'}\"".3942"/>\n";39433944$href_params{'extra_options'} ='--no-merges';3945$link_attr{'-href'} = href(%href_params);3946$link_attr{'-title'} .=' (no merges)';3947print"<link ".3948"rel=\"$link_attr{'-rel'}\"".3949"title=\"$link_attr{'-title'}\"".3950"href=\"$link_attr{'-href'}\"".3951"type=\"$link_attr{'-type'}\"".3952"/>\n";3953}39543955}else{3956printf('<link rel="alternate" title="%sprojects list" '.3957'href="%s" type="text/plain; charset=utf-8" />'."\n",3958 esc_attr($site_name), href(project=>undef, action=>"project_index"));3959printf('<link rel="alternate" title="%sprojects feeds" '.3960'href="%s" type="text/x-opml" />'."\n",3961 esc_attr($site_name), href(project=>undef, action=>"opml"));3962}3963}39643965sub print_header_links {3966my$status=shift;39673968# print out each stylesheet that exist, providing backwards capability3969# for those people who defined $stylesheet in a config file3970if(defined$stylesheet) {3971print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3972}else{3973foreachmy$stylesheet(@stylesheets) {3974next unless$stylesheet;3975print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3976}3977}3978 print_feed_meta()3979if($statuseq'200 OK');3980if(defined$favicon) {3981printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);3982}3983}39843985sub print_nav_breadcrumbs_path {3986my$dirprefix=undef;3987while(my$part=shift) {3988$dirprefix.="/"ifdefined$dirprefix;3989$dirprefix.=$part;3990print$cgi->a({-href => href(project =>undef,3991 project_filter =>$dirprefix,3992 action =>"project_list")},3993 esc_html($part)) ." / ";3994}3995}39963997sub print_nav_breadcrumbs {3998my%opts=@_;39994000formy$crumb(@extra_breadcrumbs, [$home_link_str=>$home_link]) {4001print$cgi->a({-href => esc_url($crumb->[1])},$crumb->[0]) ." / ";4002}4003if(defined$project) {4004my@dirname=split'/',$project;4005my$projectbasename=pop@dirname;4006 print_nav_breadcrumbs_path(@dirname);4007print$cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));4008if(defined$action) {4009my$action_print=$action;4010if(defined$opts{-action_extra}) {4011$action_print=$cgi->a({-href => href(action=>$action)},4012$action);4013}4014print" /$action_print";4015}4016if(defined$opts{-action_extra}) {4017print" /$opts{-action_extra}";4018}4019print"\n";4020}elsif(defined$project_filter) {4021 print_nav_breadcrumbs_path(split'/',$project_filter);4022}4023}40244025sub print_search_form {4026if(!defined$searchtext) {4027$searchtext="";4028}4029my$search_hash;4030if(defined$hash_base) {4031$search_hash=$hash_base;4032}elsif(defined$hash) {4033$search_hash=$hash;4034}else{4035$search_hash="HEAD";4036}4037my$action=$my_uri;4038my$use_pathinfo= gitweb_check_feature('pathinfo');4039if($use_pathinfo) {4040$action.="/".esc_url($project);4041}4042print$cgi->startform(-method=>"get", -action =>$action) .4043"<div class=\"search\">\n".4044(!$use_pathinfo&&4045$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .4046$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".4047$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".4048$cgi->popup_menu(-name =>'st', -default=>'commit',4049-values=> ['commit','grep','author','committer','pickaxe']) .4050" ".$cgi->a({-href => href(action=>"search_help"),4051-title =>"search help"},"?") ." search:\n",4052$cgi->textfield(-name =>"s", -value =>$searchtext, -override =>1) ."\n".4053"<span title=\"Extended regular expression\">".4054$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',4055-checked =>$search_use_regexp) .4056"</span>".4057"</div>".4058$cgi->end_form() ."\n";4059}40604061sub git_header_html {4062my$status=shift||"200 OK";4063my$expires=shift;4064my%opts=@_;40654066my$title= get_page_title();4067my$content_type= get_content_type_html();4068print$cgi->header(-type=>$content_type, -charset =>'utf-8',4069-status=>$status, -expires =>$expires)4070unless($opts{'-no_http_header'});4071my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';4072print<<EOF;4073<?xml version="1.0" encoding="utf-8"?>4074<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4075<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">4076<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->4077<!-- git core binaries version$git_version-->4078<head>4079<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>4080<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>4081<meta name="robots" content="index, nofollow"/>4082<title>$title</title>4083EOF4084# the stylesheet, favicon etc urls won't work correctly with path_info4085# unless we set the appropriate base URL4086if($ENV{'PATH_INFO'}) {4087print"<base href=\"".esc_url($base_url)."\"/>\n";4088}4089 print_header_links($status);40904091if(defined$site_html_head_string) {4092print to_utf8($site_html_head_string);4093}40944095print"</head>\n".4096"<body>\n";40974098if(defined$site_header&& -f $site_header) {4099 insert_file($site_header);4100}41014102print"<div class=\"page_header\">\n";4103if(defined$logo) {4104print$cgi->a({-href => esc_url($logo_url),4105-title =>$logo_label},4106$cgi->img({-src => esc_url($logo),4107-width =>72, -height =>27,4108-alt =>"git",4109-class=>"logo"}));4110}4111 print_nav_breadcrumbs(%opts);4112print"</div>\n";41134114my$have_search= gitweb_check_feature('search');4115if(defined$project&&$have_search) {4116 print_search_form();4117}4118}41194120sub git_footer_html {4121my$feed_class='rss_logo';41224123print"<div class=\"page_footer\">\n";4124if(defined$project) {4125my$descr= git_get_project_description($project);4126if(defined$descr) {4127print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";4128}41294130my%href_params= get_feed_info();4131if(!%href_params) {4132$feed_class.=' generic';4133}4134$href_params{'-title'} ||='log';41354136foreachmy$format(qw(RSS Atom)) {4137$href_params{'action'} =lc($format);4138print$cgi->a({-href => href(%href_params),4139-title =>"$href_params{'-title'}$formatfeed",4140-class=>$feed_class},$format)."\n";4141}41424143}else{4144print$cgi->a({-href => href(project=>undef, action=>"opml",4145 project_filter =>$project_filter),4146-class=>$feed_class},"OPML") ." ";4147print$cgi->a({-href => href(project=>undef, action=>"project_index",4148 project_filter =>$project_filter),4149-class=>$feed_class},"TXT") ."\n";4150}4151print"</div>\n";# class="page_footer"41524153if(defined$t0&& gitweb_check_feature('timed')) {4154print"<div id=\"generating_info\">\n";4155print'This page took '.4156'<span id="generating_time" class="time_span">'.4157 tv_interval($t0, [ gettimeofday() ]).4158' seconds </span>'.4159' and '.4160'<span id="generating_cmd">'.4161$number_of_git_cmds.4162'</span> git commands '.4163" to generate.\n";4164print"</div>\n";# class="page_footer"4165}41664167if(defined$site_footer&& -f $site_footer) {4168 insert_file($site_footer);4169}41704171print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;4172if(defined$action&&4173$actioneq'blame_incremental') {4174print qq!<script type="text/javascript">\n!.4175 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.4176 qq!"!. href() .qq!");\n!.4177 qq!</script>\n!;4178}else{4179my($jstimezone,$tz_cookie,$datetime_class) =4180 gitweb_get_feature('javascript-timezone');41814182print qq!<script type="text/javascript">\n!.4183 qq!window.onload = function () {\n!;4184if(gitweb_check_feature('javascript-actions')) {4185print qq! fixLinks();\n!;4186}4187if($jstimezone&&$tz_cookie&&$datetime_class) {4188print qq! var tz_cookie = { name:'$tz_cookie', expires:14, path:'/'};\n!.# in days4189 qq! onloadTZSetup('$jstimezone', tz_cookie,'$datetime_class');\n!;4190}4191print qq!};\n!.4192 qq!</script>\n!;4193}41944195print"</body>\n".4196"</html>";4197}41984199# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])4200# Example: die_error(404, 'Hash not found')4201# By convention, use the following status codes (as defined in RFC 2616):4202# 400: Invalid or missing CGI parameters, or4203# requested object exists but has wrong type.4204# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on4205# this server or project.4206# 404: Requested object/revision/project doesn't exist.4207# 500: The server isn't configured properly, or4208# an internal error occurred (e.g. failed assertions caused by bugs), or4209# an unknown error occurred (e.g. the git binary died unexpectedly).4210# 503: The server is currently unavailable (because it is overloaded,4211# or down for maintenance). Generally, this is a temporary state.4212sub die_error {4213my$status=shift||500;4214my$error= esc_html(shift) ||"Internal Server Error";4215my$extra=shift;4216my%opts=@_;42174218my%http_responses= (4219400=>'400 Bad Request',4220403=>'403 Forbidden',4221404=>'404 Not Found',4222500=>'500 Internal Server Error',4223503=>'503 Service Unavailable',4224);4225 git_header_html($http_responses{$status},undef,%opts);4226print<<EOF;4227<div class="page_body">4228<br /><br />4229$status-$error4230<br />4231EOF4232if(defined$extra) {4233print"<hr />\n".4234"$extra\n";4235}4236print"</div>\n";42374238 git_footer_html();4239goto DONE_GITWEB4240unless($opts{'-error_handler'});4241}42424243## ----------------------------------------------------------------------4244## functions printing or outputting HTML: navigation42454246sub git_print_page_nav {4247my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;4248$extra=''if!defined$extra;# pager or formats42494250my@navs=qw(summary shortlog log commit commitdiff tree);4251if($suppress) {4252@navs=grep{$_ne$suppress}@navs;4253}42544255my%arg=map{$_=> {action=>$_} }@navs;4256if(defined$head) {4257for(qw(commit commitdiff)) {4258$arg{$_}{'hash'} =$head;4259}4260if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {4261for(qw(shortlog log)) {4262$arg{$_}{'hash'} =$head;4263}4264}4265}42664267$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;4268$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;42694270my@actions= gitweb_get_feature('actions');4271my%repl= (4272'%'=>'%',4273'n'=>$project,# project name4274'f'=>$git_dir,# project path within filesystem4275'h'=>$treehead||'',# current hash ('h' parameter)4276'b'=>$treebase||'',# hash base ('hb' parameter)4277);4278while(@actions) {4279my($label,$link,$pos) =splice(@actions,0,3);4280# insert4281@navs=map{$_eq$pos? ($_,$label) :$_}@navs;4282# munch munch4283$link=~s/%([%nfhb])/$repl{$1}/g;4284$arg{$label}{'_href'} =$link;4285}42864287print"<div class=\"page_nav\">\n".4288(join" | ",4289map{$_eq$current?4290$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4291}@navs);4292print"<br/>\n$extra<br/>\n".4293"</div>\n";4294}42954296# returns a submenu for the nagivation of the refs views (tags, heads,4297# remotes) with the current view disabled and the remotes view only4298# available if the feature is enabled4299sub format_ref_views {4300my($current) =@_;4301my@ref_views=qw{tags heads};4302push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4303returnjoin" | ",map{4304$_eq$current?$_:4305$cgi->a({-href => href(action=>$_)},$_)4306}@ref_views4307}43084309sub format_paging_nav {4310my($action,$page,$has_next_link) =@_;4311my$paging_nav;431243134314if($page>0) {4315$paging_nav.=4316$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4317" ⋅ ".4318$cgi->a({-href => href(-replay=>1, page=>$page-1),4319-accesskey =>"p", -title =>"Alt-p"},"prev");4320}else{4321$paging_nav.="first ⋅ prev";4322}43234324if($has_next_link) {4325$paging_nav.=" ⋅ ".4326$cgi->a({-href => href(-replay=>1, page=>$page+1),4327-accesskey =>"n", -title =>"Alt-n"},"next");4328}else{4329$paging_nav.=" ⋅ next";4330}43314332return$paging_nav;4333}43344335## ......................................................................4336## functions printing or outputting HTML: div43374338sub git_print_header_div {4339my($action,$title,$hash,$hash_base) =@_;4340my%args= ();43414342$args{'action'} =$action;4343$args{'hash'} =$hashif$hash;4344$args{'hash_base'} =$hash_baseif$hash_base;43454346print"<div class=\"header\">\n".4347$cgi->a({-href => href(%args), -class=>"title"},4348$title?$title:$action) .4349"\n</div>\n";4350}43514352sub format_repo_url {4353my($name,$url) =@_;4354return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4355}43564357# Group output by placing it in a DIV element and adding a header.4358# Options for start_div() can be provided by passing a hash reference as the4359# first parameter to the function.4360# Options to git_print_header_div() can be provided by passing an array4361# reference. This must follow the options to start_div if they are present.4362# The content can be a scalar, which is output as-is, a scalar reference, which4363# is output after html escaping, an IO handle passed either as *handle or4364# *handle{IO}, or a function reference. In the latter case all following4365# parameters will be taken as argument to the content function call.4366sub git_print_section {4367my($div_args,$header_args,$content);4368my$arg=shift;4369if(ref($arg)eq'HASH') {4370$div_args=$arg;4371$arg=shift;4372}4373if(ref($arg)eq'ARRAY') {4374$header_args=$arg;4375$arg=shift;4376}4377$content=$arg;43784379print$cgi->start_div($div_args);4380 git_print_header_div(@$header_args);43814382if(ref($content)eq'CODE') {4383$content->(@_);4384}elsif(ref($content)eq'SCALAR') {4385print esc_html($$content);4386}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4387print<$content>;4388}elsif(!ref($content) &&defined($content)) {4389print$content;4390}43914392print$cgi->end_div;4393}43944395sub format_timestamp_html {4396my$date=shift;4397my$strtime=$date->{'rfc2822'};43984399my(undef,undef,$datetime_class) =4400 gitweb_get_feature('javascript-timezone');4401if($datetime_class) {4402$strtime= qq!<span class="$datetime_class">$strtime</span>!;4403}44044405my$localtime_format='(%02d:%02d%s)';4406if($date->{'hour_local'} <6) {4407$localtime_format='(<span class="atnight">%02d:%02d</span>%s)';4408}4409$strtime.=' '.4410sprintf($localtime_format,4411$date->{'hour_local'},$date->{'minute_local'},$date->{'tz_local'});44124413return$strtime;4414}44154416# Outputs the author name and date in long form4417sub git_print_authorship {4418my$co=shift;4419my%opts=@_;4420my$tag=$opts{-tag} ||'div';4421my$author=$co->{'author_name'};44224423my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4424print"<$tagclass=\"author_date\">".4425 format_search_author($author,"author", esc_html($author)) .4426" [".format_timestamp_html(\%ad)."]".4427 git_get_avatar($co->{'author_email'}, -pad_before =>1) .4428"</$tag>\n";4429}44304431# Outputs table rows containing the full author or committer information,4432# in the format expected for 'commit' view (& similar).4433# Parameters are a commit hash reference, followed by the list of people4434# to output information for. If the list is empty it defaults to both4435# author and committer.4436sub git_print_authorship_rows {4437my$co=shift;4438# too bad we can't use @people = @_ || ('author', 'committer')4439my@people=@_;4440@people= ('author','committer')unless@people;4441foreachmy$who(@people) {4442my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4443print"<tr><td>$who</td><td>".4444 format_search_author($co->{"${who}_name"},$who,4445 esc_html($co->{"${who}_name"})) ." ".4446 format_search_author($co->{"${who}_email"},$who,4447 esc_html("<".$co->{"${who}_email"} .">")) .4448"</td><td rowspan=\"2\">".4449 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4450"</td></tr>\n".4451"<tr>".4452"<td></td><td>".4453 format_timestamp_html(\%wd) .4454"</td>".4455"</tr>\n";4456}4457}44584459sub git_print_page_path {4460my$name=shift;4461my$type=shift;4462my$hb=shift;446344644465print"<div class=\"page_path\">";4466print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4467-title =>'tree root'}, to_utf8("[$project]"));4468print" / ";4469if(defined$name) {4470my@dirname=split'/',$name;4471my$basename=pop@dirname;4472my$fullname='';44734474foreachmy$dir(@dirname) {4475$fullname.= ($fullname?'/':'') .$dir;4476print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4477 hash_base=>$hb),4478-title =>$fullname}, esc_path($dir));4479print" / ";4480}4481if(defined$type&&$typeeq'blob') {4482print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4483 hash_base=>$hb),4484-title =>$name}, esc_path($basename));4485}elsif(defined$type&&$typeeq'tree') {4486print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4487 hash_base=>$hb),4488-title =>$name}, esc_path($basename));4489print" / ";4490}else{4491print esc_path($basename);4492}4493}4494print"<br/></div>\n";4495}44964497sub git_print_log {4498my$log=shift;4499my%opts=@_;45004501if($opts{'-remove_title'}) {4502# remove title, i.e. first line of log4503shift@$log;4504}4505# remove leading empty lines4506while(defined$log->[0] &&$log->[0]eq"") {4507shift@$log;4508}45094510# print log4511my$skip_blank_line=0;4512foreachmy$line(@$log) {4513if($line=~m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {4514if(!$opts{'-remove_signoff'}) {4515print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4516$skip_blank_line=1;4517}4518next;4519}45204521if($line=~ m,\s*([a-z]*link): (https?://\S+),i) {4522if(!$opts{'-remove_signoff'}) {4523print"<span class=\"signoff\">". esc_html($1) .": ".4524"<a href=\"". esc_html($2) ."\">". esc_html($2) ."</a>".4525"</span><br/>\n";4526$skip_blank_line=1;4527}4528next;4529}45304531# print only one empty line4532# do not print empty line after signoff4533if($lineeq"") {4534next if($skip_blank_line);4535$skip_blank_line=1;4536}else{4537$skip_blank_line=0;4538}45394540print format_log_line_html($line) ."<br/>\n";4541}45424543if($opts{'-final_empty_line'}) {4544# end with single empty line4545print"<br/>\n"unless$skip_blank_line;4546}4547}45484549# return link target (what link points to)4550sub git_get_link_target {4551my$hash=shift;4552my$link_target;45534554# read link4555open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4556orreturn;4557{4558local$/=undef;4559$link_target= <$fd>;4560}4561close$fd4562orreturn;45634564return$link_target;4565}45664567# given link target, and the directory (basedir) the link is in,4568# return target of link relative to top directory (top tree);4569# return undef if it is not possible (including absolute links).4570sub normalize_link_target {4571my($link_target,$basedir) =@_;45724573# absolute symlinks (beginning with '/') cannot be normalized4574return if(substr($link_target,0,1)eq'/');45754576# normalize link target to path from top (root) tree (dir)4577my$path;4578if($basedir) {4579$path=$basedir.'/'.$link_target;4580}else{4581# we are in top (root) tree (dir)4582$path=$link_target;4583}45844585# remove //, /./, and /../4586my@path_parts;4587foreachmy$part(split('/',$path)) {4588# discard '.' and ''4589next if(!$part||$parteq'.');4590# handle '..'4591if($parteq'..') {4592if(@path_parts) {4593pop@path_parts;4594}else{4595# link leads outside repository (outside top dir)4596return;4597}4598}else{4599push@path_parts,$part;4600}4601}4602$path=join('/',@path_parts);46034604return$path;4605}46064607# print tree entry (row of git_tree), but without encompassing <tr> element4608sub git_print_tree_entry {4609my($t,$basedir,$hash_base,$have_blame) =@_;46104611my%base_key= ();4612$base_key{'hash_base'} =$hash_baseifdefined$hash_base;46134614# The format of a table row is: mode list link. Where mode is4615# the mode of the entry, list is the name of the entry, an href,4616# and link is the action links of the entry.46174618print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4619if(exists$t->{'size'}) {4620print"<td class=\"size\">$t->{'size'}</td>\n";4621}4622if($t->{'type'}eq"blob") {4623print"<td class=\"list\">".4624$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4625 file_name=>"$basedir$t->{'name'}",%base_key),4626-class=>"list"}, esc_path($t->{'name'}));4627if(S_ISLNK(oct$t->{'mode'})) {4628my$link_target= git_get_link_target($t->{'hash'});4629if($link_target) {4630my$norm_target= normalize_link_target($link_target,$basedir);4631if(defined$norm_target) {4632print" -> ".4633$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4634 file_name=>$norm_target),4635-title =>$norm_target}, esc_path($link_target));4636}else{4637print" -> ". esc_path($link_target);4638}4639}4640}4641print"</td>\n";4642print"<td class=\"link\">";4643print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4644 file_name=>"$basedir$t->{'name'}",%base_key)},4645"blob");4646if($have_blame) {4647print" | ".4648$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4649 file_name=>"$basedir$t->{'name'}",%base_key)},4650"blame");4651}4652if(defined$hash_base) {4653print" | ".4654$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4655 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4656"history");4657}4658print" | ".4659$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4660 file_name=>"$basedir$t->{'name'}")},4661"raw");4662print"</td>\n";46634664}elsif($t->{'type'}eq"tree") {4665print"<td class=\"list\">";4666print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4667 file_name=>"$basedir$t->{'name'}",4668%base_key)},4669 esc_path($t->{'name'}));4670print"</td>\n";4671print"<td class=\"link\">";4672print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4673 file_name=>"$basedir$t->{'name'}",4674%base_key)},4675"tree");4676if(defined$hash_base) {4677print" | ".4678$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4679 file_name=>"$basedir$t->{'name'}")},4680"history");4681}4682print"</td>\n";4683}else{4684# unknown object: we can only present history for it4685# (this includes 'commit' object, i.e. submodule support)4686print"<td class=\"list\">".4687 esc_path($t->{'name'}) .4688"</td>\n";4689print"<td class=\"link\">";4690if(defined$hash_base) {4691print$cgi->a({-href => href(action=>"history",4692 hash_base=>$hash_base,4693 file_name=>"$basedir$t->{'name'}")},4694"history");4695}4696print"</td>\n";4697}4698}46994700## ......................................................................4701## functions printing large fragments of HTML47024703# get pre-image filenames for merge (combined) diff4704sub fill_from_file_info {4705my($diff,@parents) =@_;47064707$diff->{'from_file'} = [ ];4708$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4709for(my$i=0;$i<$diff->{'nparents'};$i++) {4710if($diff->{'status'}[$i]eq'R'||4711$diff->{'status'}[$i]eq'C') {4712$diff->{'from_file'}[$i] =4713 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4714}4715}47164717return$diff;4718}47194720# is current raw difftree line of file deletion4721sub is_deleted {4722my$diffinfo=shift;47234724return$diffinfo->{'to_id'}eq('0' x 40);4725}47264727# does patch correspond to [previous] difftree raw line4728# $diffinfo - hashref of parsed raw diff format4729# $patchinfo - hashref of parsed patch diff format4730# (the same keys as in $diffinfo)4731sub is_patch_split {4732my($diffinfo,$patchinfo) =@_;47334734returndefined$diffinfo&&defined$patchinfo4735&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4736}473747384739sub git_difftree_body {4740my($difftree,$hash,@parents) =@_;4741my($parent) =$parents[0];4742my$have_blame= gitweb_check_feature('blame');4743print"<div class=\"list_head\">\n";4744if($#{$difftree} >10) {4745print(($#{$difftree} +1) ." files changed:\n");4746}4747print"</div>\n";47484749print"<table class=\"".4750(@parents>1?"combined ":"") .4751"diff_tree\">\n";47524753# header only for combined diff in 'commitdiff' view4754my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4755if($has_header) {4756# table header4757print"<thead><tr>\n".4758"<th></th><th></th>\n";# filename, patchN link4759for(my$i=0;$i<@parents;$i++) {4760my$par=$parents[$i];4761print"<th>".4762$cgi->a({-href => href(action=>"commitdiff",4763 hash=>$hash, hash_parent=>$par),4764-title =>'commitdiff to parent number '.4765($i+1) .': '.substr($par,0,7)},4766$i+1) .4767" </th>\n";4768}4769print"</tr></thead>\n<tbody>\n";4770}47714772my$alternate=1;4773my$patchno=0;4774foreachmy$line(@{$difftree}) {4775my$diff= parsed_difftree_line($line);47764777if($alternate) {4778print"<tr class=\"dark\">\n";4779}else{4780print"<tr class=\"light\">\n";4781}4782$alternate^=1;47834784if(exists$diff->{'nparents'}) {# combined diff47854786 fill_from_file_info($diff,@parents)4787unlessexists$diff->{'from_file'};47884789if(!is_deleted($diff)) {4790# file exists in the result (child) commit4791print"<td>".4792$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4793 file_name=>$diff->{'to_file'},4794 hash_base=>$hash),4795-class=>"list"}, esc_path($diff->{'to_file'})) .4796"</td>\n";4797}else{4798print"<td>".4799 esc_path($diff->{'to_file'}) .4800"</td>\n";4801}48024803if($actioneq'commitdiff') {4804# link to patch4805$patchno++;4806print"<td class=\"link\">".4807$cgi->a({-href => href(-anchor=>"patch$patchno")},4808"patch") .4809" | ".4810"</td>\n";4811}48124813my$has_history=0;4814my$not_deleted=0;4815for(my$i=0;$i<$diff->{'nparents'};$i++) {4816my$hash_parent=$parents[$i];4817my$from_hash=$diff->{'from_id'}[$i];4818my$from_path=$diff->{'from_file'}[$i];4819my$status=$diff->{'status'}[$i];48204821$has_history||= ($statusne'A');4822$not_deleted||= ($statusne'D');48234824if($statuseq'A') {4825print"<td class=\"link\"align=\"right\"> | </td>\n";4826}elsif($statuseq'D') {4827print"<td class=\"link\">".4828$cgi->a({-href => href(action=>"blob",4829 hash_base=>$hash,4830 hash=>$from_hash,4831 file_name=>$from_path)},4832"blob". ($i+1)) .4833" | </td>\n";4834}else{4835if($diff->{'to_id'}eq$from_hash) {4836print"<td class=\"link nochange\">";4837}else{4838print"<td class=\"link\">";4839}4840print$cgi->a({-href => href(action=>"blobdiff",4841 hash=>$diff->{'to_id'},4842 hash_parent=>$from_hash,4843 hash_base=>$hash,4844 hash_parent_base=>$hash_parent,4845 file_name=>$diff->{'to_file'},4846 file_parent=>$from_path)},4847"diff". ($i+1)) .4848" | </td>\n";4849}4850}48514852print"<td class=\"link\">";4853if($not_deleted) {4854print$cgi->a({-href => href(action=>"blob",4855 hash=>$diff->{'to_id'},4856 file_name=>$diff->{'to_file'},4857 hash_base=>$hash)},4858"blob");4859print" | "if($has_history);4860}4861if($has_history) {4862print$cgi->a({-href => href(action=>"history",4863 file_name=>$diff->{'to_file'},4864 hash_base=>$hash)},4865"history");4866}4867print"</td>\n";48684869print"</tr>\n";4870next;# instead of 'else' clause, to avoid extra indent4871}4872# else ordinary diff48734874my($to_mode_oct,$to_mode_str,$to_file_type);4875my($from_mode_oct,$from_mode_str,$from_file_type);4876if($diff->{'to_mode'}ne('0' x 6)) {4877$to_mode_oct=oct$diff->{'to_mode'};4878if(S_ISREG($to_mode_oct)) {# only for regular file4879$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4880}4881$to_file_type= file_type($diff->{'to_mode'});4882}4883if($diff->{'from_mode'}ne('0' x 6)) {4884$from_mode_oct=oct$diff->{'from_mode'};4885if(S_ISREG($from_mode_oct)) {# only for regular file4886$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4887}4888$from_file_type= file_type($diff->{'from_mode'});4889}48904891if($diff->{'status'}eq"A") {# created4892my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4893$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4894$mode_chng.="]</span>";4895print"<td>";4896print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4897 hash_base=>$hash, file_name=>$diff->{'file'}),4898-class=>"list"}, esc_path($diff->{'file'}));4899print"</td>\n";4900print"<td>$mode_chng</td>\n";4901print"<td class=\"link\">";4902if($actioneq'commitdiff') {4903# link to patch4904$patchno++;4905print$cgi->a({-href => href(-anchor=>"patch$patchno")},4906"patch") .4907" | ";4908}4909print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4910 hash_base=>$hash, file_name=>$diff->{'file'})},4911"blob");4912print"</td>\n";49134914}elsif($diff->{'status'}eq"D") {# deleted4915my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4916print"<td>";4917print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4918 hash_base=>$parent, file_name=>$diff->{'file'}),4919-class=>"list"}, esc_path($diff->{'file'}));4920print"</td>\n";4921print"<td>$mode_chng</td>\n";4922print"<td class=\"link\">";4923if($actioneq'commitdiff') {4924# link to patch4925$patchno++;4926print$cgi->a({-href => href(-anchor=>"patch$patchno")},4927"patch") .4928" | ";4929}4930print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4931 hash_base=>$parent, file_name=>$diff->{'file'})},4932"blob") ." | ";4933if($have_blame) {4934print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4935 file_name=>$diff->{'file'})},4936"blame") ." | ";4937}4938print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4939 file_name=>$diff->{'file'})},4940"history");4941print"</td>\n";49424943}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4944my$mode_chnge="";4945if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4946$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4947if($from_file_typene$to_file_type) {4948$mode_chnge.=" from$from_file_typeto$to_file_type";4949}4950if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4951if($from_mode_str&&$to_mode_str) {4952$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4953}elsif($to_mode_str) {4954$mode_chnge.=" mode:$to_mode_str";4955}4956}4957$mode_chnge.="]</span>\n";4958}4959print"<td>";4960print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4961 hash_base=>$hash, file_name=>$diff->{'file'}),4962-class=>"list"}, esc_path($diff->{'file'}));4963print"</td>\n";4964print"<td>$mode_chnge</td>\n";4965print"<td class=\"link\">";4966if($actioneq'commitdiff') {4967# link to patch4968$patchno++;4969print$cgi->a({-href => href(-anchor=>"patch$patchno")},4970"patch") .4971" | ";4972}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4973# "commit" view and modified file (not onlu mode changed)4974print$cgi->a({-href => href(action=>"blobdiff",4975 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4976 hash_base=>$hash, hash_parent_base=>$parent,4977 file_name=>$diff->{'file'})},4978"diff") .4979" | ";4980}4981print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4982 hash_base=>$hash, file_name=>$diff->{'file'})},4983"blob") ." | ";4984if($have_blame) {4985print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4986 file_name=>$diff->{'file'})},4987"blame") ." | ";4988}4989print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4990 file_name=>$diff->{'file'})},4991"history");4992print"</td>\n";49934994}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4995my%status_name= ('R'=>'moved','C'=>'copied');4996my$nstatus=$status_name{$diff->{'status'}};4997my$mode_chng="";4998if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4999# mode also for directories, so we cannot use $to_mode_str5000$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);5001}5002print"<td>".5003$cgi->a({-href => href(action=>"blob", hash_base=>$hash,5004 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),5005-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".5006"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".5007$cgi->a({-href => href(action=>"blob", hash_base=>$parent,5008 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),5009-class=>"list"}, esc_path($diff->{'from_file'})) .5010" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".5011"<td class=\"link\">";5012if($actioneq'commitdiff') {5013# link to patch5014$patchno++;5015print$cgi->a({-href => href(-anchor=>"patch$patchno")},5016"patch") .5017" | ";5018}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {5019# "commit" view and modified file (not only pure rename or copy)5020print$cgi->a({-href => href(action=>"blobdiff",5021 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},5022 hash_base=>$hash, hash_parent_base=>$parent,5023 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},5024"diff") .5025" | ";5026}5027print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},5028 hash_base=>$parent, file_name=>$diff->{'to_file'})},5029"blob") ." | ";5030if($have_blame) {5031print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,5032 file_name=>$diff->{'to_file'})},5033"blame") ." | ";5034}5035print$cgi->a({-href => href(action=>"history", hash_base=>$hash,5036 file_name=>$diff->{'to_file'})},5037"history");5038print"</td>\n";50395040}# we should not encounter Unmerged (U) or Unknown (X) status5041print"</tr>\n";5042}5043print"</tbody>"if$has_header;5044print"</table>\n";5045}50465047# Print context lines and then rem/add lines in a side-by-side manner.5048sub print_sidebyside_diff_lines {5049my($ctx,$rem,$add) =@_;50505051# print context block before add/rem block5052if(@$ctx) {5053print join'',5054'<div class="chunk_block ctx">',5055'<div class="old">',5056@$ctx,5057'</div>',5058'<div class="new">',5059@$ctx,5060'</div>',5061'</div>';5062}50635064if(!@$add) {5065# pure removal5066print join'',5067'<div class="chunk_block rem">',5068'<div class="old">',5069@$rem,5070'</div>',5071'</div>';5072}elsif(!@$rem) {5073# pure addition5074print join'',5075'<div class="chunk_block add">',5076'<div class="new">',5077@$add,5078'</div>',5079'</div>';5080}else{5081print join'',5082'<div class="chunk_block chg">',5083'<div class="old">',5084@$rem,5085'</div>',5086'<div class="new">',5087@$add,5088'</div>',5089'</div>';5090}5091}50925093# Print context lines and then rem/add lines in inline manner.5094sub print_inline_diff_lines {5095my($ctx,$rem,$add) =@_;50965097print@$ctx,@$rem,@$add;5098}50995100# Format removed and added line, mark changed part and HTML-format them.5101# Implementation is based on contrib/diff-highlight5102sub format_rem_add_lines_pair {5103my($rem,$add,$num_parents) =@_;51045105# We need to untabify lines before split()'ing them;5106# otherwise offsets would be invalid.5107chomp$rem;5108chomp$add;5109$rem= untabify($rem);5110$add= untabify($add);51115112my@rem=split(//,$rem);5113my@add=split(//,$add);5114my($esc_rem,$esc_add);5115# Ignore leading +/- characters for each parent.5116my($prefix_len,$suffix_len) = ($num_parents,0);5117my($prefix_has_nonspace,$suffix_has_nonspace);51185119my$shorter= (@rem<@add) ?@rem:@add;5120while($prefix_len<$shorter) {5121last if($rem[$prefix_len]ne$add[$prefix_len]);51225123$prefix_has_nonspace=1if($rem[$prefix_len] !~/\s/);5124$prefix_len++;5125}51265127while($prefix_len+$suffix_len<$shorter) {5128last if($rem[-1-$suffix_len]ne$add[-1-$suffix_len]);51295130$suffix_has_nonspace=1if($rem[-1-$suffix_len] !~/\s/);5131$suffix_len++;5132}51335134# Mark lines that are different from each other, but have some common5135# part that isn't whitespace. If lines are completely different, don't5136# mark them because that would make output unreadable, especially if5137# diff consists of multiple lines.5138if($prefix_has_nonspace||$suffix_has_nonspace) {5139$esc_rem= esc_html_hl_regions($rem,'marked',5140[$prefix_len,@rem-$suffix_len], -nbsp=>1);5141$esc_add= esc_html_hl_regions($add,'marked',5142[$prefix_len,@add-$suffix_len], -nbsp=>1);5143}else{5144$esc_rem= esc_html($rem, -nbsp=>1);5145$esc_add= esc_html($add, -nbsp=>1);5146}51475148return format_diff_line(\$esc_rem,'rem'),5149 format_diff_line(\$esc_add,'add');5150}51515152# HTML-format diff context, removed and added lines.5153sub format_ctx_rem_add_lines {5154my($ctx,$rem,$add,$num_parents) =@_;5155my(@new_ctx,@new_rem,@new_add);5156my$can_highlight=0;5157my$is_combined= ($num_parents>1);51585159# Highlight if every removed line has a corresponding added line.5160if(@$add>0&&@$add==@$rem) {5161$can_highlight=1;51625163# Highlight lines in combined diff only if the chunk contains5164# diff between the same version, e.g.5165#5166# - a5167# - b5168# + c5169# + d5170#5171# Otherwise the highlightling would be confusing.5172if($is_combined) {5173for(my$i=0;$i<@$add;$i++) {5174my$prefix_rem=substr($rem->[$i],0,$num_parents);5175my$prefix_add=substr($add->[$i],0,$num_parents);51765177$prefix_rem=~s/-/+/g;51785179if($prefix_remne$prefix_add) {5180$can_highlight=0;5181last;5182}5183}5184}5185}51865187if($can_highlight) {5188for(my$i=0;$i<@$add;$i++) {5189my($line_rem,$line_add) = format_rem_add_lines_pair(5190$rem->[$i],$add->[$i],$num_parents);5191push@new_rem,$line_rem;5192push@new_add,$line_add;5193}5194}else{5195@new_rem=map{ format_diff_line($_,'rem') }@$rem;5196@new_add=map{ format_diff_line($_,'add') }@$add;5197}51985199@new_ctx=map{ format_diff_line($_,'ctx') }@$ctx;52005201return(\@new_ctx, \@new_rem, \@new_add);5202}52035204# Print context lines and then rem/add lines.5205sub print_diff_lines {5206my($ctx,$rem,$add,$diff_style,$num_parents) =@_;5207my$is_combined=$num_parents>1;52085209($ctx,$rem,$add) = format_ctx_rem_add_lines($ctx,$rem,$add,5210$num_parents);52115212if($diff_styleeq'sidebyside'&& !$is_combined) {5213 print_sidebyside_diff_lines($ctx,$rem,$add);5214}else{5215# default 'inline' style and unknown styles5216 print_inline_diff_lines($ctx,$rem,$add);5217}5218}52195220sub print_diff_chunk {5221my($diff_style,$num_parents,$from,$to,@chunk) =@_;5222my(@ctx,@rem,@add);52235224# The class of the previous line.5225my$prev_class='';52265227return unless@chunk;52285229# incomplete last line might be among removed or added lines,5230# or both, or among context lines: find which5231for(my$i=1;$i<@chunk;$i++) {5232if($chunk[$i][0]eq'incomplete') {5233$chunk[$i][0] =$chunk[$i-1][0];5234}5235}52365237# guardian5238push@chunk, ["",""];52395240foreachmy$line_info(@chunk) {5241my($class,$line) =@$line_info;52425243# print chunk headers5244if($class&&$classeq'chunk_header') {5245print format_diff_line($line,$class,$from,$to);5246next;5247}52485249## print from accumulator when have some add/rem lines or end5250# of chunk (flush context lines), or when have add and rem5251# lines and new block is reached (otherwise add/rem lines could5252# be reordered)5253if(!$class|| ((@rem||@add) &&$classeq'ctx') ||5254(@rem&&@add&&$classne$prev_class)) {5255 print_diff_lines(\@ctx, \@rem, \@add,5256$diff_style,$num_parents);5257@ctx=@rem=@add= ();5258}52595260## adding lines to accumulator5261# guardian value5262last unless$line;5263# rem, add or change5264if($classeq'rem') {5265push@rem,$line;5266}elsif($classeq'add') {5267push@add,$line;5268}5269# context line5270if($classeq'ctx') {5271push@ctx,$line;5272}52735274$prev_class=$class;5275}5276}52775278sub git_patchset_body {5279my($fd,$diff_style,$difftree,$hash,@hash_parents) =@_;5280my($hash_parent) =$hash_parents[0];52815282my$is_combined= (@hash_parents>1);5283my$patch_idx=0;5284my$patch_number=0;5285my$patch_line;5286my$diffinfo;5287my$to_name;5288my(%from,%to);5289my@chunk;# for side-by-side diff52905291print"<div class=\"patchset\">\n";52925293# skip to first patch5294while($patch_line= <$fd>) {5295chomp$patch_line;52965297last if($patch_line=~m/^diff /);5298}52995300 PATCH:5301while($patch_line) {53025303# parse "git diff" header line5304if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {5305# $1 is from_name, which we do not use5306$to_name= unquote($2);5307$to_name=~s!^b/!!;5308}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {5309# $1 is 'cc' or 'combined', which we do not use5310$to_name= unquote($2);5311}else{5312$to_name=undef;5313}53145315# check if current patch belong to current raw line5316# and parse raw git-diff line if needed5317if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {5318# this is continuation of a split patch5319print"<div class=\"patch cont\">\n";5320}else{5321# advance raw git-diff output if needed5322$patch_idx++ifdefined$diffinfo;53235324# read and prepare patch information5325$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);53265327# compact combined diff output can have some patches skipped5328# find which patch (using pathname of result) we are at now;5329if($is_combined) {5330while($to_namene$diffinfo->{'to_file'}) {5331print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5332 format_diff_cc_simplified($diffinfo,@hash_parents) .5333"</div>\n";# class="patch"53345335$patch_idx++;5336$patch_number++;53375338last if$patch_idx>$#$difftree;5339$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);5340}5341}53425343# modifies %from, %to hashes5344 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);53455346# this is first patch for raw difftree line with $patch_idx index5347# we index @$difftree array from 0, but number patches from 15348print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";5349}53505351# git diff header5352#assert($patch_line =~ m/^diff /) if DEBUG;5353#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed5354$patch_number++;5355# print "git diff" header5356print format_git_diff_header_line($patch_line,$diffinfo,5357 \%from, \%to);53585359# print extended diff header5360print"<div class=\"diff extended_header\">\n";5361 EXTENDED_HEADER:5362while($patch_line= <$fd>) {5363chomp$patch_line;53645365last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);53665367print format_extended_diff_header_line($patch_line,$diffinfo,5368 \%from, \%to);5369}5370print"</div>\n";# class="diff extended_header"53715372# from-file/to-file diff header5373if(!$patch_line) {5374print"</div>\n";# class="patch"5375last PATCH;5376}5377next PATCH if($patch_line=~m/^diff /);5378#assert($patch_line =~ m/^---/) if DEBUG;53795380my$last_patch_line=$patch_line;5381$patch_line= <$fd>;5382chomp$patch_line;5383#assert($patch_line =~ m/^\+\+\+/) if DEBUG;53845385print format_diff_from_to_header($last_patch_line,$patch_line,5386$diffinfo, \%from, \%to,5387@hash_parents);53885389# the patch itself5390 LINE:5391while($patch_line= <$fd>) {5392chomp$patch_line;53935394next PATCH if($patch_line=~m/^diff /);53955396my$class= diff_line_class($patch_line, \%from, \%to);53975398if($classeq'chunk_header') {5399 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5400@chunk= ();5401}54025403push@chunk, [$class,$patch_line];5404}54055406}continue{5407if(@chunk) {5408 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5409@chunk= ();5410}5411print"</div>\n";# class="patch"5412}54135414# for compact combined (--cc) format, with chunk and patch simplification5415# the patchset might be empty, but there might be unprocessed raw lines5416for(++$patch_idxif$patch_number>0;5417$patch_idx<@$difftree;5418++$patch_idx) {5419# read and prepare patch information5420$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);54215422# generate anchor for "patch" links in difftree / whatchanged part5423print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5424 format_diff_cc_simplified($diffinfo,@hash_parents) .5425"</div>\n";# class="patch"54265427$patch_number++;5428}54295430if($patch_number==0) {5431if(@hash_parents>1) {5432print"<div class=\"diff nodifferences\">Trivial merge</div>\n";5433}else{5434print"<div class=\"diff nodifferences\">No differences found</div>\n";5435}5436}54375438print"</div>\n";# class="patchset"5439}54405441# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .54425443sub git_project_search_form {5444my($searchtext,$search_use_regexp) =@_;54455446my$limit='';5447if($project_filter) {5448$limit=" in '$project_filter/'";5449}54505451print"<div class=\"projsearch\">\n";5452print$cgi->startform(-method=>'get', -action =>$my_uri) .5453$cgi->hidden(-name =>'a', -value =>'project_list') ."\n";5454print$cgi->hidden(-name =>'pf', -value =>$project_filter)."\n"5455if(defined$project_filter);5456print$cgi->textfield(-name =>'s', -value =>$searchtext,5457-title =>"Search project by name and description$limit",5458-size =>60) ."\n".5459"<span title=\"Extended regular expression\">".5460$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',5461-checked =>$search_use_regexp) .5462"</span>\n".5463$cgi->submit(-name =>'btnS', -value =>'Search') .5464$cgi->end_form() ."\n".5465$cgi->a({-href => href(project =>undef, searchtext =>undef,5466 project_filter =>$project_filter)},5467 esc_html("List all projects$limit")) ."<br />\n";5468print"</div>\n";5469}54705471# entry for given @keys needs filling if at least one of keys in list5472# is not present in %$project_info5473sub project_info_needs_filling {5474my($project_info,@keys) =@_;54755476# return List::MoreUtils::any { !exists $project_info->{$_} } @keys;5477foreachmy$key(@keys) {5478if(!exists$project_info->{$key}) {5479return1;5480}5481}5482return;5483}54845485# fills project list info (age, description, owner, category, forks, etc.)5486# for each project in the list, removing invalid projects from5487# returned list, or fill only specified info.5488#5489# Invalid projects are removed from the returned list if and only if you5490# ask 'age' or 'age_string' to be filled, because they are the only fields5491# that run unconditionally git command that requires repository, and5492# therefore do always check if project repository is invalid.5493#5494# USAGE:5495# * fill_project_list_info(\@project_list, 'descr_long', 'ctags')5496# ensures that 'descr_long' and 'ctags' fields are filled5497# * @project_list = fill_project_list_info(\@project_list)5498# ensures that all fields are filled (and invalid projects removed)5499#5500# NOTE: modifies $projlist, but does not remove entries from it5501sub fill_project_list_info {5502my($projlist,@wanted_keys) =@_;5503my@projects;5504my$filter_set=sub{return@_; };5505if(@wanted_keys) {5506my%wanted_keys=map{$_=>1}@wanted_keys;5507$filter_set=sub{returngrep{$wanted_keys{$_} }@_; };5508}55095510my$show_ctags= gitweb_check_feature('ctags');5511 PROJECT:5512foreachmy$pr(@$projlist) {5513if(project_info_needs_filling($pr,$filter_set->('age','age_string'))) {5514my(@activity) = git_get_last_activity($pr->{'path'});5515unless(@activity) {5516next PROJECT;5517}5518($pr->{'age'},$pr->{'age_string'}) =@activity;5519}5520if(project_info_needs_filling($pr,$filter_set->('descr','descr_long'))) {5521my$descr= git_get_project_description($pr->{'path'}) ||"";5522$descr= to_utf8($descr);5523$pr->{'descr_long'} =$descr;5524$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);5525}5526if(project_info_needs_filling($pr,$filter_set->('owner'))) {5527$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";5528}5529if($show_ctags&&5530 project_info_needs_filling($pr,$filter_set->('ctags'))) {5531$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});5532}5533if($projects_list_group_categories&&5534 project_info_needs_filling($pr,$filter_set->('category'))) {5535my$cat= git_get_project_category($pr->{'path'}) ||5536$project_list_default_category;5537$pr->{'category'} = to_utf8($cat);5538}55395540push@projects,$pr;5541}55425543return@projects;5544}55455546sub sort_projects_list {5547my($projlist,$order) =@_;55485549sub order_str {5550my$key=shift;5551return sub{$a->{$key}cmp$b->{$key} };5552}55535554sub order_num_then_undef {5555my$key=shift;5556return sub{5557defined$a->{$key} ?5558(defined$b->{$key} ?$a->{$key} <=>$b->{$key} : -1) :5559(defined$b->{$key} ?1:0)5560};5561}55625563my%orderings= (5564 project => order_str('path'),5565 descr => order_str('descr_long'),5566 owner => order_str('owner'),5567 age => order_num_then_undef('age'),5568);55695570my$ordering=$orderings{$order};5571returndefined$ordering?sort$ordering @$projlist:@$projlist;5572}55735574# returns a hash of categories, containing the list of project5575# belonging to each category5576sub build_projlist_by_category {5577my($projlist,$from,$to) =@_;5578my%categories;55795580$from=0unlessdefined$from;5581$to=$#$projlistif(!defined$to||$#$projlist<$to);55825583for(my$i=$from;$i<=$to;$i++) {5584my$pr=$projlist->[$i];5585push@{$categories{$pr->{'category'} }},$pr;5586}55875588returnwantarray?%categories: \%categories;5589}55905591# print 'sort by' <th> element, generating 'sort by $name' replay link5592# if that order is not selected5593sub print_sort_th {5594print format_sort_th(@_);5595}55965597sub format_sort_th {5598my($name,$order,$header) =@_;5599my$sort_th="";5600$header||=ucfirst($name);56015602if($ordereq$name) {5603$sort_th.="<th>$header</th>\n";5604}else{5605$sort_th.="<th>".5606$cgi->a({-href => href(-replay=>1, order=>$name),5607-class=>"header"},$header) .5608"</th>\n";5609}56105611return$sort_th;5612}56135614sub git_project_list_rows {5615my($projlist,$from,$to,$check_forks) =@_;56165617$from=0unlessdefined$from;5618$to=$#$projlistif(!defined$to||$#$projlist<$to);56195620my$alternate=1;5621for(my$i=$from;$i<=$to;$i++) {5622my$pr=$projlist->[$i];56235624if($alternate) {5625print"<tr class=\"dark\">\n";5626}else{5627print"<tr class=\"light\">\n";5628}5629$alternate^=1;56305631if($check_forks) {5632print"<td>";5633if($pr->{'forks'}) {5634my$nforks=scalar@{$pr->{'forks'}};5635if($nforks>0) {5636print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5637-title =>"$nforksforks"},"+");5638}else{5639print$cgi->span({-title =>"$nforksforks"},"+");5640}5641}5642print"</td>\n";5643}5644print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5645-class=>"list"},5646 esc_html_match_hl($pr->{'path'},$search_regexp)) .5647"</td>\n".5648"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5649-class=>"list",5650-title =>$pr->{'descr_long'}},5651$search_regexp5652? esc_html_match_hl_chopped($pr->{'descr_long'},5653$pr->{'descr'},$search_regexp)5654: esc_html($pr->{'descr'})) .5655"</td>\n";5656unless($omit_owner) {5657print"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5658}5659unless($omit_age_column) {5660print"<td class=\"". age_class($pr->{'age'}) ."\">".5661(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n";5662}5663print"<td class=\"link\">".5664$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5665$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5666$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5667$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5668($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5669"</td>\n".5670"</tr>\n";5671}5672}56735674sub git_project_list_body {5675# actually uses global variable $project5676my($projlist,$order,$from,$to,$extra,$no_header) =@_;5677my@projects=@$projlist;56785679my$check_forks= gitweb_check_feature('forks');5680my$show_ctags= gitweb_check_feature('ctags');5681my$tagfilter=$show_ctags?$input_params{'ctag'} :undef;5682$check_forks=undef5683if($tagfilter||$search_regexp);56845685# filtering out forks before filling info allows to do less work5686@projects= filter_forks_from_projects_list(\@projects)5687if($check_forks);5688# search_projects_list pre-fills required info5689@projects= search_projects_list(\@projects,5690'search_regexp'=>$search_regexp,5691'tagfilter'=>$tagfilter)5692if($tagfilter||$search_regexp);5693# fill the rest5694my@all_fields= ('descr','descr_long','ctags','category');5695push@all_fields, ('age','age_string')unless($omit_age_column);5696push@all_fields,'owner'unless($omit_owner);5697@projects= fill_project_list_info(\@projects,@all_fields);56985699$order||=$default_projects_order;5700$from=0unlessdefined$from;5701$to=$#projectsif(!defined$to||$#projects<$to);57025703# short circuit5704if($from>$to) {5705print"<center>\n".5706"<b>No such projects found</b><br />\n".5707"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5708"</center>\n<br />\n";5709return;5710}57115712@projects= sort_projects_list(\@projects,$order);57135714if($show_ctags) {5715my$ctags= git_gather_all_ctags(\@projects);5716my$cloud= git_populate_project_tagcloud($ctags);5717print git_show_project_tagcloud($cloud,64);5718}57195720print"<table class=\"project_list\">\n";5721unless($no_header) {5722print"<tr>\n";5723if($check_forks) {5724print"<th></th>\n";5725}5726 print_sort_th('project',$order,'Project');5727 print_sort_th('descr',$order,'Description');5728 print_sort_th('owner',$order,'Owner')unless$omit_owner;5729 print_sort_th('age',$order,'Last Change')unless$omit_age_column;5730print"<th></th>\n".# for links5731"</tr>\n";5732}57335734if($projects_list_group_categories) {5735# only display categories with projects in the $from-$to window5736@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5737my%categories= build_projlist_by_category(\@projects,$from,$to);5738foreachmy$cat(sort keys%categories) {5739unless($cateq"") {5740print"<tr>\n";5741if($check_forks) {5742print"<td></td>\n";5743}5744print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5745print"</tr>\n";5746}57475748 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5749}5750}else{5751 git_project_list_rows(\@projects,$from,$to,$check_forks);5752}57535754if(defined$extra) {5755print"<tr>\n";5756if($check_forks) {5757print"<td></td>\n";5758}5759print"<td colspan=\"5\">$extra</td>\n".5760"</tr>\n";5761}5762print"</table>\n";5763}57645765sub git_log_body {5766# uses global variable $project5767my($commitlist,$from,$to,$refs,$extra) =@_;57685769$from=0unlessdefined$from;5770$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);57715772for(my$i=0;$i<=$to;$i++) {5773my%co= %{$commitlist->[$i]};5774next if!%co;5775my$commit=$co{'id'};5776my$ref= format_ref_marker($refs,$commit);5777 git_print_header_div('commit',5778"<span class=\"age\">$co{'age_string'}</span>".5779 esc_html($co{'title'}) .$ref,5780$commit);5781print"<div class=\"title_text\">\n".5782"<div class=\"log_link\">\n".5783$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5784" | ".5785$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5786" | ".5787$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5788"<br/>\n".5789"</div>\n";5790 git_print_authorship(\%co, -tag =>'span');5791print"<br/>\n</div>\n";57925793print"<div class=\"log_body\">\n";5794 git_print_log($co{'comment'}, -final_empty_line=>1);5795print"</div>\n";5796}5797if($extra) {5798print"<div class=\"page_nav\">\n";5799print"$extra\n";5800print"</div>\n";5801}5802}58035804sub git_shortlog_body {5805# uses global variable $project5806my($commitlist,$from,$to,$refs,$extra) =@_;58075808$from=0unlessdefined$from;5809$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);58105811print"<table class=\"shortlog\">\n";5812my$alternate=1;5813for(my$i=$from;$i<=$to;$i++) {5814my%co= %{$commitlist->[$i]};5815my$commit=$co{'id'};5816my$ref= format_ref_marker($refs,$commit);5817if($alternate) {5818print"<tr class=\"dark\">\n";5819}else{5820print"<tr class=\"light\">\n";5821}5822$alternate^=1;5823# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5824print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5825 format_author_html('td', \%co,10) ."<td>";5826print format_subject_html($co{'title'},$co{'title_short'},5827 href(action=>"commit", hash=>$commit),$ref);5828print"</td>\n".5829"<td class=\"link\">".5830$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5831$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5832$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5833my$snapshot_links= format_snapshot_links($commit);5834if(defined$snapshot_links) {5835print" | ".$snapshot_links;5836}5837print"</td>\n".5838"</tr>\n";5839}5840if(defined$extra) {5841print"<tr>\n".5842"<td colspan=\"4\">$extra</td>\n".5843"</tr>\n";5844}5845print"</table>\n";5846}58475848sub git_history_body {5849# Warning: assumes constant type (blob or tree) during history5850my($commitlist,$from,$to,$refs,$extra,5851$file_name,$file_hash,$ftype) =@_;58525853$from=0unlessdefined$from;5854$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});58555856print"<table class=\"history\">\n";5857my$alternate=1;5858for(my$i=$from;$i<=$to;$i++) {5859my%co= %{$commitlist->[$i]};5860if(!%co) {5861next;5862}5863my$commit=$co{'id'};58645865my$ref= format_ref_marker($refs,$commit);58665867if($alternate) {5868print"<tr class=\"dark\">\n";5869}else{5870print"<tr class=\"light\">\n";5871}5872$alternate^=1;5873print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5874# shortlog: format_author_html('td', \%co, 10)5875 format_author_html('td', \%co,15,3) ."<td>";5876# originally git_history used chop_str($co{'title'}, 50)5877print format_subject_html($co{'title'},$co{'title_short'},5878 href(action=>"commit", hash=>$commit),$ref);5879print"</td>\n".5880"<td class=\"link\">".5881$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5882$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");58835884if($ftypeeq'blob') {5885my$blob_current=$file_hash;5886my$blob_parent= git_get_hash_by_path($commit,$file_name);5887if(defined$blob_current&&defined$blob_parent&&5888$blob_currentne$blob_parent) {5889print" | ".5890$cgi->a({-href => href(action=>"blobdiff",5891 hash=>$blob_current, hash_parent=>$blob_parent,5892 hash_base=>$hash_base, hash_parent_base=>$commit,5893 file_name=>$file_name)},5894"diff to current");5895}5896}5897print"</td>\n".5898"</tr>\n";5899}5900if(defined$extra) {5901print"<tr>\n".5902"<td colspan=\"4\">$extra</td>\n".5903"</tr>\n";5904}5905print"</table>\n";5906}59075908sub git_tags_body {5909# uses global variable $project5910my($taglist,$from,$to,$extra) =@_;5911$from=0unlessdefined$from;5912$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);59135914print"<table class=\"tags\">\n";5915my$alternate=1;5916for(my$i=$from;$i<=$to;$i++) {5917my$entry=$taglist->[$i];5918my%tag=%$entry;5919my$comment=$tag{'subject'};5920my$comment_short;5921if(defined$comment) {5922$comment_short= chop_str($comment,30,5);5923}5924if($alternate) {5925print"<tr class=\"dark\">\n";5926}else{5927print"<tr class=\"light\">\n";5928}5929$alternate^=1;5930if(defined$tag{'age'}) {5931print"<td><i>$tag{'age'}</i></td>\n";5932}else{5933print"<td></td>\n";5934}5935print"<td>".5936$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5937-class=>"list name"}, esc_html($tag{'name'})) .5938"</td>\n".5939"<td>";5940if(defined$comment) {5941print format_subject_html($comment,$comment_short,5942 href(action=>"tag", hash=>$tag{'id'}));5943}5944print"</td>\n".5945"<td class=\"selflink\">";5946if($tag{'type'}eq"tag") {5947print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");5948}else{5949print" ";5950}5951print"</td>\n".5952"<td class=\"link\">"." | ".5953$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});5954if($tag{'reftype'}eq"commit") {5955print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .5956" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");5957}elsif($tag{'reftype'}eq"blob") {5958print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");5959}5960print"</td>\n".5961"</tr>";5962}5963if(defined$extra) {5964print"<tr>\n".5965"<td colspan=\"5\">$extra</td>\n".5966"</tr>\n";5967}5968print"</table>\n";5969}59705971sub git_heads_body {5972# uses global variable $project5973my($headlist,$head_at,$from,$to,$extra) =@_;5974$from=0unlessdefined$from;5975$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);59765977print"<table class=\"heads\">\n";5978my$alternate=1;5979for(my$i=$from;$i<=$to;$i++) {5980my$entry=$headlist->[$i];5981my%ref=%$entry;5982my$curr=defined$head_at&&$ref{'id'}eq$head_at;5983if($alternate) {5984print"<tr class=\"dark\">\n";5985}else{5986print"<tr class=\"light\">\n";5987}5988$alternate^=1;5989print"<td><i>$ref{'age'}</i></td>\n".5990($curr?"<td class=\"current_head\">":"<td>") .5991$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),5992-class=>"list name"},esc_html($ref{'name'})) .5993"</td>\n".5994"<td class=\"link\">".5995$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".5996$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".5997$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .5998"</td>\n".5999"</tr>";6000}6001if(defined$extra) {6002print"<tr>\n".6003"<td colspan=\"3\">$extra</td>\n".6004"</tr>\n";6005}6006print"</table>\n";6007}60086009# Display a single remote block6010sub git_remote_block {6011my($remote,$rdata,$limit,$head) =@_;60126013my$heads=$rdata->{'heads'};6014my$fetch=$rdata->{'fetch'};6015my$push=$rdata->{'push'};60166017my$urls_table="<table class=\"projects_list\">\n";60186019if(defined$fetch) {6020if($fetcheq$push) {6021$urls_table.= format_repo_url("URL",$fetch);6022}else{6023$urls_table.= format_repo_url("Fetch URL",$fetch);6024$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;6025}6026}elsif(defined$push) {6027$urls_table.= format_repo_url("Push URL",$push);6028}else{6029$urls_table.= format_repo_url("","No remote URL");6030}60316032$urls_table.="</table>\n";60336034my$dots;6035if(defined$limit&&$limit<@$heads) {6036$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");6037}60386039print$urls_table;6040 git_heads_body($heads,$head,0,$limit,$dots);6041}60426043# Display a list of remote names with the respective fetch and push URLs6044sub git_remotes_list {6045my($remotedata,$limit) =@_;6046print"<table class=\"heads\">\n";6047my$alternate=1;6048my@remotes=sort keys%$remotedata;60496050my$limited=$limit&&$limit<@remotes;60516052$#remotes=$limit-1if$limited;60536054while(my$remote=shift@remotes) {6055my$rdata=$remotedata->{$remote};6056my$fetch=$rdata->{'fetch'};6057my$push=$rdata->{'push'};6058if($alternate) {6059print"<tr class=\"dark\">\n";6060}else{6061print"<tr class=\"light\">\n";6062}6063$alternate^=1;6064print"<td>".6065$cgi->a({-href=> href(action=>'remotes', hash=>$remote),6066-class=>"list name"},esc_html($remote)) .6067"</td>";6068print"<td class=\"link\">".6069(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .6070" | ".6071(defined$push?$cgi->a({-href=>$push},"push") :"push") .6072"</td>";60736074print"</tr>\n";6075}60766077if($limited) {6078print"<tr>\n".6079"<td colspan=\"3\">".6080$cgi->a({-href => href(action=>"remotes")},"...") .6081"</td>\n"."</tr>\n";6082}60836084print"</table>";6085}60866087# Display remote heads grouped by remote, unless there are too many6088# remotes, in which case we only display the remote names6089sub git_remotes_body {6090my($remotedata,$limit,$head) =@_;6091if($limitand$limit<keys%$remotedata) {6092 git_remotes_list($remotedata,$limit);6093}else{6094 fill_remote_heads($remotedata);6095while(my($remote,$rdata) =each%$remotedata) {6096 git_print_section({-class=>"remote", -id=>$remote},6097["remotes",$remote,$remote],sub{6098 git_remote_block($remote,$rdata,$limit,$head);6099});6100}6101}6102}61036104sub git_search_message {6105my%co=@_;61066107my$greptype;6108if($searchtypeeq'commit') {6109$greptype="--grep=";6110}elsif($searchtypeeq'author') {6111$greptype="--author=";6112}elsif($searchtypeeq'committer') {6113$greptype="--committer=";6114}6115$greptype.=$searchtext;6116my@commitlist= parse_commits($hash,101, (100*$page),undef,6117$greptype,'--regexp-ignore-case',6118$search_use_regexp?'--extended-regexp':'--fixed-strings');61196120my$paging_nav='';6121if($page>0) {6122$paging_nav.=6123$cgi->a({-href => href(-replay=>1, page=>undef)},6124"first") .6125" ⋅ ".6126$cgi->a({-href => href(-replay=>1, page=>$page-1),6127-accesskey =>"p", -title =>"Alt-p"},"prev");6128}else{6129$paging_nav.="first ⋅ prev";6130}6131my$next_link='';6132if($#commitlist>=100) {6133$next_link=6134$cgi->a({-href => href(-replay=>1, page=>$page+1),6135-accesskey =>"n", -title =>"Alt-n"},"next");6136$paging_nav.=" ⋅$next_link";6137}else{6138$paging_nav.=" ⋅ next";6139}61406141 git_header_html();61426143 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);6144 git_print_header_div('commit', esc_html($co{'title'}),$hash);6145if($page==0&& !@commitlist) {6146print"<p>No match.</p>\n";6147}else{6148 git_search_grep_body(\@commitlist,0,99,$next_link);6149}61506151 git_footer_html();6152}61536154sub git_search_changes {6155my%co=@_;61566157local$/="\n";6158open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,6159'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",6160($search_use_regexp?'--pickaxe-regex': ())6161or die_error(500,"Open git-log failed");61626163 git_header_html();61646165 git_print_page_nav('','',$hash,$co{'tree'},$hash);6166 git_print_header_div('commit', esc_html($co{'title'}),$hash);61676168print"<table class=\"pickaxe search\">\n";6169my$alternate=1;6170undef%co;6171my@files;6172while(my$line= <$fd>) {6173chomp$line;6174next unless$line;61756176my%set= parse_difftree_raw_line($line);6177if(defined$set{'commit'}) {6178# finish previous commit6179if(%co) {6180print"</td>\n".6181"<td class=\"link\">".6182$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6183"commit") .6184" | ".6185$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6186 hash_base=>$co{'id'})},6187"tree") .6188"</td>\n".6189"</tr>\n";6190}61916192if($alternate) {6193print"<tr class=\"dark\">\n";6194}else{6195print"<tr class=\"light\">\n";6196}6197$alternate^=1;6198%co= parse_commit($set{'commit'});6199my$author= chop_and_escape_str($co{'author_name'},15,5);6200print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6201"<td><i>$author</i></td>\n".6202"<td>".6203$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6204-class=>"list subject"},6205 chop_and_escape_str($co{'title'},50) ."<br/>");6206}elsif(defined$set{'to_id'}) {6207next if($set{'to_id'} =~m/^0{40}$/);62086209print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},6210 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),6211-class=>"list"},6212"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .6213"<br/>\n";6214}6215}6216close$fd;62176218# finish last commit (warning: repetition!)6219if(%co) {6220print"</td>\n".6221"<td class=\"link\">".6222$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6223"commit") .6224" | ".6225$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6226 hash_base=>$co{'id'})},6227"tree") .6228"</td>\n".6229"</tr>\n";6230}62316232print"</table>\n";62336234 git_footer_html();6235}62366237sub git_search_files {6238my%co=@_;62396240local$/="\n";6241open my$fd,"-|", git_cmd(),'grep','-n','-z',6242$search_use_regexp? ('-E','-i') :'-F',6243$searchtext,$co{'tree'}6244or die_error(500,"Open git-grep failed");62456246 git_header_html();62476248 git_print_page_nav('','',$hash,$co{'tree'},$hash);6249 git_print_header_div('commit', esc_html($co{'title'}),$hash);62506251print"<table class=\"grep_search\">\n";6252my$alternate=1;6253my$matches=0;6254my$lastfile='';6255my$file_href;6256while(my$line= <$fd>) {6257chomp$line;6258my($file,$lno,$ltext,$binary);6259last if($matches++>1000);6260if($line=~/^Binary file (.+) matches$/) {6261$file=$1;6262$binary=1;6263}else{6264($file,$lno,$ltext) =split(/\0/,$line,3);6265$file=~s/^$co{'tree'}://;6266}6267if($filene$lastfile) {6268$lastfileand print"</td></tr>\n";6269if($alternate++) {6270print"<tr class=\"dark\">\n";6271}else{6272print"<tr class=\"light\">\n";6273}6274$file_href= href(action=>"blob", hash_base=>$co{'id'},6275 file_name=>$file);6276print"<td class=\"list\">".6277$cgi->a({-href =>$file_href, -class=>"list"}, esc_path($file));6278print"</td><td>\n";6279$lastfile=$file;6280}6281if($binary) {6282print"<div class=\"binary\">Binary file</div>\n";6283}else{6284$ltext= untabify($ltext);6285if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6286$ltext= esc_html($1, -nbsp=>1);6287$ltext.='<span class="match">';6288$ltext.= esc_html($2, -nbsp=>1);6289$ltext.='</span>';6290$ltext.= esc_html($3, -nbsp=>1);6291}else{6292$ltext= esc_html($ltext, -nbsp=>1);6293}6294print"<div class=\"pre\">".6295$cgi->a({-href =>$file_href.'#l'.$lno,6296-class=>"linenr"},sprintf('%4i',$lno)) .6297' '.$ltext."</div>\n";6298}6299}6300if($lastfile) {6301print"</td></tr>\n";6302if($matches>1000) {6303print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6304}6305}else{6306print"<div class=\"diff nodifferences\">No matches found</div>\n";6307}6308close$fd;63096310print"</table>\n";63116312 git_footer_html();6313}63146315sub git_search_grep_body {6316my($commitlist,$from,$to,$extra) =@_;6317$from=0unlessdefined$from;6318$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);63196320print"<table class=\"commit_search\">\n";6321my$alternate=1;6322for(my$i=$from;$i<=$to;$i++) {6323my%co= %{$commitlist->[$i]};6324if(!%co) {6325next;6326}6327my$commit=$co{'id'};6328if($alternate) {6329print"<tr class=\"dark\">\n";6330}else{6331print"<tr class=\"light\">\n";6332}6333$alternate^=1;6334print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6335 format_author_html('td', \%co,15,5) .6336"<td>".6337$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6338-class=>"list subject"},6339 chop_and_escape_str($co{'title'},50) ."<br/>");6340my$comment=$co{'comment'};6341foreachmy$line(@$comment) {6342if($line=~m/^(.*?)($search_regexp)(.*)$/i) {6343my($lead,$match,$trail) = ($1,$2,$3);6344$match= chop_str($match,70,5,'center');6345my$contextlen=int((80-length($match))/2);6346$contextlen=30if($contextlen>30);6347$lead= chop_str($lead,$contextlen,10,'left');6348$trail= chop_str($trail,$contextlen,10,'right');63496350$lead= esc_html($lead);6351$match= esc_html($match);6352$trail= esc_html($trail);63536354print"$lead<span class=\"match\">$match</span>$trail<br />";6355}6356}6357print"</td>\n".6358"<td class=\"link\">".6359$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6360" | ".6361$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .6362" | ".6363$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6364print"</td>\n".6365"</tr>\n";6366}6367if(defined$extra) {6368print"<tr>\n".6369"<td colspan=\"3\">$extra</td>\n".6370"</tr>\n";6371}6372print"</table>\n";6373}63746375## ======================================================================6376## ======================================================================6377## actions63786379sub git_project_list {6380my$order=$input_params{'order'};6381if(defined$order&&$order!~m/none|project|descr|owner|age/) {6382 die_error(400,"Unknown order parameter");6383}63846385my@list= git_get_projects_list($project_filter,$strict_export);6386if(!@list) {6387 die_error(404,"No projects found");6388}63896390 git_header_html();6391if(defined$home_text&& -f $home_text) {6392print"<div class=\"index_include\">\n";6393 insert_file($home_text);6394print"</div>\n";6395}63966397 git_project_search_form($searchtext,$search_use_regexp);6398 git_project_list_body(\@list,$order);6399 git_footer_html();6400}64016402sub git_forks {6403my$order=$input_params{'order'};6404if(defined$order&&$order!~m/none|project|descr|owner|age/) {6405 die_error(400,"Unknown order parameter");6406}64076408my$filter=$project;6409$filter=~s/\.git$//;6410my@list= git_get_projects_list($filter);6411if(!@list) {6412 die_error(404,"No forks found");6413}64146415 git_header_html();6416 git_print_page_nav('','');6417 git_print_header_div('summary',"$projectforks");6418 git_project_list_body(\@list,$order);6419 git_footer_html();6420}64216422sub git_project_index {6423my@projects= git_get_projects_list($project_filter,$strict_export);6424if(!@projects) {6425 die_error(404,"No projects found");6426}64276428print$cgi->header(6429-type =>'text/plain',6430-charset =>'utf-8',6431-content_disposition =>'inline; filename="index.aux"');64326433foreachmy$pr(@projects) {6434if(!exists$pr->{'owner'}) {6435$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");6436}64376438my($path,$owner) = ($pr->{'path'},$pr->{'owner'});6439# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '6440$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6441$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6442$path=~s/ /\+/g;6443$owner=~s/ /\+/g;64446445print"$path$owner\n";6446}6447}64486449sub git_summary {6450my$descr= git_get_project_description($project) ||"none";6451my%co= parse_commit("HEAD");6452my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();6453my$head=$co{'id'};6454my$remote_heads= gitweb_check_feature('remote_heads');64556456my$owner= git_get_project_owner($project);64576458my$refs= git_get_references();6459# These get_*_list functions return one more to allow us to see if6460# there are more ...6461my@taglist= git_get_tags_list(16);6462my@headlist= git_get_heads_list(16);6463my%remotedata=$remote_heads? git_get_remotes_list() : ();6464my@forklist;6465my$check_forks= gitweb_check_feature('forks');64666467if($check_forks) {6468# find forks of a project6469my$filter=$project;6470$filter=~s/\.git$//;6471@forklist= git_get_projects_list($filter);6472# filter out forks of forks6473@forklist= filter_forks_from_projects_list(\@forklist)6474if(@forklist);6475}64766477 git_header_html();6478 git_print_page_nav('summary','',$head);64796480print"<div class=\"title\"> </div>\n";6481print"<table class=\"projects_list\">\n".6482"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n";6483if($ownerand not$omit_owner) {6484print"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";6485}6486if(defined$cd{'rfc2822'}) {6487print"<tr id=\"metadata_lchange\"><td>last change</td>".6488"<td>".format_timestamp_html(\%cd)."</td></tr>\n";6489}64906491# use per project git URL list in $projectroot/$project/cloneurl6492# or make project git URL from git base URL and project name6493my$url_tag="URL";6494my@url_list= git_get_project_url_list($project);6495@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;6496foreachmy$git_url(@url_list) {6497next unless$git_url;6498print format_repo_url($url_tag,$git_url);6499$url_tag="";6500}65016502# Tag cloud6503my$show_ctags= gitweb_check_feature('ctags');6504if($show_ctags) {6505my$ctags= git_get_project_ctags($project);6506if(%$ctags) {6507# without ability to add tags, don't show if there are none6508my$cloud= git_populate_project_tagcloud($ctags);6509print"<tr id=\"metadata_ctags\">".6510"<td>content tags</td>".6511"<td>".git_show_project_tagcloud($cloud,48)."</td>".6512"</tr>\n";6513}6514}65156516print"</table>\n";65176518# If XSS prevention is on, we don't include README.html.6519# TODO: Allow a readme in some safe format.6520if(!$prevent_xss&& -s "$projectroot/$project/README.html") {6521print"<div class=\"title\">readme</div>\n".6522"<div class=\"readme\">\n";6523 insert_file("$projectroot/$project/README.html");6524print"\n</div>\n";# class="readme"6525}65266527# we need to request one more than 16 (0..15) to check if6528# those 16 are all6529my@commitlist=$head? parse_commits($head,17) : ();6530if(@commitlist) {6531 git_print_header_div('shortlog');6532 git_shortlog_body(\@commitlist,0,15,$refs,6533$#commitlist<=15?undef:6534$cgi->a({-href => href(action=>"shortlog")},"..."));6535}65366537if(@taglist) {6538 git_print_header_div('tags');6539 git_tags_body(\@taglist,0,15,6540$#taglist<=15?undef:6541$cgi->a({-href => href(action=>"tags")},"..."));6542}65436544if(@headlist) {6545 git_print_header_div('heads');6546 git_heads_body(\@headlist,$head,0,15,6547$#headlist<=15?undef:6548$cgi->a({-href => href(action=>"heads")},"..."));6549}65506551if(%remotedata) {6552 git_print_header_div('remotes');6553 git_remotes_body(\%remotedata,15,$head);6554}65556556if(@forklist) {6557 git_print_header_div('forks');6558 git_project_list_body(\@forklist,'age',0,15,6559$#forklist<=15?undef:6560$cgi->a({-href => href(action=>"forks")},"..."),6561'no_header');6562}65636564 git_footer_html();6565}65666567sub git_tag {6568my%tag= parse_tag($hash);65696570if(!%tag) {6571 die_error(404,"Unknown tag object");6572}65736574my$head= git_get_head_hash($project);6575 git_header_html();6576 git_print_page_nav('','',$head,undef,$head);6577 git_print_header_div('commit', esc_html($tag{'name'}),$hash);6578print"<div class=\"title_text\">\n".6579"<table class=\"object_header\">\n".6580"<tr>\n".6581"<td>object</td>\n".6582"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6583$tag{'object'}) ."</td>\n".6584"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6585$tag{'type'}) ."</td>\n".6586"</tr>\n";6587if(defined($tag{'author'})) {6588 git_print_authorship_rows(\%tag,'author');6589}6590print"</table>\n\n".6591"</div>\n";6592print"<div class=\"page_body\">";6593my$comment=$tag{'comment'};6594foreachmy$line(@$comment) {6595chomp$line;6596print esc_html($line, -nbsp=>1) ."<br/>\n";6597}6598print"</div>\n";6599 git_footer_html();6600}66016602sub git_blame_common {6603my$format=shift||'porcelain';6604if($formateq'porcelain'&&$input_params{'javascript'}) {6605$format='incremental';6606$action='blame_incremental';# for page title etc6607}66086609# permissions6610 gitweb_check_feature('blame')6611or die_error(403,"Blame view not allowed");66126613# error checking6614 die_error(400,"No file name given")unless$file_name;6615$hash_base||= git_get_head_hash($project);6616 die_error(404,"Couldn't find base commit")unless$hash_base;6617my%co= parse_commit($hash_base)6618or die_error(404,"Commit not found");6619my$ftype="blob";6620if(!defined$hash) {6621$hash= git_get_hash_by_path($hash_base,$file_name,"blob")6622or die_error(404,"Error looking up file");6623}else{6624$ftype= git_get_type($hash);6625if($ftype!~"blob") {6626 die_error(400,"Object is not a blob");6627}6628}66296630my$fd;6631if($formateq'incremental') {6632# get file contents (as base)6633open$fd,"-|", git_cmd(),'cat-file','blob',$hash6634or die_error(500,"Open git-cat-file failed");6635}elsif($formateq'data') {6636# run git-blame --incremental6637open$fd,"-|", git_cmd(),"blame","--incremental",6638$hash_base,"--",$file_name6639or die_error(500,"Open git-blame --incremental failed");6640}else{6641# run git-blame --porcelain6642open$fd,"-|", git_cmd(),"blame",'-p',6643$hash_base,'--',$file_name6644or die_error(500,"Open git-blame --porcelain failed");6645}6646binmode$fd,':utf8';66476648# incremental blame data returns early6649if($formateq'data') {6650print$cgi->header(6651-type=>"text/plain", -charset =>"utf-8",6652-status=>"200 OK");6653local$| =1;# output autoflush6654while(my$line= <$fd>) {6655print to_utf8($line);6656}6657close$fd6658or print"ERROR$!\n";66596660print'END';6661if(defined$t0&& gitweb_check_feature('timed')) {6662print' '.6663 tv_interval($t0, [ gettimeofday() ]).6664' '.$number_of_git_cmds;6665}6666print"\n";66676668return;6669}66706671# page header6672 git_header_html();6673my$formats_nav=6674$cgi->a({-href => href(action=>"blob", -replay=>1)},6675"blob") .6676" | ";6677if($formateq'incremental') {6678$formats_nav.=6679$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},6680"blame") ." (non-incremental)";6681}else{6682$formats_nav.=6683$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},6684"blame") ." (incremental)";6685}6686$formats_nav.=6687" | ".6688$cgi->a({-href => href(action=>"history", -replay=>1)},6689"history") .6690" | ".6691$cgi->a({-href => href(action=>$action, file_name=>$file_name)},6692"HEAD");6693 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6694 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6695 git_print_page_path($file_name,$ftype,$hash_base);66966697# page body6698if($formateq'incremental') {6699print"<noscript>\n<div class=\"error\"><center><b>\n".6700"This page requires JavaScript to run.\nUse ".6701$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},6702'this page').6703" instead.\n".6704"</b></center></div>\n</noscript>\n";67056706print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;6707}67086709print qq!<div class="page_body">\n!;6710print qq!<div id="progress_info">.../ ...</div>\n!6711if($formateq'incremental');6712print qq!<table id="blame_table"class="blame" width="100%">\n!.6713#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.6714 qq!<thead>\n!.6715 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.6716 qq!</thead>\n!.6717 qq!<tbody>\n!;67186719my@rev_color=qw(light dark);6720my$num_colors=scalar(@rev_color);6721my$current_color=0;67226723if($formateq'incremental') {6724my$color_class=$rev_color[$current_color];67256726#contents of a file6727my$linenr=0;6728 LINE:6729while(my$line= <$fd>) {6730chomp$line;6731$linenr++;67326733print qq!<tr id="l$linenr"class="$color_class">!.6734 qq!<td class="sha1"><a href=""> </a></td>!.6735 qq!<td class="linenr">!.6736 qq!<a class="linenr" href="">$linenr</a></td>!;6737print qq!<td class="pre">! . esc_html($line) ."</td>\n";6738print qq!</tr>\n!;6739}67406741}else{# porcelain, i.e. ordinary blame6742my%metainfo= ();# saves information about commits67436744# blame data6745 LINE:6746while(my$line= <$fd>) {6747chomp$line;6748# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]6749# no <lines in group> for subsequent lines in group of lines6750my($full_rev,$orig_lineno,$lineno,$group_size) =6751($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);6752if(!exists$metainfo{$full_rev}) {6753$metainfo{$full_rev} = {'nprevious'=>0};6754}6755my$meta=$metainfo{$full_rev};6756my$data;6757while($data= <$fd>) {6758chomp$data;6759last if($data=~s/^\t//);# contents of line6760if($data=~/^(\S+)(?: (.*))?$/) {6761$meta->{$1} =$2unlessexists$meta->{$1};6762}6763if($data=~/^previous /) {6764$meta->{'nprevious'}++;6765}6766}6767my$short_rev=substr($full_rev,0,8);6768my$author=$meta->{'author'};6769my%date=6770 parse_date($meta->{'author-time'},$meta->{'author-tz'});6771my$date=$date{'iso-tz'};6772if($group_size) {6773$current_color= ($current_color+1) %$num_colors;6774}6775my$tr_class=$rev_color[$current_color];6776$tr_class.=' boundary'if(exists$meta->{'boundary'});6777$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);6778$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);6779print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";6780if($group_size) {6781print"<td class=\"sha1\"";6782print" title=\"". esc_html($author) .",$date\"";6783print" rowspan=\"$group_size\""if($group_size>1);6784print">";6785print$cgi->a({-href => href(action=>"commit",6786 hash=>$full_rev,6787 file_name=>$file_name)},6788 esc_html($short_rev));6789if($group_size>=2) {6790my@author_initials= ($author=~/\b([[:upper:]])\B/g);6791if(@author_initials) {6792print"<br />".6793 esc_html(join('',@author_initials));6794# or join('.', ...)6795}6796}6797print"</td>\n";6798}6799# 'previous' <sha1 of parent commit> <filename at commit>6800if(exists$meta->{'previous'} &&6801$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {6802$meta->{'parent'} =$1;6803$meta->{'file_parent'} = unquote($2);6804}6805my$linenr_commit=6806exists($meta->{'parent'}) ?6807$meta->{'parent'} :$full_rev;6808my$linenr_filename=6809exists($meta->{'file_parent'}) ?6810$meta->{'file_parent'} : unquote($meta->{'filename'});6811my$blamed= href(action =>'blame',6812 file_name =>$linenr_filename,6813 hash_base =>$linenr_commit);6814print"<td class=\"linenr\">";6815print$cgi->a({ -href =>"$blamed#l$orig_lineno",6816-class=>"linenr"},6817 esc_html($lineno));6818print"</td>";6819print"<td class=\"pre\">". esc_html($data) ."</td>\n";6820print"</tr>\n";6821}# end while68226823}68246825# footer6826print"</tbody>\n".6827"</table>\n";# class="blame"6828print"</div>\n";# class="blame_body"6829close$fd6830or print"Reading blob failed\n";68316832 git_footer_html();6833}68346835sub git_blame {6836 git_blame_common();6837}68386839sub git_blame_incremental {6840 git_blame_common('incremental');6841}68426843sub git_blame_data {6844 git_blame_common('data');6845}68466847sub git_tags {6848my$head= git_get_head_hash($project);6849 git_header_html();6850 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6851 git_print_header_div('summary',$project);68526853my@tagslist= git_get_tags_list();6854if(@tagslist) {6855 git_tags_body(\@tagslist);6856}6857 git_footer_html();6858}68596860sub git_heads {6861my$head= git_get_head_hash($project);6862 git_header_html();6863 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6864 git_print_header_div('summary',$project);68656866my@headslist= git_get_heads_list();6867if(@headslist) {6868 git_heads_body(\@headslist,$head);6869}6870 git_footer_html();6871}68726873# used both for single remote view and for list of all the remotes6874sub git_remotes {6875 gitweb_check_feature('remote_heads')6876or die_error(403,"Remote heads view is disabled");68776878my$head= git_get_head_hash($project);6879my$remote=$input_params{'hash'};68806881my$remotedata= git_get_remotes_list($remote);6882 die_error(500,"Unable to get remote information")unlessdefined$remotedata;68836884unless(%$remotedata) {6885 die_error(404,defined$remote?6886"Remote$remotenot found":6887"No remotes found");6888}68896890 git_header_html(undef,undef, -action_extra =>$remote);6891 git_print_page_nav('','',$head,undef,$head,6892 format_ref_views($remote?'':'remotes'));68936894 fill_remote_heads($remotedata);6895if(defined$remote) {6896 git_print_header_div('remotes',"$remoteremote for$project");6897 git_remote_block($remote,$remotedata->{$remote},undef,$head);6898}else{6899 git_print_header_div('summary',"$projectremotes");6900 git_remotes_body($remotedata,undef,$head);6901}69026903 git_footer_html();6904}69056906sub git_blob_plain {6907my$type=shift;6908my$expires;69096910if(!defined$hash) {6911if(defined$file_name) {6912my$base=$hash_base|| git_get_head_hash($project);6913$hash= git_get_hash_by_path($base,$file_name,"blob")6914or die_error(404,"Cannot find file");6915}else{6916 die_error(400,"No file name defined");6917}6918}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6919# blobs defined by non-textual hash id's can be cached6920$expires="+1d";6921}69226923open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6924or die_error(500,"Open git-cat-file blob '$hash' failed");69256926# content-type (can include charset)6927$type= blob_contenttype($fd,$file_name,$type);69286929# "save as" filename, even when no $file_name is given6930my$save_as="$hash";6931if(defined$file_name) {6932$save_as=$file_name;6933}elsif($type=~m/^text\//) {6934$save_as.='.txt';6935}69366937# With XSS prevention on, blobs of all types except a few known safe6938# ones are served with "Content-Disposition: attachment" to make sure6939# they don't run in our security domain. For certain image types,6940# blob view writes an <img> tag referring to blob_plain view, and we6941# want to be sure not to break that by serving the image as an6942# attachment (though Firefox 3 doesn't seem to care).6943my$sandbox=$prevent_xss&&6944$type!~m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;69456946# serve text/* as text/plain6947if($prevent_xss&&6948($type=~m!^text/[a-z]+\b(.*)$!||6949($type=~m!^[a-z]+/[a-z]\+xml\b(.*)$!&& -T $fd))) {6950my$rest=$1;6951$rest=defined$rest?$rest:'';6952$type="text/plain$rest";6953}69546955print$cgi->header(6956-type =>$type,6957-expires =>$expires,6958-content_disposition =>6959($sandbox?'attachment':'inline')6960.'; filename="'.$save_as.'"');6961local$/=undef;6962binmode STDOUT,':raw';6963print<$fd>;6964binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6965close$fd;6966}69676968sub git_blob {6969my$expires;69706971if(!defined$hash) {6972if(defined$file_name) {6973my$base=$hash_base|| git_get_head_hash($project);6974$hash= git_get_hash_by_path($base,$file_name,"blob")6975or die_error(404,"Cannot find file");6976}else{6977 die_error(400,"No file name defined");6978}6979}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6980# blobs defined by non-textual hash id's can be cached6981$expires="+1d";6982}69836984my$have_blame= gitweb_check_feature('blame');6985open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6986or die_error(500,"Couldn't cat$file_name,$hash");6987my$mimetype= blob_mimetype($fd,$file_name);6988# use 'blob_plain' (aka 'raw') view for files that cannot be displayed6989if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {6990close$fd;6991return git_blob_plain($mimetype);6992}6993# we can have blame only for text/* mimetype6994$have_blame&&= ($mimetype=~m!^text/!);69956996my$highlight= gitweb_check_feature('highlight');6997my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);6998$fd= run_highlighter($fd,$highlight,$syntax)6999if$syntax;70007001 git_header_html(undef,$expires);7002my$formats_nav='';7003if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7004if(defined$file_name) {7005if($have_blame) {7006$formats_nav.=7007$cgi->a({-href => href(action=>"blame", -replay=>1)},7008"blame") .7009" | ";7010}7011$formats_nav.=7012$cgi->a({-href => href(action=>"history", -replay=>1)},7013"history") .7014" | ".7015$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},7016"raw") .7017" | ".7018$cgi->a({-href => href(action=>"blob",7019 hash_base=>"HEAD", file_name=>$file_name)},7020"HEAD");7021}else{7022$formats_nav.=7023$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},7024"raw");7025}7026 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7027 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7028}else{7029print"<div class=\"page_nav\">\n".7030"<br/><br/></div>\n".7031"<div class=\"title\">".esc_html($hash)."</div>\n";7032}7033 git_print_page_path($file_name,"blob",$hash_base);7034print"<div class=\"page_body\">\n";7035if($mimetype=~m!^image/!) {7036print qq!<img type="!.esc_attr($mimetype).qq!"!;7037if($file_name) {7038print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;7039}7040print qq! src="! .7041 href(action=>"blob_plain", hash=>$hash,7042 hash_base=>$hash_base, file_name=>$file_name) .7043 qq!"/>\n!;7044}else{7045my$nr;7046while(my$line= <$fd>) {7047chomp$line;7048$nr++;7049$line= untabify($line);7050printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,7051$nr, esc_attr(href(-replay =>1)),$nr,$nr,7052$syntax? sanitize($line) : esc_html($line, -nbsp=>1);7053}7054}7055close$fd7056or print"Reading blob failed.\n";7057print"</div>";7058 git_footer_html();7059}70607061sub git_tree {7062if(!defined$hash_base) {7063$hash_base="HEAD";7064}7065if(!defined$hash) {7066if(defined$file_name) {7067$hash= git_get_hash_by_path($hash_base,$file_name,"tree");7068}else{7069$hash=$hash_base;7070}7071}7072 die_error(404,"No such tree")unlessdefined($hash);70737074my$show_sizes= gitweb_check_feature('show-sizes');7075my$have_blame= gitweb_check_feature('blame');70767077my@entries= ();7078{7079local$/="\0";7080open my$fd,"-|", git_cmd(),"ls-tree",'-z',7081($show_sizes?'-l': ()),@extra_options,$hash7082or die_error(500,"Open git-ls-tree failed");7083@entries=map{chomp;$_} <$fd>;7084close$fd7085or die_error(404,"Reading tree failed");7086}70877088my$refs= git_get_references();7089my$ref= format_ref_marker($refs,$hash_base);7090 git_header_html();7091my$basedir='';7092if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7093my@views_nav= ();7094if(defined$file_name) {7095push@views_nav,7096$cgi->a({-href => href(action=>"history", -replay=>1)},7097"history"),7098$cgi->a({-href => href(action=>"tree",7099 hash_base=>"HEAD", file_name=>$file_name)},7100"HEAD"),7101}7102my$snapshot_links= format_snapshot_links($hash);7103if(defined$snapshot_links) {7104# FIXME: Should be available when we have no hash base as well.7105push@views_nav,$snapshot_links;7106}7107 git_print_page_nav('tree','',$hash_base,undef,undef,7108join(' | ',@views_nav));7109 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);7110}else{7111undef$hash_base;7112print"<div class=\"page_nav\">\n";7113print"<br/><br/></div>\n";7114print"<div class=\"title\">".esc_html($hash)."</div>\n";7115}7116if(defined$file_name) {7117$basedir=$file_name;7118if($basedirne''&&substr($basedir, -1)ne'/') {7119$basedir.='/';7120}7121 git_print_page_path($file_name,'tree',$hash_base);7122}7123print"<div class=\"page_body\">\n";7124print"<table class=\"tree\">\n";7125my$alternate=1;7126# '..' (top directory) link if possible7127if(defined$hash_base&&7128defined$file_name&&$file_name=~m![^/]+$!) {7129if($alternate) {7130print"<tr class=\"dark\">\n";7131}else{7132print"<tr class=\"light\">\n";7133}7134$alternate^=1;71357136my$up=$file_name;7137$up=~s!/?[^/]+$!!;7138undef$upunless$up;7139# based on git_print_tree_entry7140print'<td class="mode">'. mode_str('040000') ."</td>\n";7141print'<td class="size"> </td>'."\n"if$show_sizes;7142print'<td class="list">';7143print$cgi->a({-href => href(action=>"tree",7144 hash_base=>$hash_base,7145 file_name=>$up)},7146"..");7147print"</td>\n";7148print"<td class=\"link\"></td>\n";71497150print"</tr>\n";7151}7152foreachmy$line(@entries) {7153my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);71547155if($alternate) {7156print"<tr class=\"dark\">\n";7157}else{7158print"<tr class=\"light\">\n";7159}7160$alternate^=1;71617162 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);71637164print"</tr>\n";7165}7166print"</table>\n".7167"</div>";7168 git_footer_html();7169}71707171sub snapshot_name {7172my($project,$hash) =@_;71737174# path/to/project.git -> project7175# path/to/project/.git -> project7176my$name= to_utf8($project);7177$name=~ s,([^/])/*\.git$,$1,;7178$name= basename($name);7179# sanitize name7180$name=~s/[[:cntrl:]]/?/g;71817182my$ver=$hash;7183if($hash=~/^[0-9a-fA-F]+$/) {7184# shorten SHA-1 hash7185my$full_hash= git_get_full_hash($project,$hash);7186if($full_hash=~/^$hash/&&length($hash) >7) {7187$ver= git_get_short_hash($project,$hash);7188}7189}elsif($hash=~m!^refs/tags/(.*)$!) {7190# tags don't need shortened SHA-1 hash7191$ver=$1;7192}else{7193# branches and other need shortened SHA-1 hash7194if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {7195$ver=$1;7196}7197$ver.='-'. git_get_short_hash($project,$hash);7198}7199# in case of hierarchical branch names7200$ver=~s!/!.!g;72017202# name = project-version_string7203$name="$name-$ver";72047205returnwantarray? ($name,$name) :$name;7206}72077208sub exit_if_unmodified_since {7209my($latest_epoch) =@_;7210our$cgi;72117212my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7213if(defined$if_modified) {7214my$since;7215if(eval{require HTTP::Date;1; }) {7216$since= HTTP::Date::str2time($if_modified);7217}elsif(eval{require Time::ParseDate;1; }) {7218$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7219}7220if(defined$since&&$latest_epoch<=$since) {7221my%latest_date= parse_date($latest_epoch);7222print$cgi->header(7223-last_modified =>$latest_date{'rfc2822'},7224-status =>'304 Not Modified');7225goto DONE_GITWEB;7226}7227}7228}72297230sub git_snapshot {7231my$format=$input_params{'snapshot_format'};7232if(!@snapshot_fmts) {7233 die_error(403,"Snapshots not allowed");7234}7235# default to first supported snapshot format7236$format||=$snapshot_fmts[0];7237if($format!~m/^[a-z0-9]+$/) {7238 die_error(400,"Invalid snapshot format parameter");7239}elsif(!exists($known_snapshot_formats{$format})) {7240 die_error(400,"Unknown snapshot format");7241}elsif($known_snapshot_formats{$format}{'disabled'}) {7242 die_error(403,"Snapshot format not allowed");7243}elsif(!grep($_eq$format,@snapshot_fmts)) {7244 die_error(403,"Unsupported snapshot format");7245}72467247my$type= git_get_type("$hash^{}");7248if(!$type) {7249 die_error(404,'Object does not exist');7250}elsif($typeeq'blob') {7251 die_error(400,'Object is not a tree-ish');7252}72537254my($name,$prefix) = snapshot_name($project,$hash);7255my$filename="$name$known_snapshot_formats{$format}{'suffix'}";72567257my%co= parse_commit($hash);7258 exit_if_unmodified_since($co{'committer_epoch'})if%co;72597260my$cmd= quote_command(7261 git_cmd(),'archive',7262"--format=$known_snapshot_formats{$format}{'format'}",7263"--prefix=$prefix/",$hash);7264if(exists$known_snapshot_formats{$format}{'compressor'}) {7265$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});7266}72677268$filename=~s/(["\\])/\\$1/g;7269my%latest_date;7270if(%co) {7271%latest_date= parse_date($co{'committer_epoch'},$co{'committer_tz'});7272}72737274print$cgi->header(7275-type =>$known_snapshot_formats{$format}{'type'},7276-content_disposition =>'inline; filename="'.$filename.'"',7277%co? (-last_modified =>$latest_date{'rfc2822'}) : (),7278-status =>'200 OK');72797280open my$fd,"-|",$cmd7281or die_error(500,"Execute git-archive failed");7282binmode STDOUT,':raw';7283print<$fd>;7284binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi7285close$fd;7286}72877288sub git_log_generic {7289my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;72907291my$head= git_get_head_hash($project);7292if(!defined$base) {7293$base=$head;7294}7295if(!defined$page) {7296$page=0;7297}7298my$refs= git_get_references();72997300my$commit_hash=$base;7301if(defined$parent) {7302$commit_hash="$parent..$base";7303}7304my@commitlist=7305 parse_commits($commit_hash,101, (100*$page),7306defined$file_name? ($file_name,"--full-history") : ());73077308my$ftype;7309if(!defined$file_hash&&defined$file_name) {7310# some commits could have deleted file in question,7311# and not have it in tree, but one of them has to have it7312for(my$i=0;$i<@commitlist;$i++) {7313$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);7314last ifdefined$file_hash;7315}7316}7317if(defined$file_hash) {7318$ftype= git_get_type($file_hash);7319}7320if(defined$file_name&& !defined$ftype) {7321 die_error(500,"Unknown type of object");7322}7323my%co;7324if(defined$file_name) {7325%co= parse_commit($base)7326or die_error(404,"Unknown commit object");7327}732873297330my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);7331my$next_link='';7332if($#commitlist>=100) {7333$next_link=7334$cgi->a({-href => href(-replay=>1, page=>$page+1),7335-accesskey =>"n", -title =>"Alt-n"},"next");7336}7337my$patch_max= gitweb_get_feature('patches');7338if($patch_max&& !defined$file_name) {7339if($patch_max<0||@commitlist<=$patch_max) {7340$paging_nav.=" ⋅ ".7341$cgi->a({-href => href(action=>"patches", -replay=>1)},7342"patches");7343}7344}73457346 git_header_html();7347 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);7348if(defined$file_name) {7349 git_print_header_div('commit', esc_html($co{'title'}),$base);7350}else{7351 git_print_header_div('summary',$project)7352}7353 git_print_page_path($file_name,$ftype,$hash_base)7354if(defined$file_name);73557356$body_subr->(\@commitlist,0,99,$refs,$next_link,7357$file_name,$file_hash,$ftype);73587359 git_footer_html();7360}73617362sub git_log {7363 git_log_generic('log', \&git_log_body,7364$hash,$hash_parent);7365}73667367sub git_commit {7368$hash||=$hash_base||"HEAD";7369my%co= parse_commit($hash)7370or die_error(404,"Unknown commit object");73717372my$parent=$co{'parent'};7373my$parents=$co{'parents'};# listref73747375# we need to prepare $formats_nav before any parameter munging7376my$formats_nav;7377if(!defined$parent) {7378# --root commitdiff7379$formats_nav.='(initial)';7380}elsif(@$parents==1) {7381# single parent commit7382$formats_nav.=7383'(parent: '.7384$cgi->a({-href => href(action=>"commit",7385 hash=>$parent)},7386 esc_html(substr($parent,0,7))) .7387')';7388}else{7389# merge commit7390$formats_nav.=7391'(merge: '.7392join(' ',map{7393$cgi->a({-href => href(action=>"commit",7394 hash=>$_)},7395 esc_html(substr($_,0,7)));7396}@$parents) .7397')';7398}7399if(gitweb_check_feature('patches') &&@$parents<=1) {7400$formats_nav.=" | ".7401$cgi->a({-href => href(action=>"patch", -replay=>1)},7402"patch");7403}74047405if(!defined$parent) {7406$parent="--root";7407}7408my@difftree;7409open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",7410@diff_opts,7411(@$parents<=1?$parent:'-c'),7412$hash,"--"7413or die_error(500,"Open git-diff-tree failed");7414@difftree=map{chomp;$_} <$fd>;7415close$fdor die_error(404,"Reading git-diff-tree failed");74167417# non-textual hash id's can be cached7418my$expires;7419if($hash=~m/^[0-9a-fA-F]{40}$/) {7420$expires="+1d";7421}7422my$refs= git_get_references();7423my$ref= format_ref_marker($refs,$co{'id'});74247425 git_header_html(undef,$expires);7426 git_print_page_nav('commit','',7427$hash,$co{'tree'},$hash,7428$formats_nav);74297430if(defined$co{'parent'}) {7431 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);7432}else{7433 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);7434}7435print"<div class=\"title_text\">\n".7436"<table class=\"object_header\">\n";7437 git_print_authorship_rows(\%co);7438print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";7439print"<tr>".7440"<td>tree</td>".7441"<td class=\"sha1\">".7442$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),7443class=>"list"},$co{'tree'}) .7444"</td>".7445"<td class=\"link\">".7446$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},7447"tree");7448my$snapshot_links= format_snapshot_links($hash);7449if(defined$snapshot_links) {7450print" | ".$snapshot_links;7451}7452print"</td>".7453"</tr>\n";74547455foreachmy$par(@$parents) {7456print"<tr>".7457"<td>parent</td>".7458"<td class=\"sha1\">".7459$cgi->a({-href => href(action=>"commit", hash=>$par),7460class=>"list"},$par) .7461"</td>".7462"<td class=\"link\">".7463$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .7464" | ".7465$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .7466"</td>".7467"</tr>\n";7468}7469print"</table>".7470"</div>\n";74717472print"<div class=\"page_body\">\n";7473 git_print_log($co{'comment'});7474print"</div>\n";74757476 git_difftree_body(\@difftree,$hash,@$parents);74777478 git_footer_html();7479}74807481sub git_object {7482# object is defined by:7483# - hash or hash_base alone7484# - hash_base and file_name7485my$type;74867487# - hash or hash_base alone7488if($hash|| ($hash_base&& !defined$file_name)) {7489my$object_id=$hash||$hash_base;74907491open my$fd,"-|", quote_command(7492 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'7493or die_error(404,"Object does not exist");7494$type= <$fd>;7495chomp$type;7496close$fd7497or die_error(404,"Object does not exist");74987499# - hash_base and file_name7500}elsif($hash_base&&defined$file_name) {7501$file_name=~ s,/+$,,;75027503system(git_cmd(),"cat-file",'-e',$hash_base) ==07504or die_error(404,"Base object does not exist");75057506# here errors should not happen7507open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name7508or die_error(500,"Open git-ls-tree failed");7509my$line= <$fd>;7510close$fd;75117512#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'7513unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {7514 die_error(404,"File or directory for given base does not exist");7515}7516$type=$2;7517$hash=$3;7518}else{7519 die_error(400,"Not enough information to find object");7520}75217522print$cgi->redirect(-uri => href(action=>$type, -full=>1,7523 hash=>$hash, hash_base=>$hash_base,7524 file_name=>$file_name),7525-status =>'302 Found');7526}75277528sub git_blobdiff {7529my$format=shift||'html';7530my$diff_style=$input_params{'diff_style'} ||'inline';75317532my$fd;7533my@difftree;7534my%diffinfo;7535my$expires;75367537# preparing $fd and %diffinfo for git_patchset_body7538# new style URI7539if(defined$hash_base&&defined$hash_parent_base) {7540if(defined$file_name) {7541# read raw output7542open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7543$hash_parent_base,$hash_base,7544"--", (defined$file_parent?$file_parent: ()),$file_name7545or die_error(500,"Open git-diff-tree failed");7546@difftree=map{chomp;$_} <$fd>;7547close$fd7548or die_error(404,"Reading git-diff-tree failed");7549@difftree7550or die_error(404,"Blob diff not found");75517552}elsif(defined$hash&&7553$hash=~/[0-9a-fA-F]{40}/) {7554# try to find filename from $hash75557556# read filtered raw output7557open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7558$hash_parent_base,$hash_base,"--"7559or die_error(500,"Open git-diff-tree failed");7560@difftree=7561# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'7562# $hash == to_id7563grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}7564map{chomp;$_} <$fd>;7565close$fd7566or die_error(404,"Reading git-diff-tree failed");7567@difftree7568or die_error(404,"Blob diff not found");75697570}else{7571 die_error(400,"Missing one of the blob diff parameters");7572}75737574if(@difftree>1) {7575 die_error(400,"Ambiguous blob diff specification");7576}75777578%diffinfo= parse_difftree_raw_line($difftree[0]);7579$file_parent||=$diffinfo{'from_file'} ||$file_name;7580$file_name||=$diffinfo{'to_file'};75817582$hash_parent||=$diffinfo{'from_id'};7583$hash||=$diffinfo{'to_id'};75847585# non-textual hash id's can be cached7586if($hash_base=~m/^[0-9a-fA-F]{40}$/&&7587$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {7588$expires='+1d';7589}75907591# open patch output7592open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7593'-p', ($formateq'html'?"--full-index": ()),7594$hash_parent_base,$hash_base,7595"--", (defined$file_parent?$file_parent: ()),$file_name7596or die_error(500,"Open git-diff-tree failed");7597}75987599# old/legacy style URI -- not generated anymore since 1.4.3.7600if(!%diffinfo) {7601 die_error('404 Not Found',"Missing one of the blob diff parameters")7602}76037604# header7605if($formateq'html') {7606my$formats_nav=7607$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},7608"raw");7609$formats_nav.= diff_style_nav($diff_style);7610 git_header_html(undef,$expires);7611if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7612 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7613 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7614}else{7615print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";7616print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";7617}7618if(defined$file_name) {7619 git_print_page_path($file_name,"blob",$hash_base);7620}else{7621print"<div class=\"page_path\"></div>\n";7622}76237624}elsif($formateq'plain') {7625print$cgi->header(7626-type =>'text/plain',7627-charset =>'utf-8',7628-expires =>$expires,7629-content_disposition =>'inline; filename="'."$file_name".'.patch"');76307631print"X-Git-Url: ".$cgi->self_url() ."\n\n";76327633}else{7634 die_error(400,"Unknown blobdiff format");7635}76367637# patch7638if($formateq'html') {7639print"<div class=\"page_body\">\n";76407641 git_patchset_body($fd,$diff_style,7642[ \%diffinfo],$hash_base,$hash_parent_base);7643close$fd;76447645print"</div>\n";# class="page_body"7646 git_footer_html();76477648}else{7649while(my$line= <$fd>) {7650$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;7651$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;76527653print$line;76547655last if$line=~m!^\+\+\+!;7656}7657local$/=undef;7658print<$fd>;7659close$fd;7660}7661}76627663sub git_blobdiff_plain {7664 git_blobdiff('plain');7665}76667667# assumes that it is added as later part of already existing navigation,7668# so it returns "| foo | bar" rather than just "foo | bar"7669sub diff_style_nav {7670my($diff_style,$is_combined) =@_;7671$diff_style||='inline';76727673return""if($is_combined);76747675my@styles= (inline =>'inline','sidebyside'=>'side by side');7676my%styles=@styles;7677@styles=7678@styles[map{$_*2}0..$#styles/2];76797680returnjoin'',7681map{" | ".$_}7682map{7683$_eq$diff_style?$styles{$_} :7684$cgi->a({-href => href(-replay=>1, diff_style =>$_)},$styles{$_})7685}@styles;7686}76877688sub git_commitdiff {7689my%params=@_;7690my$format=$params{-format} ||'html';7691my$diff_style=$input_params{'diff_style'} ||'inline';76927693my($patch_max) = gitweb_get_feature('patches');7694if($formateq'patch') {7695 die_error(403,"Patch view not allowed")unless$patch_max;7696}76977698$hash||=$hash_base||"HEAD";7699my%co= parse_commit($hash)7700or die_error(404,"Unknown commit object");77017702# choose format for commitdiff for merge7703if(!defined$hash_parent&& @{$co{'parents'}} >1) {7704$hash_parent='--cc';7705}7706# we need to prepare $formats_nav before almost any parameter munging7707my$formats_nav;7708if($formateq'html') {7709$formats_nav=7710$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},7711"raw");7712if($patch_max&& @{$co{'parents'}} <=1) {7713$formats_nav.=" | ".7714$cgi->a({-href => href(action=>"patch", -replay=>1)},7715"patch");7716}7717$formats_nav.= diff_style_nav($diff_style, @{$co{'parents'}} >1);77187719if(defined$hash_parent&&7720$hash_parentne'-c'&&$hash_parentne'--cc') {7721# commitdiff with two commits given7722my$hash_parent_short=$hash_parent;7723if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {7724$hash_parent_short=substr($hash_parent,0,7);7725}7726$formats_nav.=7727' (from';7728for(my$i=0;$i< @{$co{'parents'}};$i++) {7729if($co{'parents'}[$i]eq$hash_parent) {7730$formats_nav.=' parent '. ($i+1);7731last;7732}7733}7734$formats_nav.=': '.7735$cgi->a({-href => href(-replay=>1,7736 hash=>$hash_parent, hash_base=>undef)},7737 esc_html($hash_parent_short)) .7738')';7739}elsif(!$co{'parent'}) {7740# --root commitdiff7741$formats_nav.=' (initial)';7742}elsif(scalar@{$co{'parents'}} ==1) {7743# single parent commit7744$formats_nav.=7745' (parent: '.7746$cgi->a({-href => href(-replay=>1,7747 hash=>$co{'parent'}, hash_base=>undef)},7748 esc_html(substr($co{'parent'},0,7))) .7749')';7750}else{7751# merge commit7752if($hash_parenteq'--cc') {7753$formats_nav.=' | '.7754$cgi->a({-href => href(-replay=>1,7755 hash=>$hash, hash_parent=>'-c')},7756'combined');7757}else{# $hash_parent eq '-c'7758$formats_nav.=' | '.7759$cgi->a({-href => href(-replay=>1,7760 hash=>$hash, hash_parent=>'--cc')},7761'compact');7762}7763$formats_nav.=7764' (merge: '.7765join(' ',map{7766$cgi->a({-href => href(-replay=>1,7767 hash=>$_, hash_base=>undef)},7768 esc_html(substr($_,0,7)));7769} @{$co{'parents'}} ) .7770')';7771}7772}77737774my$hash_parent_param=$hash_parent;7775if(!defined$hash_parent_param) {7776# --cc for multiple parents, --root for parentless7777$hash_parent_param=7778@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';7779}77807781# read commitdiff7782my$fd;7783my@difftree;7784if($formateq'html') {7785open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7786"--no-commit-id","--patch-with-raw","--full-index",7787$hash_parent_param,$hash,"--"7788or die_error(500,"Open git-diff-tree failed");77897790while(my$line= <$fd>) {7791chomp$line;7792# empty line ends raw part of diff-tree output7793last unless$line;7794push@difftree,scalar parse_difftree_raw_line($line);7795}77967797}elsif($formateq'plain') {7798open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7799'-p',$hash_parent_param,$hash,"--"7800or die_error(500,"Open git-diff-tree failed");7801}elsif($formateq'patch') {7802# For commit ranges, we limit the output to the number of7803# patches specified in the 'patches' feature.7804# For single commits, we limit the output to a single patch,7805# diverging from the git-format-patch default.7806my@commit_spec= ();7807if($hash_parent) {7808if($patch_max>0) {7809push@commit_spec,"-$patch_max";7810}7811push@commit_spec,'-n',"$hash_parent..$hash";7812}else{7813if($params{-single}) {7814push@commit_spec,'-1';7815}else{7816if($patch_max>0) {7817push@commit_spec,"-$patch_max";7818}7819push@commit_spec,"-n";7820}7821push@commit_spec,'--root',$hash;7822}7823open$fd,"-|", git_cmd(),"format-patch",@diff_opts,7824'--encoding=utf8','--stdout',@commit_spec7825or die_error(500,"Open git-format-patch failed");7826}else{7827 die_error(400,"Unknown commitdiff format");7828}78297830# non-textual hash id's can be cached7831my$expires;7832if($hash=~m/^[0-9a-fA-F]{40}$/) {7833$expires="+1d";7834}78357836# write commit message7837if($formateq'html') {7838my$refs= git_get_references();7839my$ref= format_ref_marker($refs,$co{'id'});78407841 git_header_html(undef,$expires);7842 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);7843 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);7844print"<div class=\"title_text\">\n".7845"<table class=\"object_header\">\n";7846 git_print_authorship_rows(\%co);7847print"</table>".7848"</div>\n";7849print"<div class=\"page_body\">\n";7850if(@{$co{'comment'}} >1) {7851print"<div class=\"log\">\n";7852 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);7853print"</div>\n";# class="log"7854}78557856}elsif($formateq'plain') {7857my$refs= git_get_references("tags");7858my$tagname= git_get_rev_name_tags($hash);7859my$filename= basename($project) ."-$hash.patch";78607861print$cgi->header(7862-type =>'text/plain',7863-charset =>'utf-8',7864-expires =>$expires,7865-content_disposition =>'inline; filename="'."$filename".'"');7866my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});7867print"From: ". to_utf8($co{'author'}) ."\n";7868print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";7869print"Subject: ". to_utf8($co{'title'}) ."\n";78707871print"X-Git-Tag:$tagname\n"if$tagname;7872print"X-Git-Url: ".$cgi->self_url() ."\n\n";78737874foreachmy$line(@{$co{'comment'}}) {7875print to_utf8($line) ."\n";7876}7877print"---\n\n";7878}elsif($formateq'patch') {7879my$filename= basename($project) ."-$hash.patch";78807881print$cgi->header(7882-type =>'text/plain',7883-charset =>'utf-8',7884-expires =>$expires,7885-content_disposition =>'inline; filename="'."$filename".'"');7886}78877888# write patch7889if($formateq'html') {7890my$use_parents= !defined$hash_parent||7891$hash_parenteq'-c'||$hash_parenteq'--cc';7892 git_difftree_body(\@difftree,$hash,7893$use_parents? @{$co{'parents'}} :$hash_parent);7894print"<br/>\n";78957896 git_patchset_body($fd,$diff_style,7897 \@difftree,$hash,7898$use_parents? @{$co{'parents'}} :$hash_parent);7899close$fd;7900print"</div>\n";# class="page_body"7901 git_footer_html();79027903}elsif($formateq'plain') {7904local$/=undef;7905print<$fd>;7906close$fd7907or print"Reading git-diff-tree failed\n";7908}elsif($formateq'patch') {7909local$/=undef;7910print<$fd>;7911close$fd7912or print"Reading git-format-patch failed\n";7913}7914}79157916sub git_commitdiff_plain {7917 git_commitdiff(-format =>'plain');7918}79197920# format-patch-style patches7921sub git_patch {7922 git_commitdiff(-format =>'patch', -single =>1);7923}79247925sub git_patches {7926 git_commitdiff(-format =>'patch');7927}79287929sub git_history {7930 git_log_generic('history', \&git_history_body,7931$hash_base,$hash_parent_base,7932$file_name,$hash);7933}79347935sub git_search {7936$searchtype||='commit';79377938# check if appropriate features are enabled7939 gitweb_check_feature('search')7940or die_error(403,"Search is disabled");7941if($searchtypeeq'pickaxe') {7942# pickaxe may take all resources of your box and run for several minutes7943# with every query - so decide by yourself how public you make this feature7944 gitweb_check_feature('pickaxe')7945or die_error(403,"Pickaxe search is disabled");7946}7947if($searchtypeeq'grep') {7948# grep search might be potentially CPU-intensive, too7949 gitweb_check_feature('grep')7950or die_error(403,"Grep search is disabled");7951}79527953if(!defined$searchtext) {7954 die_error(400,"Text field is empty");7955}7956if(!defined$hash) {7957$hash= git_get_head_hash($project);7958}7959my%co= parse_commit($hash);7960if(!%co) {7961 die_error(404,"Unknown commit object");7962}7963if(!defined$page) {7964$page=0;7965}79667967if($searchtypeeq'commit'||7968$searchtypeeq'author'||7969$searchtypeeq'committer') {7970 git_search_message(%co);7971}elsif($searchtypeeq'pickaxe') {7972 git_search_changes(%co);7973}elsif($searchtypeeq'grep') {7974 git_search_files(%co);7975}else{7976 die_error(400,"Unknown search type");7977}7978}79797980sub git_search_help {7981 git_header_html();7982 git_print_page_nav('','',$hash,$hash,$hash);7983print<<EOT;7984<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without7985regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,7986the pattern entered is recognized as the POSIX extended7987<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case7988insensitive).</p>7989<dl>7990<dt><b>commit</b></dt>7991<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>7992EOT7993my$have_grep= gitweb_check_feature('grep');7994if($have_grep) {7995print<<EOT;7996<dt><b>grep</b></dt>7997<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing7998 a different one) are searched for the given pattern. On large trees, this search can take7999a while and put some strain on the server, so please use it with some consideration. Note that8000due to git-grep peculiarity, currently if regexp mode is turned off, the matches are8001case-sensitive.</dd>8002EOT8003}8004print<<EOT;8005<dt><b>author</b></dt>8006<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>8007<dt><b>committer</b></dt>8008<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>8009EOT8010my$have_pickaxe= gitweb_check_feature('pickaxe');8011if($have_pickaxe) {8012print<<EOT;8013<dt><b>pickaxe</b></dt>8014<dd>All commits that caused the string to appear or disappear from any file (changes that8015added, removed or "modified" the string) will be listed. This search can take a while and8016takes a lot of strain on the server, so please use it wisely. Note that since you may be8017interested even in changes just changing the case as well, this search is case sensitive.</dd>8018EOT8019}8020print"</dl>\n";8021 git_footer_html();8022}80238024sub git_shortlog {8025 git_log_generic('shortlog', \&git_shortlog_body,8026$hash,$hash_parent);8027}80288029## ......................................................................8030## feeds (RSS, Atom; OPML)80318032sub git_feed {8033my$format=shift||'atom';8034my$have_blame= gitweb_check_feature('blame');80358036# Atom: http://www.atomenabled.org/developers/syndication/8037# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ8038if($formatne'rss'&&$formatne'atom') {8039 die_error(400,"Unknown web feed format");8040}80418042# log/feed of current (HEAD) branch, log of given branch, history of file/directory8043my$head=$hash||'HEAD';8044my@commitlist= parse_commits($head,150,0,$file_name);80458046my%latest_commit;8047my%latest_date;8048my$content_type="application/$format+xml";8049if(defined$cgi->http('HTTP_ACCEPT') &&8050$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {8051# browser (feed reader) prefers text/xml8052$content_type='text/xml';8053}8054if(defined($commitlist[0])) {8055%latest_commit= %{$commitlist[0]};8056my$latest_epoch=$latest_commit{'committer_epoch'};8057 exit_if_unmodified_since($latest_epoch);8058%latest_date= parse_date($latest_epoch,$latest_commit{'committer_tz'});8059}8060print$cgi->header(8061-type =>$content_type,8062-charset =>'utf-8',8063%latest_date? (-last_modified =>$latest_date{'rfc2822'}) : (),8064-status =>'200 OK');80658066# Optimization: skip generating the body if client asks only8067# for Last-Modified date.8068return if($cgi->request_method()eq'HEAD');80698070# header variables8071my$title="$site_name-$project/$action";8072my$feed_type='log';8073if(defined$hash) {8074$title.=" - '$hash'";8075$feed_type='branch log';8076if(defined$file_name) {8077$title.=" ::$file_name";8078$feed_type='history';8079}8080}elsif(defined$file_name) {8081$title.=" -$file_name";8082$feed_type='history';8083}8084$title.="$feed_type";8085$title= esc_html($title);8086my$descr= git_get_project_description($project);8087if(defined$descr) {8088$descr= esc_html($descr);8089}else{8090$descr="$project".8091($formateq'rss'?'RSS':'Atom') .8092" feed";8093}8094my$owner= git_get_project_owner($project);8095$owner= esc_html($owner);80968097#header8098my$alt_url;8099if(defined$file_name) {8100$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);8101}elsif(defined$hash) {8102$alt_url= href(-full=>1, action=>"log", hash=>$hash);8103}else{8104$alt_url= href(-full=>1, action=>"summary");8105}8106print qq!<?xml version="1.0" encoding="utf-8"?>\n!;8107if($formateq'rss') {8108print<<XML;8109<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">8110<channel>8111XML8112print"<title>$title</title>\n".8113"<link>$alt_url</link>\n".8114"<description>$descr</description>\n".8115"<language>en</language>\n".8116# project owner is responsible for 'editorial' content8117"<managingEditor>$owner</managingEditor>\n";8118if(defined$logo||defined$favicon) {8119# prefer the logo to the favicon, since RSS8120# doesn't allow both8121my$img= esc_url($logo||$favicon);8122print"<image>\n".8123"<url>$img</url>\n".8124"<title>$title</title>\n".8125"<link>$alt_url</link>\n".8126"</image>\n";8127}8128if(%latest_date) {8129print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";8130print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";8131}8132print"<generator>gitweb v.$version/$git_version</generator>\n";8133}elsif($formateq'atom') {8134print<<XML;8135<feed xmlns="http://www.w3.org/2005/Atom">8136XML8137print"<title>$title</title>\n".8138"<subtitle>$descr</subtitle>\n".8139'<link rel="alternate" type="text/html" href="'.8140$alt_url.'" />'."\n".8141'<link rel="self" type="'.$content_type.'" href="'.8142$cgi->self_url() .'" />'."\n".8143"<id>". href(-full=>1) ."</id>\n".8144# use project owner for feed author8145"<author><name>$owner</name></author>\n";8146if(defined$favicon) {8147print"<icon>". esc_url($favicon) ."</icon>\n";8148}8149if(defined$logo) {8150# not twice as wide as tall: 72 x 27 pixels8151print"<logo>". esc_url($logo) ."</logo>\n";8152}8153if(!%latest_date) {8154# dummy date to keep the feed valid until commits trickle in:8155print"<updated>1970-01-01T00:00:00Z</updated>\n";8156}else{8157print"<updated>$latest_date{'iso-8601'}</updated>\n";8158}8159print"<generator version='$version/$git_version'>gitweb</generator>\n";8160}81618162# contents8163for(my$i=0;$i<=$#commitlist;$i++) {8164my%co= %{$commitlist[$i]};8165my$commit=$co{'id'};8166# we read 150, we always show 30 and the ones more recent than 48 hours8167if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {8168last;8169}8170my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});81718172# get list of changed files8173open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,8174$co{'parent'} ||"--root",8175$co{'id'},"--", (defined$file_name?$file_name: ())8176ornext;8177my@difftree=map{chomp;$_} <$fd>;8178close$fd8179ornext;81808181# print element (entry, item)8182my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);8183if($formateq'rss') {8184print"<item>\n".8185"<title>". esc_html($co{'title'}) ."</title>\n".8186"<author>". esc_html($co{'author'}) ."</author>\n".8187"<pubDate>$cd{'rfc2822'}</pubDate>\n".8188"<guid isPermaLink=\"true\">$co_url</guid>\n".8189"<link>$co_url</link>\n".8190"<description>". esc_html($co{'title'}) ."</description>\n".8191"<content:encoded>".8192"<![CDATA[\n";8193}elsif($formateq'atom') {8194print"<entry>\n".8195"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".8196"<updated>$cd{'iso-8601'}</updated>\n".8197"<author>\n".8198" <name>". esc_html($co{'author_name'}) ."</name>\n";8199if($co{'author_email'}) {8200print" <email>". esc_html($co{'author_email'}) ."</email>\n";8201}8202print"</author>\n".8203# use committer for contributor8204"<contributor>\n".8205" <name>". esc_html($co{'committer_name'}) ."</name>\n";8206if($co{'committer_email'}) {8207print" <email>". esc_html($co{'committer_email'}) ."</email>\n";8208}8209print"</contributor>\n".8210"<published>$cd{'iso-8601'}</published>\n".8211"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".8212"<id>$co_url</id>\n".8213"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".8214"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";8215}8216my$comment=$co{'comment'};8217print"<pre>\n";8218foreachmy$line(@$comment) {8219$line= esc_html($line);8220print"$line\n";8221}8222print"</pre><ul>\n";8223foreachmy$difftree_line(@difftree) {8224my%difftree= parse_difftree_raw_line($difftree_line);8225next if!$difftree{'from_id'};82268227my$file=$difftree{'file'} ||$difftree{'to_file'};82288229print"<li>".8230"[".8231$cgi->a({-href => href(-full=>1, action=>"blobdiff",8232 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},8233 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},8234 file_name=>$file, file_parent=>$difftree{'from_file'}),8235-title =>"diff"},'D');8236if($have_blame) {8237print$cgi->a({-href => href(-full=>1, action=>"blame",8238 file_name=>$file, hash_base=>$commit),8239-title =>"blame"},'B');8240}8241# if this is not a feed of a file history8242if(!defined$file_name||$file_namene$file) {8243print$cgi->a({-href => href(-full=>1, action=>"history",8244 file_name=>$file, hash=>$commit),8245-title =>"history"},'H');8246}8247$file= esc_path($file);8248print"] ".8249"$file</li>\n";8250}8251if($formateq'rss') {8252print"</ul>]]>\n".8253"</content:encoded>\n".8254"</item>\n";8255}elsif($formateq'atom') {8256print"</ul>\n</div>\n".8257"</content>\n".8258"</entry>\n";8259}8260}82618262# end of feed8263if($formateq'rss') {8264print"</channel>\n</rss>\n";8265}elsif($formateq'atom') {8266print"</feed>\n";8267}8268}82698270sub git_rss {8271 git_feed('rss');8272}82738274sub git_atom {8275 git_feed('atom');8276}82778278sub git_opml {8279my@list= git_get_projects_list($project_filter,$strict_export);8280if(!@list) {8281 die_error(404,"No projects found");8282}82838284print$cgi->header(8285-type =>'text/xml',8286-charset =>'utf-8',8287-content_disposition =>'inline; filename="opml.xml"');82888289my$title= esc_html($site_name);8290my$filter=" within subdirectory ";8291if(defined$project_filter) {8292$filter.= esc_html($project_filter);8293}else{8294$filter="";8295}8296print<<XML;8297<?xml version="1.0" encoding="utf-8"?>8298<opml version="1.0">8299<head>8300 <title>$titleOPML Export$filter</title>8301</head>8302<body>8303<outline text="git RSS feeds">8304XML83058306foreachmy$pr(@list) {8307my%proj=%$pr;8308my$head= git_get_head_hash($proj{'path'});8309if(!defined$head) {8310next;8311}8312$git_dir="$projectroot/$proj{'path'}";8313my%co= parse_commit($head);8314if(!%co) {8315next;8316}83178318my$path= esc_html(chop_str($proj{'path'},25,5));8319my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);8320my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);8321print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";8322}8323print<<XML;8324</outline>8325</body>8326</opml>8327XML8328}