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) { 57if($my_url=~ s,\Q$path_info\E$,, && 58$my_uri=~ s,\Q$path_info\E$,, && 59defined$ENV{'SCRIPT_NAME'}) { 60$base_url=$cgi->url(-base =>1) .$ENV{'SCRIPT_NAME'}; 61} 62} 63 64# target of the home link on top of all pages 65our$home_link=$my_uri||"/"; 66} 67 68# core git executable to use 69# this can just be "git" if your webserver has a sensible PATH 70our$GIT="++GIT_BINDIR++/git"; 71 72# absolute fs-path which will be prepended to the project path 73#our $projectroot = "/pub/scm"; 74our$projectroot="++GITWEB_PROJECTROOT++"; 75 76# fs traversing limit for getting project list 77# the number is relative to the projectroot 78our$project_maxdepth="++GITWEB_PROJECT_MAXDEPTH++"; 79 80# string of the home link on top of all pages 81our$home_link_str="++GITWEB_HOME_LINK_STR++"; 82 83# name of your site or organization to appear in page titles 84# replace this with something more descriptive for clearer bookmarks 85our$site_name="++GITWEB_SITENAME++" 86|| ($ENV{'SERVER_NAME'} ||"Untitled") ." Git"; 87 88# html snippet to include in the <head> section of each page 89our$site_html_head_string="++GITWEB_SITE_HTML_HEAD_STRING++"; 90# filename of html text to include at top of each page 91our$site_header="++GITWEB_SITE_HEADER++"; 92# html text to include at home page 93our$home_text="++GITWEB_HOMETEXT++"; 94# filename of html text to include at bottom of each page 95our$site_footer="++GITWEB_SITE_FOOTER++"; 96 97# URI of stylesheets 98our@stylesheets= ("++GITWEB_CSS++"); 99# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG. 100our$stylesheet=undef; 101# URI of GIT logo (72x27 size) 102our$logo="++GITWEB_LOGO++"; 103# URI of GIT favicon, assumed to be image/png type 104our$favicon="++GITWEB_FAVICON++"; 105# URI of gitweb.js (JavaScript code for gitweb) 106our$javascript="++GITWEB_JS++"; 107 108# URI and label (title) of GIT logo link 109#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/"; 110#our $logo_label = "git documentation"; 111our$logo_url="http://git-scm.com/"; 112our$logo_label="git homepage"; 113 114# source of projects list 115our$projects_list="++GITWEB_LIST++"; 116 117# the width (in characters) of the projects list "Description" column 118our$projects_list_description_width=25; 119 120# group projects by category on the projects list 121# (enabled if this variable evaluates to true) 122our$projects_list_group_categories=0; 123 124# default category if none specified 125# (leave the empty string for no category) 126our$project_list_default_category=""; 127 128# default order of projects list 129# valid values are none, project, descr, owner, and age 130our$default_projects_order="project"; 131 132# show repository only if this file exists 133# (only effective if this variable evaluates to true) 134our$export_ok="++GITWEB_EXPORT_OK++"; 135 136# show repository only if this subroutine returns true 137# when given the path to the project, for example: 138# sub { return -e "$_[0]/git-daemon-export-ok"; } 139our$export_auth_hook=undef; 140 141# only allow viewing of repositories also shown on the overview page 142our$strict_export="++GITWEB_STRICT_EXPORT++"; 143 144# list of git base URLs used for URL to where fetch project from, 145# i.e. full URL is "$git_base_url/$project" 146our@git_base_url_list=grep{$_ne''} ("++GITWEB_BASE_URL++"); 147 148# default blob_plain mimetype and default charset for text/plain blob 149our$default_blob_plain_mimetype='text/plain'; 150our$default_text_plain_charset=undef; 151 152# file to use for guessing MIME types before trying /etc/mime.types 153# (relative to the current git repository) 154our$mimetypes_file=undef; 155 156# assume this charset if line contains non-UTF-8 characters; 157# it should be valid encoding (see Encoding::Supported(3pm) for list), 158# for which encoding all byte sequences are valid, for example 159# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it 160# could be even 'utf-8' for the old behavior) 161our$fallback_encoding='latin1'; 162 163# rename detection options for git-diff and git-diff-tree 164# - default is '-M', with the cost proportional to 165# (number of removed files) * (number of new files). 166# - more costly is '-C' (which implies '-M'), with the cost proportional to 167# (number of changed files + number of removed files) * (number of new files) 168# - even more costly is '-C', '--find-copies-harder' with cost 169# (number of files in the original tree) * (number of new files) 170# - one might want to include '-B' option, e.g. '-B', '-M' 171our@diff_opts= ('-M');# taken from git_commit 172 173# Disables features that would allow repository owners to inject script into 174# the gitweb domain. 175our$prevent_xss=0; 176 177# Path to the highlight executable to use (must be the one from 178# http://www.andre-simon.de due to assumptions about parameters and output). 179# Useful if highlight is not installed on your webserver's PATH. 180# [Default: highlight] 181our$highlight_bin="++HIGHLIGHT_BIN++"; 182 183# information about snapshot formats that gitweb is capable of serving 184our%known_snapshot_formats= ( 185# name => { 186# 'display' => display name, 187# 'type' => mime type, 188# 'suffix' => filename suffix, 189# 'format' => --format for git-archive, 190# 'compressor' => [compressor command and arguments] 191# (array reference, optional) 192# 'disabled' => boolean (optional)} 193# 194'tgz'=> { 195'display'=>'tar.gz', 196'type'=>'application/x-gzip', 197'suffix'=>'.tar.gz', 198'format'=>'tar', 199'compressor'=> ['gzip','-n']}, 200 201'tbz2'=> { 202'display'=>'tar.bz2', 203'type'=>'application/x-bzip2', 204'suffix'=>'.tar.bz2', 205'format'=>'tar', 206'compressor'=> ['bzip2']}, 207 208'txz'=> { 209'display'=>'tar.xz', 210'type'=>'application/x-xz', 211'suffix'=>'.tar.xz', 212'format'=>'tar', 213'compressor'=> ['xz'], 214'disabled'=>1}, 215 216'zip'=> { 217'display'=>'zip', 218'type'=>'application/x-zip', 219'suffix'=>'.zip', 220'format'=>'zip'}, 221); 222 223# Aliases so we understand old gitweb.snapshot values in repository 224# configuration. 225our%known_snapshot_format_aliases= ( 226'gzip'=>'tgz', 227'bzip2'=>'tbz2', 228'xz'=>'txz', 229 230# backward compatibility: legacy gitweb config support 231'x-gzip'=>undef,'gz'=>undef, 232'x-bzip2'=>undef,'bz2'=>undef, 233'x-zip'=>undef,''=>undef, 234); 235 236# Pixel sizes for icons and avatars. If the default font sizes or lineheights 237# are changed, it may be appropriate to change these values too via 238# $GITWEB_CONFIG. 239our%avatar_size= ( 240'default'=>16, 241'double'=>32 242); 243 244# Used to set the maximum load that we will still respond to gitweb queries. 245# If server load exceed this value then return "503 server busy" error. 246# If gitweb cannot determined server load, it is taken to be 0. 247# Leave it undefined (or set to 'undef') to turn off load checking. 248our$maxload=300; 249 250# configuration for 'highlight' (http://www.andre-simon.de/) 251# match by basename 252our%highlight_basename= ( 253#'Program' => 'py', 254#'Library' => 'py', 255'SConstruct'=>'py',# SCons equivalent of Makefile 256'Makefile'=>'make', 257); 258# match by extension 259our%highlight_ext= ( 260# main extensions, defining name of syntax; 261# see files in /usr/share/highlight/langDefs/ directory 262map{$_=>$_} 263qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl sql make), 264# alternate extensions, see /etc/highlight/filetypes.conf 265'h'=>'c', 266map{$_=>'sh'}qw(bash zsh ksh), 267map{$_=>'cpp'}qw(cxx c++ cc), 268map{$_=>'php'}qw(php3 php4 php5 phps), 269map{$_=>'pl'}qw(perl pm),# perhaps also 'cgi' 270map{$_=>'make'}qw(mak mk), 271map{$_=>'xml'}qw(xhtml html htm), 272); 273 274# You define site-wide feature defaults here; override them with 275# $GITWEB_CONFIG as necessary. 276our%feature= ( 277# feature => { 278# 'sub' => feature-sub (subroutine), 279# 'override' => allow-override (boolean), 280# 'default' => [ default options...] (array reference)} 281# 282# if feature is overridable (it means that allow-override has true value), 283# then feature-sub will be called with default options as parameters; 284# return value of feature-sub indicates if to enable specified feature 285# 286# if there is no 'sub' key (no feature-sub), then feature cannot be 287# overridden 288# 289# use gitweb_get_feature(<feature>) to retrieve the <feature> value 290# (an array) or gitweb_check_feature(<feature>) to check if <feature> 291# is enabled 292 293# Enable the 'blame' blob view, showing the last commit that modified 294# each line in the file. This can be very CPU-intensive. 295 296# To enable system wide have in $GITWEB_CONFIG 297# $feature{'blame'}{'default'} = [1]; 298# To have project specific config enable override in $GITWEB_CONFIG 299# $feature{'blame'}{'override'} = 1; 300# and in project config gitweb.blame = 0|1; 301'blame'=> { 302'sub'=>sub{ feature_bool('blame',@_) }, 303'override'=>0, 304'default'=> [0]}, 305 306# Enable the 'snapshot' link, providing a compressed archive of any 307# tree. This can potentially generate high traffic if you have large 308# project. 309 310# Value is a list of formats defined in %known_snapshot_formats that 311# you wish to offer. 312# To disable system wide have in $GITWEB_CONFIG 313# $feature{'snapshot'}{'default'} = []; 314# To have project specific config enable override in $GITWEB_CONFIG 315# $feature{'snapshot'}{'override'} = 1; 316# and in project config, a comma-separated list of formats or "none" 317# to disable. Example: gitweb.snapshot = tbz2,zip; 318'snapshot'=> { 319'sub'=> \&feature_snapshot, 320'override'=>0, 321'default'=> ['tgz']}, 322 323# Enable text search, which will list the commits which match author, 324# committer or commit text to a given string. Enabled by default. 325# Project specific override is not supported. 326# 327# Note that this controls all search features, which means that if 328# it is disabled, then 'grep' and 'pickaxe' search would also be 329# disabled. 330'search'=> { 331'override'=>0, 332'default'=> [1]}, 333 334# Enable grep search, which will list the files in currently selected 335# tree containing the given string. Enabled by default. This can be 336# potentially CPU-intensive, of course. 337# Note that you need to have 'search' feature enabled too. 338 339# To enable system wide have in $GITWEB_CONFIG 340# $feature{'grep'}{'default'} = [1]; 341# To have project specific config enable override in $GITWEB_CONFIG 342# $feature{'grep'}{'override'} = 1; 343# and in project config gitweb.grep = 0|1; 344'grep'=> { 345'sub'=>sub{ feature_bool('grep',@_) }, 346'override'=>0, 347'default'=> [1]}, 348 349# Enable the pickaxe search, which will list the commits that modified 350# a given string in a file. This can be practical and quite faster 351# alternative to 'blame', but still potentially CPU-intensive. 352# Note that you need to have 'search' feature enabled too. 353 354# To enable system wide have in $GITWEB_CONFIG 355# $feature{'pickaxe'}{'default'} = [1]; 356# To have project specific config enable override in $GITWEB_CONFIG 357# $feature{'pickaxe'}{'override'} = 1; 358# and in project config gitweb.pickaxe = 0|1; 359'pickaxe'=> { 360'sub'=>sub{ feature_bool('pickaxe',@_) }, 361'override'=>0, 362'default'=> [1]}, 363 364# Enable showing size of blobs in a 'tree' view, in a separate 365# column, similar to what 'ls -l' does. This cost a bit of IO. 366 367# To disable system wide have in $GITWEB_CONFIG 368# $feature{'show-sizes'}{'default'} = [0]; 369# To have project specific config enable override in $GITWEB_CONFIG 370# $feature{'show-sizes'}{'override'} = 1; 371# and in project config gitweb.showsizes = 0|1; 372'show-sizes'=> { 373'sub'=>sub{ feature_bool('showsizes',@_) }, 374'override'=>0, 375'default'=> [1]}, 376 377# Make gitweb use an alternative format of the URLs which can be 378# more readable and natural-looking: project name is embedded 379# directly in the path and the query string contains other 380# auxiliary information. All gitweb installations recognize 381# URL in either format; this configures in which formats gitweb 382# generates links. 383 384# To enable system wide have in $GITWEB_CONFIG 385# $feature{'pathinfo'}{'default'} = [1]; 386# Project specific override is not supported. 387 388# Note that you will need to change the default location of CSS, 389# favicon, logo and possibly other files to an absolute URL. Also, 390# if gitweb.cgi serves as your indexfile, you will need to force 391# $my_uri to contain the script name in your $GITWEB_CONFIG. 392'pathinfo'=> { 393'override'=>0, 394'default'=> [0]}, 395 396# Make gitweb consider projects in project root subdirectories 397# to be forks of existing projects. Given project $projname.git, 398# projects matching $projname/*.git will not be shown in the main 399# projects list, instead a '+' mark will be added to $projname 400# there and a 'forks' view will be enabled for the project, listing 401# all the forks. If project list is taken from a file, forks have 402# to be listed after the main project. 403 404# To enable system wide have in $GITWEB_CONFIG 405# $feature{'forks'}{'default'} = [1]; 406# Project specific override is not supported. 407'forks'=> { 408'override'=>0, 409'default'=> [0]}, 410 411# Insert custom links to the action bar of all project pages. 412# This enables you mainly to link to third-party scripts integrating 413# into gitweb; e.g. git-browser for graphical history representation 414# or custom web-based repository administration interface. 415 416# The 'default' value consists of a list of triplets in the form 417# (label, link, position) where position is the label after which 418# to insert the link and link is a format string where %n expands 419# to the project name, %f to the project path within the filesystem, 420# %h to the current hash (h gitweb parameter) and %b to the current 421# hash base (hb gitweb parameter); %% expands to %. 422 423# To enable system wide have in $GITWEB_CONFIG e.g. 424# $feature{'actions'}{'default'} = [('graphiclog', 425# '/git-browser/by-commit.html?r=%n', 'summary')]; 426# Project specific override is not supported. 427'actions'=> { 428'override'=>0, 429'default'=> []}, 430 431# Allow gitweb scan project content tags of project repository, 432# and display the popular Web 2.0-ish "tag cloud" near the projects 433# list. Note that this is something COMPLETELY different from the 434# normal Git tags. 435 436# gitweb by itself can show existing tags, but it does not handle 437# tagging itself; you need to do it externally, outside gitweb. 438# The format is described in git_get_project_ctags() subroutine. 439# You may want to install the HTML::TagCloud Perl module to get 440# a pretty tag cloud instead of just a list of tags. 441 442# To enable system wide have in $GITWEB_CONFIG 443# $feature{'ctags'}{'default'} = [1]; 444# Project specific override is not supported. 445 446# In the future whether ctags editing is enabled might depend 447# on the value, but using 1 should always mean no editing of ctags. 448'ctags'=> { 449'override'=>0, 450'default'=> [0]}, 451 452# The maximum number of patches in a patchset generated in patch 453# view. Set this to 0 or undef to disable patch view, or to a 454# negative number to remove any limit. 455 456# To disable system wide have in $GITWEB_CONFIG 457# $feature{'patches'}{'default'} = [0]; 458# To have project specific config enable override in $GITWEB_CONFIG 459# $feature{'patches'}{'override'} = 1; 460# and in project config gitweb.patches = 0|n; 461# where n is the maximum number of patches allowed in a patchset. 462'patches'=> { 463'sub'=> \&feature_patches, 464'override'=>0, 465'default'=> [16]}, 466 467# Avatar support. When this feature is enabled, views such as 468# shortlog or commit will display an avatar associated with 469# the email of the committer(s) and/or author(s). 470 471# Currently available providers are gravatar and picon. 472# If an unknown provider is specified, the feature is disabled. 473 474# Gravatar depends on Digest::MD5. 475# Picon currently relies on the indiana.edu database. 476 477# To enable system wide have in $GITWEB_CONFIG 478# $feature{'avatar'}{'default'} = ['<provider>']; 479# where <provider> is either gravatar or picon. 480# To have project specific config enable override in $GITWEB_CONFIG 481# $feature{'avatar'}{'override'} = 1; 482# and in project config gitweb.avatar = <provider>; 483'avatar'=> { 484'sub'=> \&feature_avatar, 485'override'=>0, 486'default'=> ['']}, 487 488# Enable displaying how much time and how many git commands 489# it took to generate and display page. Disabled by default. 490# Project specific override is not supported. 491'timed'=> { 492'override'=>0, 493'default'=> [0]}, 494 495# Enable turning some links into links to actions which require 496# JavaScript to run (like 'blame_incremental'). Not enabled by 497# default. Project specific override is currently not supported. 498'javascript-actions'=> { 499'override'=>0, 500'default'=> [0]}, 501 502# Enable and configure ability to change common timezone for dates 503# in gitweb output via JavaScript. Enabled by default. 504# Project specific override is not supported. 505'javascript-timezone'=> { 506'override'=>0, 507'default'=> [ 508'local',# default timezone: 'utc', 'local', or '(-|+)HHMM' format, 509# or undef to turn off this feature 510'gitweb_tz',# name of cookie where to store selected timezone 511'datetime',# CSS class used to mark up dates for manipulation 512]}, 513 514# Syntax highlighting support. This is based on Daniel Svensson's 515# and Sham Chukoury's work in gitweb-xmms2.git. 516# It requires the 'highlight' program present in $PATH, 517# and therefore is disabled by default. 518 519# To enable system wide have in $GITWEB_CONFIG 520# $feature{'highlight'}{'default'} = [1]; 521 522'highlight'=> { 523'sub'=>sub{ feature_bool('highlight',@_) }, 524'override'=>0, 525'default'=> [0]}, 526 527# Enable displaying of remote heads in the heads list 528 529# To enable system wide have in $GITWEB_CONFIG 530# $feature{'remote_heads'}{'default'} = [1]; 531# To have project specific config enable override in $GITWEB_CONFIG 532# $feature{'remote_heads'}{'override'} = 1; 533# and in project config gitweb.remote_heads = 0|1; 534'remote_heads'=> { 535'sub'=>sub{ feature_bool('remote_heads',@_) }, 536'override'=>0, 537'default'=> [0]}, 538); 539 540sub gitweb_get_feature { 541my($name) =@_; 542return unlessexists$feature{$name}; 543my($sub,$override,@defaults) = ( 544$feature{$name}{'sub'}, 545$feature{$name}{'override'}, 546@{$feature{$name}{'default'}}); 547# project specific override is possible only if we have project 548our$git_dir;# global variable, declared later 549if(!$override|| !defined$git_dir) { 550return@defaults; 551} 552if(!defined$sub) { 553warn"feature$nameis not overridable"; 554return@defaults; 555} 556return$sub->(@defaults); 557} 558 559# A wrapper to check if a given feature is enabled. 560# With this, you can say 561# 562# my $bool_feat = gitweb_check_feature('bool_feat'); 563# gitweb_check_feature('bool_feat') or somecode; 564# 565# instead of 566# 567# my ($bool_feat) = gitweb_get_feature('bool_feat'); 568# (gitweb_get_feature('bool_feat'))[0] or somecode; 569# 570sub gitweb_check_feature { 571return(gitweb_get_feature(@_))[0]; 572} 573 574 575sub feature_bool { 576my$key=shift; 577my($val) = git_get_project_config($key,'--bool'); 578 579if(!defined$val) { 580return($_[0]); 581}elsif($valeq'true') { 582return(1); 583}elsif($valeq'false') { 584return(0); 585} 586} 587 588sub feature_snapshot { 589my(@fmts) =@_; 590 591my($val) = git_get_project_config('snapshot'); 592 593if($val) { 594@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 595} 596 597return@fmts; 598} 599 600sub feature_patches { 601my@val= (git_get_project_config('patches','--int')); 602 603if(@val) { 604return@val; 605} 606 607return($_[0]); 608} 609 610sub feature_avatar { 611my@val= (git_get_project_config('avatar')); 612 613return@val?@val:@_; 614} 615 616# checking HEAD file with -e is fragile if the repository was 617# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 618# and then pruned. 619sub check_head_link { 620my($dir) =@_; 621my$headfile="$dir/HEAD"; 622return((-e $headfile) || 623(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 624} 625 626sub check_export_ok { 627my($dir) =@_; 628return(check_head_link($dir) && 629(!$export_ok|| -e "$dir/$export_ok") && 630(!$export_auth_hook||$export_auth_hook->($dir))); 631} 632 633# process alternate names for backward compatibility 634# filter out unsupported (unknown) snapshot formats 635sub filter_snapshot_fmts { 636my@fmts=@_; 637 638@fmts=map{ 639exists$known_snapshot_format_aliases{$_} ? 640$known_snapshot_format_aliases{$_} :$_}@fmts; 641@fmts=grep{ 642exists$known_snapshot_formats{$_} && 643!$known_snapshot_formats{$_}{'disabled'}}@fmts; 644} 645 646# If it is set to code reference, it is code that it is to be run once per 647# request, allowing updating configurations that change with each request, 648# while running other code in config file only once. 649# 650# Otherwise, if it is false then gitweb would process config file only once; 651# if it is true then gitweb config would be run for each request. 652our$per_request_config=1; 653 654# read and parse gitweb config file given by its parameter. 655# returns true on success, false on recoverable error, allowing 656# to chain this subroutine, using first file that exists. 657# dies on errors during parsing config file, as it is unrecoverable. 658sub read_config_file { 659my$filename=shift; 660return unlessdefined$filename; 661# die if there are errors parsing config file 662if(-e $filename) { 663do$filename; 664die$@if$@; 665return1; 666} 667return; 668} 669 670our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM,$GITWEB_CONFIG_COMMON); 671sub evaluate_gitweb_config { 672our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 673our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 674our$GITWEB_CONFIG_COMMON=$ENV{'GITWEB_CONFIG_COMMON'} ||"++GITWEB_CONFIG_COMMON++"; 675 676# Protect agains duplications of file names, to not read config twice. 677# Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so 678# there possibility of duplication of filename there doesn't matter. 679$GITWEB_CONFIG=""if($GITWEB_CONFIGeq$GITWEB_CONFIG_COMMON); 680$GITWEB_CONFIG_SYSTEM=""if($GITWEB_CONFIG_SYSTEMeq$GITWEB_CONFIG_COMMON); 681 682# Common system-wide settings for convenience. 683# Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM. 684 read_config_file($GITWEB_CONFIG_COMMON); 685 686# Use first config file that exists. This means use the per-instance 687# GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG. 688 read_config_file($GITWEB_CONFIG)andreturn; 689 read_config_file($GITWEB_CONFIG_SYSTEM); 690} 691 692# Get loadavg of system, to compare against $maxload. 693# Currently it requires '/proc/loadavg' present to get loadavg; 694# if it is not present it returns 0, which means no load checking. 695sub get_loadavg { 696if( -e '/proc/loadavg'){ 697open my$fd,'<','/proc/loadavg' 698orreturn0; 699my@load=split(/\s+/,scalar<$fd>); 700close$fd; 701 702# The first three columns measure CPU and IO utilization of the last one, 703# five, and 10 minute periods. The fourth column shows the number of 704# currently running processes and the total number of processes in the m/n 705# format. The last column displays the last process ID used. 706return$load[0] ||0; 707} 708# additional checks for load average should go here for things that don't export 709# /proc/loadavg 710 711return0; 712} 713 714# version of the core git binary 715our$git_version; 716sub evaluate_git_version { 717our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 718$number_of_git_cmds++; 719} 720 721sub check_loadavg { 722if(defined$maxload&& get_loadavg() >$maxload) { 723 die_error(503,"The load average on the server is too high"); 724} 725} 726 727# ====================================================================== 728# input validation and dispatch 729 730# input parameters can be collected from a variety of sources (presently, CGI 731# and PATH_INFO), so we define an %input_params hash that collects them all 732# together during validation: this allows subsequent uses (e.g. href()) to be 733# agnostic of the parameter origin 734 735our%input_params= (); 736 737# input parameters are stored with the long parameter name as key. This will 738# also be used in the href subroutine to convert parameters to their CGI 739# equivalent, and since the href() usage is the most frequent one, we store 740# the name -> CGI key mapping here, instead of the reverse. 741# 742# XXX: Warning: If you touch this, check the search form for updating, 743# too. 744 745our@cgi_param_mapping= ( 746 project =>"p", 747 action =>"a", 748 file_name =>"f", 749 file_parent =>"fp", 750 hash =>"h", 751 hash_parent =>"hp", 752 hash_base =>"hb", 753 hash_parent_base =>"hpb", 754 page =>"pg", 755 order =>"o", 756 searchtext =>"s", 757 searchtype =>"st", 758 snapshot_format =>"sf", 759 extra_options =>"opt", 760 search_use_regexp =>"sr", 761 ctag =>"by_tag", 762 diff_style =>"ds", 763# this must be last entry (for manipulation from JavaScript) 764 javascript =>"js" 765); 766our%cgi_param_mapping=@cgi_param_mapping; 767 768# we will also need to know the possible actions, for validation 769our%actions= ( 770"blame"=> \&git_blame, 771"blame_incremental"=> \&git_blame_incremental, 772"blame_data"=> \&git_blame_data, 773"blobdiff"=> \&git_blobdiff, 774"blobdiff_plain"=> \&git_blobdiff_plain, 775"blob"=> \&git_blob, 776"blob_plain"=> \&git_blob_plain, 777"commitdiff"=> \&git_commitdiff, 778"commitdiff_plain"=> \&git_commitdiff_plain, 779"commit"=> \&git_commit, 780"forks"=> \&git_forks, 781"heads"=> \&git_heads, 782"history"=> \&git_history, 783"log"=> \&git_log, 784"patch"=> \&git_patch, 785"patches"=> \&git_patches, 786"remotes"=> \&git_remotes, 787"rss"=> \&git_rss, 788"atom"=> \&git_atom, 789"search"=> \&git_search, 790"search_help"=> \&git_search_help, 791"shortlog"=> \&git_shortlog, 792"summary"=> \&git_summary, 793"tag"=> \&git_tag, 794"tags"=> \&git_tags, 795"tree"=> \&git_tree, 796"snapshot"=> \&git_snapshot, 797"object"=> \&git_object, 798# those below don't need $project 799"opml"=> \&git_opml, 800"project_list"=> \&git_project_list, 801"project_index"=> \&git_project_index, 802); 803 804# finally, we have the hash of allowed extra_options for the commands that 805# allow them 806our%allowed_options= ( 807"--no-merges"=> [qw(rss atom log shortlog history)], 808); 809 810# fill %input_params with the CGI parameters. All values except for 'opt' 811# should be single values, but opt can be an array. We should probably 812# build an array of parameters that can be multi-valued, but since for the time 813# being it's only this one, we just single it out 814sub evaluate_query_params { 815our$cgi; 816 817while(my($name,$symbol) =each%cgi_param_mapping) { 818if($symboleq'opt') { 819$input_params{$name} = [map{ decode_utf8($_) }$cgi->param($symbol) ]; 820}else{ 821$input_params{$name} = decode_utf8($cgi->param($symbol)); 822} 823} 824} 825 826# now read PATH_INFO and update the parameter list for missing parameters 827sub evaluate_path_info { 828return ifdefined$input_params{'project'}; 829return if!$path_info; 830$path_info=~ s,^/+,,; 831return if!$path_info; 832 833# find which part of PATH_INFO is project 834my$project=$path_info; 835$project=~ s,/+$,,; 836while($project&& !check_head_link("$projectroot/$project")) { 837$project=~ s,/*[^/]*$,,; 838} 839return unless$project; 840$input_params{'project'} =$project; 841 842# do not change any parameters if an action is given using the query string 843return if$input_params{'action'}; 844$path_info=~ s,^\Q$project\E/*,,; 845 846# next, check if we have an action 847my$action=$path_info; 848$action=~ s,/.*$,,; 849if(exists$actions{$action}) { 850$path_info=~ s,^$action/*,,; 851$input_params{'action'} =$action; 852} 853 854# list of actions that want hash_base instead of hash, but can have no 855# pathname (f) parameter 856my@wants_base= ( 857'tree', 858'history', 859); 860 861# we want to catch, among others 862# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 863my($parentrefname,$parentpathname,$refname,$pathname) = 864($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/); 865 866# first, analyze the 'current' part 867if(defined$pathname) { 868# we got "branch:filename" or "branch:dir/" 869# we could use git_get_type(branch:pathname), but: 870# - it needs $git_dir 871# - it does a git() call 872# - the convention of terminating directories with a slash 873# makes it superfluous 874# - embedding the action in the PATH_INFO would make it even 875# more superfluous 876$pathname=~ s,^/+,,; 877if(!$pathname||substr($pathname, -1)eq"/") { 878$input_params{'action'} ||="tree"; 879$pathname=~ s,/$,,; 880}else{ 881# the default action depends on whether we had parent info 882# or not 883if($parentrefname) { 884$input_params{'action'} ||="blobdiff_plain"; 885}else{ 886$input_params{'action'} ||="blob_plain"; 887} 888} 889$input_params{'hash_base'} ||=$refname; 890$input_params{'file_name'} ||=$pathname; 891}elsif(defined$refname) { 892# we got "branch". In this case we have to choose if we have to 893# set hash or hash_base. 894# 895# Most of the actions without a pathname only want hash to be 896# set, except for the ones specified in @wants_base that want 897# hash_base instead. It should also be noted that hand-crafted 898# links having 'history' as an action and no pathname or hash 899# set will fail, but that happens regardless of PATH_INFO. 900if(defined$parentrefname) { 901# if there is parent let the default be 'shortlog' action 902# (for http://git.example.com/repo.git/A..B links); if there 903# is no parent, dispatch will detect type of object and set 904# action appropriately if required (if action is not set) 905$input_params{'action'} ||="shortlog"; 906} 907if($input_params{'action'} && 908grep{$_eq$input_params{'action'} }@wants_base) { 909$input_params{'hash_base'} ||=$refname; 910}else{ 911$input_params{'hash'} ||=$refname; 912} 913} 914 915# next, handle the 'parent' part, if present 916if(defined$parentrefname) { 917# a missing pathspec defaults to the 'current' filename, allowing e.g. 918# someproject/blobdiff/oldrev..newrev:/filename 919if($parentpathname) { 920$parentpathname=~ s,^/+,,; 921$parentpathname=~ s,/$,,; 922$input_params{'file_parent'} ||=$parentpathname; 923}else{ 924$input_params{'file_parent'} ||=$input_params{'file_name'}; 925} 926# we assume that hash_parent_base is wanted if a path was specified, 927# or if the action wants hash_base instead of hash 928if(defined$input_params{'file_parent'} || 929grep{$_eq$input_params{'action'} }@wants_base) { 930$input_params{'hash_parent_base'} ||=$parentrefname; 931}else{ 932$input_params{'hash_parent'} ||=$parentrefname; 933} 934} 935 936# for the snapshot action, we allow URLs in the form 937# $project/snapshot/$hash.ext 938# where .ext determines the snapshot and gets removed from the 939# passed $refname to provide the $hash. 940# 941# To be able to tell that $refname includes the format extension, we 942# require the following two conditions to be satisfied: 943# - the hash input parameter MUST have been set from the $refname part 944# of the URL (i.e. they must be equal) 945# - the snapshot format MUST NOT have been defined already (e.g. from 946# CGI parameter sf) 947# It's also useless to try any matching unless $refname has a dot, 948# so we check for that too 949if(defined$input_params{'action'} && 950$input_params{'action'}eq'snapshot'&& 951defined$refname&&index($refname,'.') != -1&& 952$refnameeq$input_params{'hash'} && 953!defined$input_params{'snapshot_format'}) { 954# We loop over the known snapshot formats, checking for 955# extensions. Allowed extensions are both the defined suffix 956# (which includes the initial dot already) and the snapshot 957# format key itself, with a prepended dot 958while(my($fmt,$opt) =each%known_snapshot_formats) { 959my$hash=$refname; 960unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 961next; 962} 963my$sfx=$1; 964# a valid suffix was found, so set the snapshot format 965# and reset the hash parameter 966$input_params{'snapshot_format'} =$fmt; 967$input_params{'hash'} =$hash; 968# we also set the format suffix to the one requested 969# in the URL: this way a request for e.g. .tgz returns 970# a .tgz instead of a .tar.gz 971$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 972last; 973} 974} 975} 976 977our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 978$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 979$searchtext,$search_regexp); 980sub evaluate_and_validate_params { 981our$action=$input_params{'action'}; 982if(defined$action) { 983if(!validate_action($action)) { 984 die_error(400,"Invalid action parameter"); 985} 986} 987 988# parameters which are pathnames 989our$project=$input_params{'project'}; 990if(defined$project) { 991if(!validate_project($project)) { 992undef$project; 993 die_error(404,"No such project"); 994} 995} 996 997our$file_name=$input_params{'file_name'}; 998if(defined$file_name) { 999if(!validate_pathname($file_name)) {1000 die_error(400,"Invalid file parameter");1001}1002}10031004our$file_parent=$input_params{'file_parent'};1005if(defined$file_parent) {1006if(!validate_pathname($file_parent)) {1007 die_error(400,"Invalid file parent parameter");1008}1009}10101011# parameters which are refnames1012our$hash=$input_params{'hash'};1013if(defined$hash) {1014if(!validate_refname($hash)) {1015 die_error(400,"Invalid hash parameter");1016}1017}10181019our$hash_parent=$input_params{'hash_parent'};1020if(defined$hash_parent) {1021if(!validate_refname($hash_parent)) {1022 die_error(400,"Invalid hash parent parameter");1023}1024}10251026our$hash_base=$input_params{'hash_base'};1027if(defined$hash_base) {1028if(!validate_refname($hash_base)) {1029 die_error(400,"Invalid hash base parameter");1030}1031}10321033our@extra_options= @{$input_params{'extra_options'}};1034# @extra_options is always defined, since it can only be (currently) set from1035# CGI, and $cgi->param() returns the empty array in array context if the param1036# is not set1037foreachmy$opt(@extra_options) {1038if(not exists$allowed_options{$opt}) {1039 die_error(400,"Invalid option parameter");1040}1041if(not grep(/^$action$/, @{$allowed_options{$opt}})) {1042 die_error(400,"Invalid option parameter for this action");1043}1044}10451046our$hash_parent_base=$input_params{'hash_parent_base'};1047if(defined$hash_parent_base) {1048if(!validate_refname($hash_parent_base)) {1049 die_error(400,"Invalid hash parent base parameter");1050}1051}10521053# other parameters1054our$page=$input_params{'page'};1055if(defined$page) {1056if($page=~m/[^0-9]/) {1057 die_error(400,"Invalid page parameter");1058}1059}10601061our$searchtype=$input_params{'searchtype'};1062if(defined$searchtype) {1063if($searchtype=~m/[^a-z]/) {1064 die_error(400,"Invalid searchtype parameter");1065}1066}10671068our$search_use_regexp=$input_params{'search_use_regexp'};10691070our$searchtext=$input_params{'searchtext'};1071our$search_regexp;1072if(defined$searchtext) {1073if(length($searchtext) <2) {1074 die_error(403,"At least two characters are required for search parameter");1075}1076if($search_use_regexp) {1077$search_regexp=$searchtext;1078if(!eval{qr/$search_regexp/;1; }) {1079(my$error=$@) =~s/ at \S+ line \d+.*\n?//;1080 die_error(400,"Invalid search regexp '$search_regexp'",1081 esc_html($error));1082}1083}else{1084$search_regexp=quotemeta$searchtext;1085}1086}1087}10881089# path to the current git repository1090our$git_dir;1091sub evaluate_git_dir {1092our$git_dir="$projectroot/$project"if$project;1093}10941095our(@snapshot_fmts,$git_avatar);1096sub configure_gitweb_features {1097# list of supported snapshot formats1098our@snapshot_fmts= gitweb_get_feature('snapshot');1099@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);11001101# check that the avatar feature is set to a known provider name,1102# and for each provider check if the dependencies are satisfied.1103# if the provider name is invalid or the dependencies are not met,1104# reset $git_avatar to the empty string.1105our($git_avatar) = gitweb_get_feature('avatar');1106if($git_avatareq'gravatar') {1107$git_avatar=''unless(eval{require Digest::MD5;1; });1108}elsif($git_avatareq'picon') {1109# no dependencies1110}else{1111$git_avatar='';1112}1113}11141115# custom error handler: 'die <message>' is Internal Server Error1116sub handle_errors_html {1117my$msg=shift;# it is already HTML escaped11181119# to avoid infinite loop where error occurs in die_error,1120# change handler to default handler, disabling handle_errors_html1121 set_message("Error occured when inside die_error:\n$msg");11221123# you cannot jump out of die_error when called as error handler;1124# the subroutine set via CGI::Carp::set_message is called _after_1125# HTTP headers are already written, so it cannot write them itself1126 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1127}1128set_message(\&handle_errors_html);11291130# dispatch1131sub dispatch {1132if(!defined$action) {1133if(defined$hash) {1134$action= git_get_type($hash);1135$actionor die_error(404,"Object does not exist");1136}elsif(defined$hash_base&&defined$file_name) {1137$action= git_get_type("$hash_base:$file_name");1138$actionor die_error(404,"File or directory does not exist");1139}elsif(defined$project) {1140$action='summary';1141}else{1142$action='project_list';1143}1144}1145if(!defined($actions{$action})) {1146 die_error(400,"Unknown action");1147}1148if($action!~m/^(?:opml|project_list|project_index)$/&&1149!$project) {1150 die_error(400,"Project needed");1151}1152$actions{$action}->();1153}11541155sub reset_timer {1156our$t0= [ gettimeofday() ]1157ifdefined$t0;1158our$number_of_git_cmds=0;1159}11601161our$first_request=1;1162sub run_request {1163 reset_timer();11641165 evaluate_uri();1166if($first_request) {1167 evaluate_gitweb_config();1168 evaluate_git_version();1169}1170if($per_request_config) {1171if(ref($per_request_config)eq'CODE') {1172$per_request_config->();1173}elsif(!$first_request) {1174 evaluate_gitweb_config();1175}1176}1177 check_loadavg();11781179# $projectroot and $projects_list might be set in gitweb config file1180$projects_list||=$projectroot;11811182 evaluate_query_params();1183 evaluate_path_info();1184 evaluate_and_validate_params();1185 evaluate_git_dir();11861187 configure_gitweb_features();11881189 dispatch();1190}11911192our$is_last_request=sub{1};1193our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1194our$CGI='CGI';1195our$cgi;1196sub configure_as_fcgi {1197require CGI::Fast;1198our$CGI='CGI::Fast';11991200my$request_number=0;1201# let each child service 100 requests1202our$is_last_request=sub{ ++$request_number>100};1203}1204sub evaluate_argv {1205my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1206 configure_as_fcgi()1207if$script_name=~/\.fcgi$/;12081209return unless(@ARGV);12101211require Getopt::Long;1212 Getopt::Long::GetOptions(1213'fastcgi|fcgi|f'=> \&configure_as_fcgi,1214'nproc|n=i'=>sub{1215my($arg,$val) =@_;1216return unlesseval{require FCGI::ProcManager;1; };1217my$proc_manager= FCGI::ProcManager->new({1218 n_processes =>$val,1219});1220our$pre_listen_hook=sub{$proc_manager->pm_manage() };1221our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1222our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1223},1224);1225}12261227sub run {1228 evaluate_argv();12291230$first_request=1;1231$pre_listen_hook->()1232if$pre_listen_hook;12331234 REQUEST:1235while($cgi=$CGI->new()) {1236$pre_dispatch_hook->()1237if$pre_dispatch_hook;12381239 run_request();12401241$post_dispatch_hook->()1242if$post_dispatch_hook;1243$first_request=0;12441245last REQUEST if($is_last_request->());1246}12471248 DONE_GITWEB:12491;1250}12511252run();12531254if(defined caller) {1255# wrapped in a subroutine processing requests,1256# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1257return;1258}else{1259# pure CGI script, serving single request1260exit;1261}12621263## ======================================================================1264## action links12651266# possible values of extra options1267# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1268# -replay => 1 - start from a current view (replay with modifications)1269# -path_info => 0|1 - don't use/use path_info URL (if possible)1270# -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone1271sub href {1272my%params=@_;1273# default is to use -absolute url() i.e. $my_uri1274my$href=$params{-full} ?$my_url:$my_uri;12751276# implicit -replay, must be first of implicit params1277$params{-replay} =1if(keys%params==1&&$params{-anchor});12781279$params{'project'} =$projectunlessexists$params{'project'};12801281if($params{-replay}) {1282while(my($name,$symbol) =each%cgi_param_mapping) {1283if(!exists$params{$name}) {1284$params{$name} =$input_params{$name};1285}1286}1287}12881289my$use_pathinfo= gitweb_check_feature('pathinfo');1290if(defined$params{'project'} &&1291(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1292# try to put as many parameters as possible in PATH_INFO:1293# - project name1294# - action1295# - hash_parent or hash_parent_base:/file_parent1296# - hash or hash_base:/filename1297# - the snapshot_format as an appropriate suffix12981299# When the script is the root DirectoryIndex for the domain,1300# $href here would be something like http://gitweb.example.com/1301# Thus, we strip any trailing / from $href, to spare us double1302# slashes in the final URL1303$href=~ s,/$,,;13041305# Then add the project name, if present1306$href.="/".esc_path_info($params{'project'});1307delete$params{'project'};13081309# since we destructively absorb parameters, we keep this1310# boolean that remembers if we're handling a snapshot1311my$is_snapshot=$params{'action'}eq'snapshot';13121313# Summary just uses the project path URL, any other action is1314# added to the URL1315if(defined$params{'action'}) {1316$href.="/".esc_path_info($params{'action'})1317unless$params{'action'}eq'summary';1318delete$params{'action'};1319}13201321# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1322# stripping nonexistent or useless pieces1323$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1324||$params{'hash_parent'} ||$params{'hash'});1325if(defined$params{'hash_base'}) {1326if(defined$params{'hash_parent_base'}) {1327$href.= esc_path_info($params{'hash_parent_base'});1328# skip the file_parent if it's the same as the file_name1329if(defined$params{'file_parent'}) {1330if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1331delete$params{'file_parent'};1332}elsif($params{'file_parent'} !~/\.\./) {1333$href.=":/".esc_path_info($params{'file_parent'});1334delete$params{'file_parent'};1335}1336}1337$href.="..";1338delete$params{'hash_parent'};1339delete$params{'hash_parent_base'};1340}elsif(defined$params{'hash_parent'}) {1341$href.= esc_path_info($params{'hash_parent'})."..";1342delete$params{'hash_parent'};1343}13441345$href.= esc_path_info($params{'hash_base'});1346if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1347$href.=":/".esc_path_info($params{'file_name'});1348delete$params{'file_name'};1349}1350delete$params{'hash'};1351delete$params{'hash_base'};1352}elsif(defined$params{'hash'}) {1353$href.= esc_path_info($params{'hash'});1354delete$params{'hash'};1355}13561357# If the action was a snapshot, we can absorb the1358# snapshot_format parameter too1359if($is_snapshot) {1360my$fmt=$params{'snapshot_format'};1361# snapshot_format should always be defined when href()1362# is called, but just in case some code forgets, we1363# fall back to the default1364$fmt||=$snapshot_fmts[0];1365$href.=$known_snapshot_formats{$fmt}{'suffix'};1366delete$params{'snapshot_format'};1367}1368}13691370# now encode the parameters explicitly1371my@result= ();1372for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1373my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1374if(defined$params{$name}) {1375if(ref($params{$name})eq"ARRAY") {1376foreachmy$par(@{$params{$name}}) {1377push@result,$symbol."=". esc_param($par);1378}1379}else{1380push@result,$symbol."=". esc_param($params{$name});1381}1382}1383}1384$href.="?".join(';',@result)ifscalar@result;13851386# final transformation: trailing spaces must be escaped (URI-encoded)1387$href=~s/(\s+)$/CGI::escape($1)/e;13881389if($params{-anchor}) {1390$href.="#".esc_param($params{-anchor});1391}13921393return$href;1394}139513961397## ======================================================================1398## validation, quoting/unquoting and escaping13991400sub validate_action {1401my$input=shift||returnundef;1402returnundefunlessexists$actions{$input};1403return$input;1404}14051406sub validate_project {1407my$input=shift||returnundef;1408if(!validate_pathname($input) ||1409!(-d "$projectroot/$input") ||1410!check_export_ok("$projectroot/$input") ||1411($strict_export&& !project_in_list($input))) {1412returnundef;1413}else{1414return$input;1415}1416}14171418sub validate_pathname {1419my$input=shift||returnundef;14201421# no '.' or '..' as elements of path, i.e. no '.' nor '..'1422# at the beginning, at the end, and between slashes.1423# also this catches doubled slashes1424if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1425returnundef;1426}1427# no null characters1428if($input=~m!\0!) {1429returnundef;1430}1431return$input;1432}14331434sub validate_refname {1435my$input=shift||returnundef;14361437# textual hashes are O.K.1438if($input=~m/^[0-9a-fA-F]{40}$/) {1439return$input;1440}1441# it must be correct pathname1442$input= validate_pathname($input)1443orreturnundef;1444# restrictions on ref name according to git-check-ref-format1445if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1446returnundef;1447}1448return$input;1449}14501451# decode sequences of octets in utf8 into Perl's internal form,1452# which is utf-8 with utf8 flag set if needed. gitweb writes out1453# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1454sub to_utf8 {1455my$str=shift;1456returnundefunlessdefined$str;14571458if(utf8::is_utf8($str) || utf8::decode($str)) {1459return$str;1460}else{1461return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1462}1463}14641465# quote unsafe chars, but keep the slash, even when it's not1466# correct, but quoted slashes look too horrible in bookmarks1467sub esc_param {1468my$str=shift;1469returnundefunlessdefined$str;1470$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1471$str=~s/ /\+/g;1472return$str;1473}14741475# the quoting rules for path_info fragment are slightly different1476sub esc_path_info {1477my$str=shift;1478returnundefunlessdefined$str;14791480# path_info doesn't treat '+' as space (specially), but '?' must be escaped1481$str=~s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;14821483return$str;1484}14851486# quote unsafe chars in whole URL, so some characters cannot be quoted1487sub esc_url {1488my$str=shift;1489returnundefunlessdefined$str;1490$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1491$str=~s/ /\+/g;1492return$str;1493}14941495# quote unsafe characters in HTML attributes1496sub esc_attr {14971498# for XHTML conformance escaping '"' to '"' is not enough1499return esc_html(@_);1500}15011502# replace invalid utf8 character with SUBSTITUTION sequence1503sub esc_html {1504my$str=shift;1505my%opts=@_;15061507returnundefunlessdefined$str;15081509$str= to_utf8($str);1510$str=$cgi->escapeHTML($str);1511if($opts{'-nbsp'}) {1512$str=~s/ / /g;1513}1514$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1515return$str;1516}15171518# quote control characters and escape filename to HTML1519sub esc_path {1520my$str=shift;1521my%opts=@_;15221523returnundefunlessdefined$str;15241525$str= to_utf8($str);1526$str=$cgi->escapeHTML($str);1527if($opts{'-nbsp'}) {1528$str=~s/ / /g;1529}1530$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1531return$str;1532}15331534# Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)1535sub sanitize {1536my$str=shift;15371538returnundefunlessdefined$str;15391540$str= to_utf8($str);1541$str=~ s|([[:cntrl:]])|($1=~/[\t\n\r]/?$1: quot_cec($1))|eg;1542return$str;1543}15441545# Make control characters "printable", using character escape codes (CEC)1546sub quot_cec {1547my$cntrl=shift;1548my%opts=@_;1549my%es= (# character escape codes, aka escape sequences1550"\t"=>'\t',# tab (HT)1551"\n"=>'\n',# line feed (LF)1552"\r"=>'\r',# carrige return (CR)1553"\f"=>'\f',# form feed (FF)1554"\b"=>'\b',# backspace (BS)1555"\a"=>'\a',# alarm (bell) (BEL)1556"\e"=>'\e',# escape (ESC)1557"\013"=>'\v',# vertical tab (VT)1558"\000"=>'\0',# nul character (NUL)1559);1560my$chr= ( (exists$es{$cntrl})1561?$es{$cntrl}1562:sprintf('\%2x',ord($cntrl)) );1563if($opts{-nohtml}) {1564return$chr;1565}else{1566return"<span class=\"cntrl\">$chr</span>";1567}1568}15691570# Alternatively use unicode control pictures codepoints,1571# Unicode "printable representation" (PR)1572sub quot_upr {1573my$cntrl=shift;1574my%opts=@_;15751576my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1577if($opts{-nohtml}) {1578return$chr;1579}else{1580return"<span class=\"cntrl\">$chr</span>";1581}1582}15831584# git may return quoted and escaped filenames1585sub unquote {1586my$str=shift;15871588sub unq {1589my$seq=shift;1590my%es= (# character escape codes, aka escape sequences1591't'=>"\t",# tab (HT, TAB)1592'n'=>"\n",# newline (NL)1593'r'=>"\r",# return (CR)1594'f'=>"\f",# form feed (FF)1595'b'=>"\b",# backspace (BS)1596'a'=>"\a",# alarm (bell) (BEL)1597'e'=>"\e",# escape (ESC)1598'v'=>"\013",# vertical tab (VT)1599);16001601if($seq=~m/^[0-7]{1,3}$/) {1602# octal char sequence1603returnchr(oct($seq));1604}elsif(exists$es{$seq}) {1605# C escape sequence, aka character escape code1606return$es{$seq};1607}1608# quoted ordinary character1609return$seq;1610}16111612if($str=~m/^"(.*)"$/) {1613# needs unquoting1614$str=$1;1615$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1616}1617return$str;1618}16191620# escape tabs (convert tabs to spaces)1621sub untabify {1622my$line=shift;16231624while((my$pos=index($line,"\t")) != -1) {1625if(my$count= (8- ($pos%8))) {1626my$spaces=' ' x $count;1627$line=~s/\t/$spaces/;1628}1629}16301631return$line;1632}16331634sub project_in_list {1635my$project=shift;1636my@list= git_get_projects_list();1637return@list&&scalar(grep{$_->{'path'}eq$project}@list);1638}16391640## ----------------------------------------------------------------------1641## HTML aware string manipulation16421643# Try to chop given string on a word boundary between position1644# $len and $len+$add_len. If there is no word boundary there,1645# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1646# (marking chopped part) would be longer than given string.1647sub chop_str {1648my$str=shift;1649my$len=shift;1650my$add_len=shift||10;1651my$where=shift||'right';# 'left' | 'center' | 'right'16521653# Make sure perl knows it is utf8 encoded so we don't1654# cut in the middle of a utf8 multibyte char.1655$str= to_utf8($str);16561657# allow only $len chars, but don't cut a word if it would fit in $add_len1658# if it doesn't fit, cut it if it's still longer than the dots we would add1659# remove chopped character entities entirely16601661# when chopping in the middle, distribute $len into left and right part1662# return early if chopping wouldn't make string shorter1663if($whereeq'center') {1664return$strif($len+5>=length($str));# filler is length 51665$len=int($len/2);1666}else{1667return$strif($len+4>=length($str));# filler is length 41668}16691670# regexps: ending and beginning with word part up to $add_len1671my$endre=qr/.{$len}\w{0,$add_len}/;1672my$begre=qr/\w{0,$add_len}.{$len}/;16731674if($whereeq'left') {1675$str=~m/^(.*?)($begre)$/;1676my($lead,$body) = ($1,$2);1677if(length($lead) >4) {1678$lead=" ...";1679}1680return"$lead$body";16811682}elsif($whereeq'center') {1683$str=~m/^($endre)(.*)$/;1684my($left,$str) = ($1,$2);1685$str=~m/^(.*?)($begre)$/;1686my($mid,$right) = ($1,$2);1687if(length($mid) >5) {1688$mid=" ... ";1689}1690return"$left$mid$right";16911692}else{1693$str=~m/^($endre)(.*)$/;1694my$body=$1;1695my$tail=$2;1696if(length($tail) >4) {1697$tail="... ";1698}1699return"$body$tail";1700}1701}17021703# takes the same arguments as chop_str, but also wraps a <span> around the1704# result with a title attribute if it does get chopped. Additionally, the1705# string is HTML-escaped.1706sub chop_and_escape_str {1707my($str) =@_;17081709my$chopped= chop_str(@_);1710$str= to_utf8($str);1711if($choppedeq$str) {1712return esc_html($chopped);1713}else{1714$str=~s/[[:cntrl:]]/?/g;1715return$cgi->span({-title=>$str}, esc_html($chopped));1716}1717}17181719## ----------------------------------------------------------------------1720## functions returning short strings17211722# CSS class for given age value (in seconds)1723sub age_class {1724my$age=shift;17251726if(!defined$age) {1727return"noage";1728}elsif($age<60*60*2) {1729return"age0";1730}elsif($age<60*60*24*2) {1731return"age1";1732}else{1733return"age2";1734}1735}17361737# convert age in seconds to "nn units ago" string1738sub age_string {1739my$age=shift;1740my$age_str;17411742if($age>60*60*24*365*2) {1743$age_str= (int$age/60/60/24/365);1744$age_str.=" years ago";1745}elsif($age>60*60*24*(365/12)*2) {1746$age_str=int$age/60/60/24/(365/12);1747$age_str.=" months ago";1748}elsif($age>60*60*24*7*2) {1749$age_str=int$age/60/60/24/7;1750$age_str.=" weeks ago";1751}elsif($age>60*60*24*2) {1752$age_str=int$age/60/60/24;1753$age_str.=" days ago";1754}elsif($age>60*60*2) {1755$age_str=int$age/60/60;1756$age_str.=" hours ago";1757}elsif($age>60*2) {1758$age_str=int$age/60;1759$age_str.=" min ago";1760}elsif($age>2) {1761$age_str=int$age;1762$age_str.=" sec ago";1763}else{1764$age_str.=" right now";1765}1766return$age_str;1767}17681769useconstant{1770 S_IFINVALID =>0030000,1771 S_IFGITLINK =>0160000,1772};17731774# submodule/subproject, a commit object reference1775sub S_ISGITLINK {1776my$mode=shift;17771778return(($mode& S_IFMT) == S_IFGITLINK)1779}17801781# convert file mode in octal to symbolic file mode string1782sub mode_str {1783my$mode=oct shift;17841785if(S_ISGITLINK($mode)) {1786return'm---------';1787}elsif(S_ISDIR($mode& S_IFMT)) {1788return'drwxr-xr-x';1789}elsif(S_ISLNK($mode)) {1790return'lrwxrwxrwx';1791}elsif(S_ISREG($mode)) {1792# git cares only about the executable bit1793if($mode& S_IXUSR) {1794return'-rwxr-xr-x';1795}else{1796return'-rw-r--r--';1797};1798}else{1799return'----------';1800}1801}18021803# convert file mode in octal to file type string1804sub file_type {1805my$mode=shift;18061807if($mode!~m/^[0-7]+$/) {1808return$mode;1809}else{1810$mode=oct$mode;1811}18121813if(S_ISGITLINK($mode)) {1814return"submodule";1815}elsif(S_ISDIR($mode& S_IFMT)) {1816return"directory";1817}elsif(S_ISLNK($mode)) {1818return"symlink";1819}elsif(S_ISREG($mode)) {1820return"file";1821}else{1822return"unknown";1823}1824}18251826# convert file mode in octal to file type description string1827sub file_type_long {1828my$mode=shift;18291830if($mode!~m/^[0-7]+$/) {1831return$mode;1832}else{1833$mode=oct$mode;1834}18351836if(S_ISGITLINK($mode)) {1837return"submodule";1838}elsif(S_ISDIR($mode& S_IFMT)) {1839return"directory";1840}elsif(S_ISLNK($mode)) {1841return"symlink";1842}elsif(S_ISREG($mode)) {1843if($mode& S_IXUSR) {1844return"executable";1845}else{1846return"file";1847};1848}else{1849return"unknown";1850}1851}185218531854## ----------------------------------------------------------------------1855## functions returning short HTML fragments, or transforming HTML fragments1856## which don't belong to other sections18571858# format line of commit message.1859sub format_log_line_html {1860my$line=shift;18611862$line= esc_html($line, -nbsp=>1);1863$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1864$cgi->a({-href => href(action=>"object", hash=>$1),1865-class=>"text"},$1);1866}eg;18671868return$line;1869}18701871# format marker of refs pointing to given object18721873# the destination action is chosen based on object type and current context:1874# - for annotated tags, we choose the tag view unless it's the current view1875# already, in which case we go to shortlog view1876# - for other refs, we keep the current view if we're in history, shortlog or1877# log view, and select shortlog otherwise1878sub format_ref_marker {1879my($refs,$id) =@_;1880my$markers='';18811882if(defined$refs->{$id}) {1883foreachmy$ref(@{$refs->{$id}}) {1884# this code exploits the fact that non-lightweight tags are the1885# only indirect objects, and that they are the only objects for which1886# we want to use tag instead of shortlog as action1887my($type,$name) =qw();1888my$indirect= ($ref=~s/\^\{\}$//);1889# e.g. tags/v2.6.11 or heads/next1890if($ref=~m!^(.*?)s?/(.*)$!) {1891$type=$1;1892$name=$2;1893}else{1894$type="ref";1895$name=$ref;1896}18971898my$class=$type;1899$class.=" indirect"if$indirect;19001901my$dest_action="shortlog";19021903if($indirect) {1904$dest_action="tag"unless$actioneq"tag";1905}elsif($action=~/^(history|(short)?log)$/) {1906$dest_action=$action;1907}19081909my$dest="";1910$dest.="refs/"unless$ref=~ m!^refs/!;1911$dest.=$ref;19121913my$link=$cgi->a({1914-href => href(1915 action=>$dest_action,1916 hash=>$dest1917)},$name);19181919$markers.=" <span class=\"".esc_attr($class)."\"title=\"".esc_attr($ref)."\">".1920$link."</span>";1921}1922}19231924if($markers) {1925return' <span class="refs">'.$markers.'</span>';1926}else{1927return"";1928}1929}19301931# format, perhaps shortened and with markers, title line1932sub format_subject_html {1933my($long,$short,$href,$extra) =@_;1934$extra=''unlessdefined($extra);19351936if(length($short) <length($long)) {1937$long=~s/[[:cntrl:]]/?/g;1938return$cgi->a({-href =>$href, -class=>"list subject",1939-title => to_utf8($long)},1940 esc_html($short)) .$extra;1941}else{1942return$cgi->a({-href =>$href, -class=>"list subject"},1943 esc_html($long)) .$extra;1944}1945}19461947# Rather than recomputing the url for an email multiple times, we cache it1948# after the first hit. This gives a visible benefit in views where the avatar1949# for the same email is used repeatedly (e.g. shortlog).1950# The cache is shared by all avatar engines (currently gravatar only), which1951# are free to use it as preferred. Since only one avatar engine is used for any1952# given page, there's no risk for cache conflicts.1953our%avatar_cache= ();19541955# Compute the picon url for a given email, by using the picon search service over at1956# http://www.cs.indiana.edu/picons/search.html1957sub picon_url {1958my$email=lc shift;1959if(!$avatar_cache{$email}) {1960my($user,$domain) =split('@',$email);1961$avatar_cache{$email} =1962"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1963"$domain/$user/".1964"users+domains+unknown/up/single";1965}1966return$avatar_cache{$email};1967}19681969# Compute the gravatar url for a given email, if it's not in the cache already.1970# Gravatar stores only the part of the URL before the size, since that's the1971# one computationally more expensive. This also allows reuse of the cache for1972# different sizes (for this particular engine).1973sub gravatar_url {1974my$email=lc shift;1975my$size=shift;1976$avatar_cache{$email} ||=1977"http://www.gravatar.com/avatar/".1978 Digest::MD5::md5_hex($email) ."?s=";1979return$avatar_cache{$email} .$size;1980}19811982# Insert an avatar for the given $email at the given $size if the feature1983# is enabled.1984sub git_get_avatar {1985my($email,%opts) =@_;1986my$pre_white= ($opts{-pad_before} ?" ":"");1987my$post_white= ($opts{-pad_after} ?" ":"");1988$opts{-size} ||='default';1989my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1990my$url="";1991if($git_avatareq'gravatar') {1992$url= gravatar_url($email,$size);1993}elsif($git_avatareq'picon') {1994$url= picon_url($email);1995}1996# Other providers can be added by extending the if chain, defining $url1997# as needed. If no variant puts something in $url, we assume avatars1998# are completely disabled/unavailable.1999if($url) {2000return$pre_white.2001"<img width=\"$size\"".2002"class=\"avatar\"".2003"src=\"".esc_url($url)."\"".2004"alt=\"\"".2005"/>".$post_white;2006}else{2007return"";2008}2009}20102011sub format_search_author {2012my($author,$searchtype,$displaytext) =@_;2013my$have_search= gitweb_check_feature('search');20142015if($have_search) {2016my$performed="";2017if($searchtypeeq'author') {2018$performed="authored";2019}elsif($searchtypeeq'committer') {2020$performed="committed";2021}20222023return$cgi->a({-href => href(action=>"search", hash=>$hash,2024 searchtext=>$author,2025 searchtype=>$searchtype),class=>"list",2026 title=>"Search for commits$performedby$author"},2027$displaytext);20282029}else{2030return$displaytext;2031}2032}20332034# format the author name of the given commit with the given tag2035# the author name is chopped and escaped according to the other2036# optional parameters (see chop_str).2037sub format_author_html {2038my$tag=shift;2039my$co=shift;2040my$author= chop_and_escape_str($co->{'author_name'},@_);2041return"<$tagclass=\"author\">".2042 format_search_author($co->{'author_name'},"author",2043 git_get_avatar($co->{'author_email'}, -pad_after =>1) .2044$author) .2045"</$tag>";2046}20472048# format git diff header line, i.e. "diff --(git|combined|cc) ..."2049sub format_git_diff_header_line {2050my$line=shift;2051my$diffinfo=shift;2052my($from,$to) =@_;20532054if($diffinfo->{'nparents'}) {2055# combined diff2056$line=~s!^(diff (.*?) )"?.*$!$1!;2057if($to->{'href'}) {2058$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2059 esc_path($to->{'file'}));2060}else{# file was deleted (no href)2061$line.= esc_path($to->{'file'});2062}2063}else{2064# "ordinary" diff2065$line=~s!^(diff (.*?) )"?a/.*$!$1!;2066if($from->{'href'}) {2067$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},2068'a/'. esc_path($from->{'file'}));2069}else{# file was added (no href)2070$line.='a/'. esc_path($from->{'file'});2071}2072$line.=' ';2073if($to->{'href'}) {2074$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2075'b/'. esc_path($to->{'file'}));2076}else{# file was deleted2077$line.='b/'. esc_path($to->{'file'});2078}2079}20802081return"<div class=\"diff header\">$line</div>\n";2082}20832084# format extended diff header line, before patch itself2085sub format_extended_diff_header_line {2086my$line=shift;2087my$diffinfo=shift;2088my($from,$to) =@_;20892090# match <path>2091if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {2092$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},2093 esc_path($from->{'file'}));2094}2095if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {2096$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},2097 esc_path($to->{'file'}));2098}2099# match single <mode>2100if($line=~m/\s(\d{6})$/) {2101$line.='<span class="info"> ('.2102 file_type_long($1) .2103')</span>';2104}2105# match <hash>2106if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {2107# can match only for combined diff2108$line='index ';2109for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2110if($from->{'href'}[$i]) {2111$line.=$cgi->a({-href=>$from->{'href'}[$i],2112-class=>"hash"},2113substr($diffinfo->{'from_id'}[$i],0,7));2114}else{2115$line.='0' x 7;2116}2117# separator2118$line.=','if($i<$diffinfo->{'nparents'} -1);2119}2120$line.='..';2121if($to->{'href'}) {2122$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2123substr($diffinfo->{'to_id'},0,7));2124}else{2125$line.='0' x 7;2126}21272128}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {2129# can match only for ordinary diff2130my($from_link,$to_link);2131if($from->{'href'}) {2132$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},2133substr($diffinfo->{'from_id'},0,7));2134}else{2135$from_link='0' x 7;2136}2137if($to->{'href'}) {2138$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2139substr($diffinfo->{'to_id'},0,7));2140}else{2141$to_link='0' x 7;2142}2143my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});2144$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;2145}21462147return$line."<br/>\n";2148}21492150# format from-file/to-file diff header2151sub format_diff_from_to_header {2152my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2153my$line;2154my$result='';21552156$line=$from_line;2157#assert($line =~ m/^---/) if DEBUG;2158# no extra formatting for "^--- /dev/null"2159if(!$diffinfo->{'nparents'}) {2160# ordinary (single parent) diff2161if($line=~m!^--- "?a/!) {2162if($from->{'href'}) {2163$line='--- a/'.2164$cgi->a({-href=>$from->{'href'}, -class=>"path"},2165 esc_path($from->{'file'}));2166}else{2167$line='--- a/'.2168 esc_path($from->{'file'});2169}2170}2171$result.= qq!<div class="diff from_file">$line</div>\n!;21722173}else{2174# combined diff (merge commit)2175for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2176if($from->{'href'}[$i]) {2177$line='--- '.2178$cgi->a({-href=>href(action=>"blobdiff",2179 hash_parent=>$diffinfo->{'from_id'}[$i],2180 hash_parent_base=>$parents[$i],2181 file_parent=>$from->{'file'}[$i],2182 hash=>$diffinfo->{'to_id'},2183 hash_base=>$hash,2184 file_name=>$to->{'file'}),2185-class=>"path",2186-title=>"diff". ($i+1)},2187$i+1) .2188'/'.2189$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2190 esc_path($from->{'file'}[$i]));2191}else{2192$line='--- /dev/null';2193}2194$result.= qq!<div class="diff from_file">$line</div>\n!;2195}2196}21972198$line=$to_line;2199#assert($line =~ m/^\+\+\+/) if DEBUG;2200# no extra formatting for "^+++ /dev/null"2201if($line=~m!^\+\+\+ "?b/!) {2202if($to->{'href'}) {2203$line='+++ b/'.2204$cgi->a({-href=>$to->{'href'}, -class=>"path"},2205 esc_path($to->{'file'}));2206}else{2207$line='+++ b/'.2208 esc_path($to->{'file'});2209}2210}2211$result.= qq!<div class="diff to_file">$line</div>\n!;22122213return$result;2214}22152216# create note for patch simplified by combined diff2217sub format_diff_cc_simplified {2218my($diffinfo,@parents) =@_;2219my$result='';22202221$result.="<div class=\"diff header\">".2222"diff --cc ";2223if(!is_deleted($diffinfo)) {2224$result.=$cgi->a({-href => href(action=>"blob",2225 hash_base=>$hash,2226 hash=>$diffinfo->{'to_id'},2227 file_name=>$diffinfo->{'to_file'}),2228-class=>"path"},2229 esc_path($diffinfo->{'to_file'}));2230}else{2231$result.= esc_path($diffinfo->{'to_file'});2232}2233$result.="</div>\n".# class="diff header"2234"<div class=\"diff nodifferences\">".2235"Simple merge".2236"</div>\n";# class="diff nodifferences"22372238return$result;2239}22402241sub diff_line_class {2242my($line,$from,$to) =@_;22432244# ordinary diff2245my$num_sign=1;2246# combined diff2247if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2248$num_sign=scalar@{$from->{'href'}};2249}22502251my@diff_line_classifier= (2252{ regexp =>qr/^\@\@{$num_sign} /,class=>"chunk_header"},2253{ regexp =>qr/^\\/,class=>"incomplete"},2254{ regexp =>qr/^ {$num_sign}/,class=>"ctx"},2255# classifier for context must come before classifier add/rem,2256# or we would have to use more complicated regexp, for example2257# qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;2258{ regexp =>qr/^[+ ]{$num_sign}/,class=>"add"},2259{ regexp =>qr/^[- ]{$num_sign}/,class=>"rem"},2260);2261formy$clsfy(@diff_line_classifier) {2262return$clsfy->{'class'}2263if($line=~$clsfy->{'regexp'});2264}22652266# fallback2267return"";2268}22692270# assumes that $from and $to are defined and correctly filled,2271# and that $line holds a line of chunk header for unified diff2272sub format_unidiff_chunk_header {2273my($line,$from,$to) =@_;22742275my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2276$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;22772278$from_lines=0unlessdefined$from_lines;2279$to_lines=0unlessdefined$to_lines;22802281if($from->{'href'}) {2282$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2283-class=>"list"},$from_text);2284}2285if($to->{'href'}) {2286$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2287-class=>"list"},$to_text);2288}2289$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2290"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2291return$line;2292}22932294# assumes that $from and $to are defined and correctly filled,2295# and that $line holds a line of chunk header for combined diff2296sub format_cc_diff_chunk_header {2297my($line,$from,$to) =@_;22982299my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2300my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);23012302@from_text=split(' ',$ranges);2303for(my$i=0;$i<@from_text; ++$i) {2304($from_start[$i],$from_nlines[$i]) =2305(split(',',substr($from_text[$i],1)),0);2306}23072308$to_text=pop@from_text;2309$to_start=pop@from_start;2310$to_nlines=pop@from_nlines;23112312$line="<span class=\"chunk_info\">$prefix";2313for(my$i=0;$i<@from_text; ++$i) {2314if($from->{'href'}[$i]) {2315$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2316-class=>"list"},$from_text[$i]);2317}else{2318$line.=$from_text[$i];2319}2320$line.=" ";2321}2322if($to->{'href'}) {2323$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2324-class=>"list"},$to_text);2325}else{2326$line.=$to_text;2327}2328$line.="$prefix</span>".2329"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2330return$line;2331}23322333# process patch (diff) line (not to be used for diff headers),2334# returning class and HTML-formatted (but not wrapped) line2335sub process_diff_line {2336my$line=shift;2337my($from,$to) =@_;23382339my$diff_class= diff_line_class($line,$from,$to);23402341chomp$line;2342$line= untabify($line);23432344if($from&&$to&&$line=~m/^\@{2} /) {2345$line= format_unidiff_chunk_header($line,$from,$to);2346return$diff_class,$line;23472348}elsif($from&&$to&&$line=~m/^\@{3}/) {2349$line= format_cc_diff_chunk_header($line,$from,$to);2350return$diff_class,$line;23512352}2353return$diff_class, esc_html($line, -nbsp=>1);2354}23552356# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2357# linked. Pass the hash of the tree/commit to snapshot.2358sub format_snapshot_links {2359my($hash) =@_;2360my$num_fmts=@snapshot_fmts;2361if($num_fmts>1) {2362# A parenthesized list of links bearing format names.2363# e.g. "snapshot (_tar.gz_ _zip_)"2364return"snapshot (".join(' ',map2365$cgi->a({2366-href => href(2367 action=>"snapshot",2368 hash=>$hash,2369 snapshot_format=>$_2370)2371},$known_snapshot_formats{$_}{'display'})2372,@snapshot_fmts) .")";2373}elsif($num_fmts==1) {2374# A single "snapshot" link whose tooltip bears the format name.2375# i.e. "_snapshot_"2376my($fmt) =@snapshot_fmts;2377return2378$cgi->a({2379-href => href(2380 action=>"snapshot",2381 hash=>$hash,2382 snapshot_format=>$fmt2383),2384-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2385},"snapshot");2386}else{# $num_fmts == 02387returnundef;2388}2389}23902391## ......................................................................2392## functions returning values to be passed, perhaps after some2393## transformation, to other functions; e.g. returning arguments to href()23942395# returns hash to be passed to href to generate gitweb URL2396# in -title key it returns description of link2397sub get_feed_info {2398my$format=shift||'Atom';2399my%res= (action =>lc($format));24002401# feed links are possible only for project views2402return unless(defined$project);2403# some views should link to OPML, or to generic project feed,2404# or don't have specific feed yet (so they should use generic)2405return if(!$action||$action=~/^(?:tags|heads|forks|tag|search)$/x);24062407my$branch;2408# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2409# from tag links; this also makes possible to detect branch links2410if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2411(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2412$branch=$1;2413}2414# find log type for feed description (title)2415my$type='log';2416if(defined$file_name) {2417$type="history of$file_name";2418$type.="/"if($actioneq'tree');2419$type.=" on '$branch'"if(defined$branch);2420}else{2421$type="log of$branch"if(defined$branch);2422}24232424$res{-title} =$type;2425$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2426$res{'file_name'} =$file_name;24272428return%res;2429}24302431## ----------------------------------------------------------------------2432## git utility subroutines, invoking git commands24332434# returns path to the core git executable and the --git-dir parameter as list2435sub git_cmd {2436$number_of_git_cmds++;2437return$GIT,'--git-dir='.$git_dir;2438}24392440# quote the given arguments for passing them to the shell2441# quote_command("command", "arg 1", "arg with ' and ! characters")2442# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2443# Try to avoid using this function wherever possible.2444sub quote_command {2445returnjoin(' ',2446map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2447}24482449# get HEAD ref of given project as hash2450sub git_get_head_hash {2451return git_get_full_hash(shift,'HEAD');2452}24532454sub git_get_full_hash {2455return git_get_hash(@_);2456}24572458sub git_get_short_hash {2459return git_get_hash(@_,'--short=7');2460}24612462sub git_get_hash {2463my($project,$hash,@options) =@_;2464my$o_git_dir=$git_dir;2465my$retval=undef;2466$git_dir="$projectroot/$project";2467if(open my$fd,'-|', git_cmd(),'rev-parse',2468'--verify','-q',@options,$hash) {2469$retval= <$fd>;2470chomp$retvalifdefined$retval;2471close$fd;2472}2473if(defined$o_git_dir) {2474$git_dir=$o_git_dir;2475}2476return$retval;2477}24782479# get type of given object2480sub git_get_type {2481my$hash=shift;24822483open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2484my$type= <$fd>;2485close$fdorreturn;2486chomp$type;2487return$type;2488}24892490# repository configuration2491our$config_file='';2492our%config;24932494# store multiple values for single key as anonymous array reference2495# single values stored directly in the hash, not as [ <value> ]2496sub hash_set_multi {2497my($hash,$key,$value) =@_;24982499if(!exists$hash->{$key}) {2500$hash->{$key} =$value;2501}elsif(!ref$hash->{$key}) {2502$hash->{$key} = [$hash->{$key},$value];2503}else{2504push@{$hash->{$key}},$value;2505}2506}25072508# return hash of git project configuration2509# optionally limited to some section, e.g. 'gitweb'2510sub git_parse_project_config {2511my$section_regexp=shift;2512my%config;25132514local$/="\0";25152516open my$fh,"-|", git_cmd(),"config",'-z','-l',2517orreturn;25182519while(my$keyval= <$fh>) {2520chomp$keyval;2521my($key,$value) =split(/\n/,$keyval,2);25222523 hash_set_multi(\%config,$key,$value)2524if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2525}2526close$fh;25272528return%config;2529}25302531# convert config value to boolean: 'true' or 'false'2532# no value, number > 0, 'true' and 'yes' values are true2533# rest of values are treated as false (never as error)2534sub config_to_bool {2535my$val=shift;25362537return1if!defined$val;# section.key25382539# strip leading and trailing whitespace2540$val=~s/^\s+//;2541$val=~s/\s+$//;25422543return(($val=~/^\d+$/&&$val) ||# section.key = 12544($val=~/^(?:true|yes)$/i));# section.key = true2545}25462547# convert config value to simple decimal number2548# an optional value suffix of 'k', 'm', or 'g' will cause the value2549# to be multiplied by 1024, 1048576, or 10737418242550sub config_to_int {2551my$val=shift;25522553# strip leading and trailing whitespace2554$val=~s/^\s+//;2555$val=~s/\s+$//;25562557if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2558$unit=lc($unit);2559# unknown unit is treated as 12560return$num* ($uniteq'g'?1073741824:2561$uniteq'm'?1048576:2562$uniteq'k'?1024:1);2563}2564return$val;2565}25662567# convert config value to array reference, if needed2568sub config_to_multi {2569my$val=shift;25702571returnref($val) ?$val: (defined($val) ? [$val] : []);2572}25732574sub git_get_project_config {2575my($key,$type) =@_;25762577return unlessdefined$git_dir;25782579# key sanity check2580return unless($key);2581# only subsection, if exists, is case sensitive,2582# and not lowercased by 'git config -z -l'2583if(my($hi,$mi,$lo) = ($key=~/^([^.]*)\.(.*)\.([^.]*)$/)) {2584$key=join(".",lc($hi),$mi,lc($lo));2585}else{2586$key=lc($key);2587}2588$key=~s/^gitweb\.//;2589return if($key=~m/\W/);25902591# type sanity check2592if(defined$type) {2593$type=~s/^--//;2594$type=undef2595unless($typeeq'bool'||$typeeq'int');2596}25972598# get config2599if(!defined$config_file||2600$config_filene"$git_dir/config") {2601%config= git_parse_project_config('gitweb');2602$config_file="$git_dir/config";2603}26042605# check if config variable (key) exists2606return unlessexists$config{"gitweb.$key"};26072608# ensure given type2609if(!defined$type) {2610return$config{"gitweb.$key"};2611}elsif($typeeq'bool') {2612# backward compatibility: 'git config --bool' returns true/false2613return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2614}elsif($typeeq'int') {2615return config_to_int($config{"gitweb.$key"});2616}2617return$config{"gitweb.$key"};2618}26192620# get hash of given path at given ref2621sub git_get_hash_by_path {2622my$base=shift;2623my$path=shift||returnundef;2624my$type=shift;26252626$path=~ s,/+$,,;26272628open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2629or die_error(500,"Open git-ls-tree failed");2630my$line= <$fd>;2631close$fdorreturnundef;26322633if(!defined$line) {2634# there is no tree or hash given by $path at $base2635returnundef;2636}26372638#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2639$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2640if(defined$type&&$typene$2) {2641# type doesn't match2642returnundef;2643}2644return$3;2645}26462647# get path of entry with given hash at given tree-ish (ref)2648# used to get 'from' filename for combined diff (merge commit) for renames2649sub git_get_path_by_hash {2650my$base=shift||return;2651my$hash=shift||return;26522653local$/="\0";26542655open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2656orreturnundef;2657while(my$line= <$fd>) {2658chomp$line;26592660#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2661#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2662if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2663close$fd;2664return$1;2665}2666}2667close$fd;2668returnundef;2669}26702671## ......................................................................2672## git utility functions, directly accessing git repository26732674# get the value of config variable either from file named as the variable2675# itself in the repository ($GIT_DIR/$name file), or from gitweb.$name2676# configuration variable in the repository config file.2677sub git_get_file_or_project_config {2678my($path,$name) =@_;26792680$git_dir="$projectroot/$path";2681open my$fd,'<',"$git_dir/$name"2682orreturn git_get_project_config($name);2683my$conf= <$fd>;2684close$fd;2685if(defined$conf) {2686chomp$conf;2687}2688return$conf;2689}26902691sub git_get_project_description {2692my$path=shift;2693return git_get_file_or_project_config($path,'description');2694}26952696sub git_get_project_category {2697my$path=shift;2698return git_get_file_or_project_config($path,'category');2699}270027012702# supported formats:2703# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2704# - if its contents is a number, use it as tag weight,2705# - otherwise add a tag with weight 12706# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2707# the same value multiple times increases tag weight2708# * `gitweb.ctag' multi-valued repo config variable2709sub git_get_project_ctags {2710my$project=shift;2711my$ctags= {};27122713$git_dir="$projectroot/$project";2714if(opendir my$dh,"$git_dir/ctags") {2715my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2716foreachmy$tagfile(@files) {2717open my$ct,'<',$tagfile2718ornext;2719my$val= <$ct>;2720chomp$valif$val;2721close$ct;27222723(my$ctag=$tagfile) =~ s#.*/##;2724if($val=~/^\d+$/) {2725$ctags->{$ctag} =$val;2726}else{2727$ctags->{$ctag} =1;2728}2729}2730closedir$dh;27312732}elsif(open my$fh,'<',"$git_dir/ctags") {2733while(my$line= <$fh>) {2734chomp$line;2735$ctags->{$line}++if$line;2736}2737close$fh;27382739}else{2740my$taglist= config_to_multi(git_get_project_config('ctag'));2741foreachmy$tag(@$taglist) {2742$ctags->{$tag}++;2743}2744}27452746return$ctags;2747}27482749# return hash, where keys are content tags ('ctags'),2750# and values are sum of weights of given tag in every project2751sub git_gather_all_ctags {2752my$projects=shift;2753my$ctags= {};27542755foreachmy$p(@$projects) {2756foreachmy$ct(keys%{$p->{'ctags'}}) {2757$ctags->{$ct} +=$p->{'ctags'}->{$ct};2758}2759}27602761return$ctags;2762}27632764sub git_populate_project_tagcloud {2765my$ctags=shift;27662767# First, merge different-cased tags; tags vote on casing2768my%ctags_lc;2769foreach(keys%$ctags) {2770$ctags_lc{lc$_}->{count} +=$ctags->{$_};2771if(not$ctags_lc{lc$_}->{topcount}2772or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2773$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2774$ctags_lc{lc$_}->{topname} =$_;2775}2776}27772778my$cloud;2779my$matched=$input_params{'ctag'};2780if(eval{require HTML::TagCloud;1; }) {2781$cloud= HTML::TagCloud->new;2782foreachmy$ctag(sort keys%ctags_lc) {2783# Pad the title with spaces so that the cloud looks2784# less crammed.2785my$title= esc_html($ctags_lc{$ctag}->{topname});2786$title=~s/ / /g;2787$title=~s/^/ /g;2788$title=~s/$/ /g;2789if(defined$matched&&$matchedeq$ctag) {2790$title=qq(<span class="match">$title</span>);2791}2792$cloud->add($title, href(project=>undef, ctag=>$ctag),2793$ctags_lc{$ctag}->{count});2794}2795}else{2796$cloud= {};2797foreachmy$ctag(keys%ctags_lc) {2798my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2799if(defined$matched&&$matchedeq$ctag) {2800$title=qq(<span class="match">$title</span>);2801}2802$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};2803$cloud->{$ctag}{ctag} =2804$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);2805}2806}2807return$cloud;2808}28092810sub git_show_project_tagcloud {2811my($cloud,$count) =@_;2812if(ref$cloudeq'HTML::TagCloud') {2813return$cloud->html_and_css($count);2814}else{2815my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;2816return2817'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.2818join(', ',map{2819$cloud->{$_}->{'ctag'}2820}splice(@tags,0,$count)) .2821'</div>';2822}2823}28242825sub git_get_project_url_list {2826my$path=shift;28272828$git_dir="$projectroot/$path";2829open my$fd,'<',"$git_dir/cloneurl"2830orreturnwantarray?2831@{ config_to_multi(git_get_project_config('url')) } :2832 config_to_multi(git_get_project_config('url'));2833my@git_project_url_list=map{chomp;$_} <$fd>;2834close$fd;28352836returnwantarray?@git_project_url_list: \@git_project_url_list;2837}28382839sub git_get_projects_list {2840my$filter=shift||'';2841my@list;28422843$filter=~s/\.git$//;28442845if(-d $projects_list) {2846# search in directory2847my$dir=$projects_list;2848# remove the trailing "/"2849$dir=~s!/+$!!;2850my$pfxlen=length("$dir");2851my$pfxdepth= ($dir=~tr!/!!);2852# when filtering, search only given subdirectory2853if($filter) {2854$dir.="/$filter";2855$dir=~s!/+$!!;2856}28572858 File::Find::find({2859 follow_fast =>1,# follow symbolic links2860 follow_skip =>2,# ignore duplicates2861 dangling_symlinks =>0,# ignore dangling symlinks, silently2862 wanted =>sub{2863# global variables2864our$project_maxdepth;2865our$projectroot;2866# skip project-list toplevel, if we get it.2867return if(m!^[/.]$!);2868# only directories can be git repositories2869return unless(-d $_);2870# don't traverse too deep (Find is super slow on os x)2871# $project_maxdepth excludes depth of $projectroot2872if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2873$File::Find::prune =1;2874return;2875}28762877my$path=substr($File::Find::name,$pfxlen+1);2878# we check related file in $projectroot2879if(check_export_ok("$projectroot/$path")) {2880push@list, { path =>$path};2881$File::Find::prune =1;2882}2883},2884},"$dir");28852886}elsif(-f $projects_list) {2887# read from file(url-encoded):2888# 'git%2Fgit.git Linus+Torvalds'2889# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2890# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2891open my$fd,'<',$projects_listorreturn;2892 PROJECT:2893while(my$line= <$fd>) {2894chomp$line;2895my($path,$owner) =split' ',$line;2896$path= unescape($path);2897$owner= unescape($owner);2898if(!defined$path) {2899next;2900}2901# if $filter is rpovided, check if $path begins with $filter2902if($filter&&$path!~m!^\Q$filter\E/!) {2903next;2904}2905if(check_export_ok("$projectroot/$path")) {2906my$pr= {2907 path =>$path,2908 owner => to_utf8($owner),2909};2910push@list,$pr;2911}2912}2913close$fd;2914}2915return@list;2916}29172918# written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)2919# as side effects it sets 'forks' field to list of forks for forked projects2920sub filter_forks_from_projects_list {2921my$projects=shift;29222923my%trie;# prefix tree of directories (path components)2924# generate trie out of those directories that might contain forks2925foreachmy$pr(@$projects) {2926my$path=$pr->{'path'};2927$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory2928next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'2929next unless($path);# skip '.git' repository: tests, git-instaweb2930next unless(-d "$projectroot/$path");# containing directory exists2931$pr->{'forks'} = [];# there can be 0 or more forks of project29322933# add to trie2934my@dirs=split('/',$path);2935# walk the trie, until either runs out of components or out of trie2936my$ref= \%trie;2937while(scalar@dirs&&2938exists($ref->{$dirs[0]})) {2939$ref=$ref->{shift@dirs};2940}2941# create rest of trie structure from rest of components2942foreachmy$dir(@dirs) {2943$ref=$ref->{$dir} = {};2944}2945# create end marker, store $pr as a data2946$ref->{''} =$prif(!exists$ref->{''});2947}29482949# filter out forks, by finding shortest prefix match for paths2950my@filtered;2951 PROJECT:2952foreachmy$pr(@$projects) {2953# trie lookup2954my$ref= \%trie;2955 DIR:2956foreachmy$dir(split('/',$pr->{'path'})) {2957if(exists$ref->{''}) {2958# found [shortest] prefix, is a fork - skip it2959push@{$ref->{''}{'forks'}},$pr;2960next PROJECT;2961}2962if(!exists$ref->{$dir}) {2963# not in trie, cannot have prefix, not a fork2964push@filtered,$pr;2965next PROJECT;2966}2967# If the dir is there, we just walk one step down the trie.2968$ref=$ref->{$dir};2969}2970# we ran out of trie2971# (shouldn't happen: it's either no match, or end marker)2972push@filtered,$pr;2973}29742975return@filtered;2976}29772978# note: fill_project_list_info must be run first,2979# for 'descr_long' and 'ctags' to be filled2980sub search_projects_list {2981my($projlist,%opts) =@_;2982my$tagfilter=$opts{'tagfilter'};2983my$search_re=$opts{'search_regexp'};29842985return@$projlist2986unless($tagfilter||$search_re);29872988my@projects;2989 PROJECT:2990foreachmy$pr(@$projlist) {29912992if($tagfilter) {2993next unlessref($pr->{'ctags'})eq'HASH';2994next unless2995grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};2996}29972998if($search_re) {2999next unless3000$pr->{'path'} =~/$search_re/||3001$pr->{'descr_long'} =~/$search_re/;3002}30033004push@projects,$pr;3005}30063007return@projects;3008}30093010our$gitweb_project_owner=undef;3011sub git_get_project_list_from_file {30123013return if(defined$gitweb_project_owner);30143015$gitweb_project_owner= {};3016# read from file (url-encoded):3017# 'git%2Fgit.git Linus+Torvalds'3018# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'3019# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'3020if(-f $projects_list) {3021open(my$fd,'<',$projects_list);3022while(my$line= <$fd>) {3023chomp$line;3024my($pr,$ow) =split' ',$line;3025$pr= unescape($pr);3026$ow= unescape($ow);3027$gitweb_project_owner->{$pr} = to_utf8($ow);3028}3029close$fd;3030}3031}30323033sub git_get_project_owner {3034my$project=shift;3035my$owner;30363037returnundefunless$project;3038$git_dir="$projectroot/$project";30393040if(!defined$gitweb_project_owner) {3041 git_get_project_list_from_file();3042}30433044if(exists$gitweb_project_owner->{$project}) {3045$owner=$gitweb_project_owner->{$project};3046}3047if(!defined$owner){3048$owner= git_get_project_config('owner');3049}3050if(!defined$owner) {3051$owner= get_file_owner("$git_dir");3052}30533054return$owner;3055}30563057sub git_get_last_activity {3058my($path) =@_;3059my$fd;30603061$git_dir="$projectroot/$path";3062open($fd,"-|", git_cmd(),'for-each-ref',3063'--format=%(committer)',3064'--sort=-committerdate',3065'--count=1',3066'refs/heads')orreturn;3067my$most_recent= <$fd>;3068close$fdorreturn;3069if(defined$most_recent&&3070$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {3071my$timestamp=$1;3072my$age=time-$timestamp;3073return($age, age_string($age));3074}3075return(undef,undef);3076}30773078# Implementation note: when a single remote is wanted, we cannot use 'git3079# remote show -n' because that command always work (assuming it's a remote URL3080# if it's not defined), and we cannot use 'git remote show' because that would3081# try to make a network roundtrip. So the only way to find if that particular3082# remote is defined is to walk the list provided by 'git remote -v' and stop if3083# and when we find what we want.3084sub git_get_remotes_list {3085my$wanted=shift;3086my%remotes= ();30873088open my$fd,'-|', git_cmd(),'remote','-v';3089return unless$fd;3090while(my$remote= <$fd>) {3091chomp$remote;3092$remote=~s!\t(.*?)\s+\((\w+)\)$!!;3093next if$wantedand not$remoteeq$wanted;3094my($url,$key) = ($1,$2);30953096$remotes{$remote} ||= {'heads'=> () };3097$remotes{$remote}{$key} =$url;3098}3099close$fdorreturn;3100returnwantarray?%remotes: \%remotes;3101}31023103# Takes a hash of remotes as first parameter and fills it by adding the3104# available remote heads for each of the indicated remotes.3105sub fill_remote_heads {3106my$remotes=shift;3107my@heads=map{"remotes/$_"}keys%$remotes;3108my@remoteheads= git_get_heads_list(undef,@heads);3109foreachmy$remote(keys%$remotes) {3110$remotes->{$remote}{'heads'} = [grep{3111$_->{'name'} =~s!^$remote/!!3112}@remoteheads];3113}3114}31153116sub git_get_references {3117my$type=shift||"";3118my%refs;3119# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113120# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3121open my$fd,"-|", git_cmd(),"show-ref","--dereference",3122($type? ("--","refs/$type") : ())# use -- <pattern> if $type3123orreturn;31243125while(my$line= <$fd>) {3126chomp$line;3127if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3128if(defined$refs{$1}) {3129push@{$refs{$1}},$2;3130}else{3131$refs{$1} = [$2];3132}3133}3134}3135close$fdorreturn;3136return \%refs;3137}31383139sub git_get_rev_name_tags {3140my$hash=shift||returnundef;31413142open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3143orreturn;3144my$name_rev= <$fd>;3145close$fd;31463147if($name_rev=~ m|^$hash tags/(.*)$|) {3148return$1;3149}else{3150# catches also '$hash undefined' output3151returnundef;3152}3153}31543155## ----------------------------------------------------------------------3156## parse to hash functions31573158sub parse_date {3159my$epoch=shift;3160my$tz=shift||"-0000";31613162my%date;3163my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3164my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3165my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3166$date{'hour'} =$hour;3167$date{'minute'} =$min;3168$date{'mday'} =$mday;3169$date{'day'} =$days[$wday];3170$date{'month'} =$months[$mon];3171$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3172$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3173$date{'mday-time'} =sprintf"%d%s%02d:%02d",3174$mday,$months[$mon],$hour,$min;3175$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",31761900+$year,1+$mon,$mday,$hour,$min,$sec;31773178my($tz_sign,$tz_hour,$tz_min) =3179($tz=~m/^([-+])(\d\d)(\d\d)$/);3180$tz_sign= ($tz_signeq'-'? -1: +1);3181my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3182($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3183$date{'hour_local'} =$hour;3184$date{'minute_local'} =$min;3185$date{'tz_local'} =$tz;3186$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",31871900+$year,$mon+1,$mday,3188$hour,$min,$sec,$tz);3189return%date;3190}31913192sub parse_tag {3193my$tag_id=shift;3194my%tag;3195my@comment;31963197open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3198$tag{'id'} =$tag_id;3199while(my$line= <$fd>) {3200chomp$line;3201if($line=~m/^object ([0-9a-fA-F]{40})$/) {3202$tag{'object'} =$1;3203}elsif($line=~m/^type (.+)$/) {3204$tag{'type'} =$1;3205}elsif($line=~m/^tag (.+)$/) {3206$tag{'name'} =$1;3207}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3208$tag{'author'} =$1;3209$tag{'author_epoch'} =$2;3210$tag{'author_tz'} =$3;3211if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3212$tag{'author_name'} =$1;3213$tag{'author_email'} =$2;3214}else{3215$tag{'author_name'} =$tag{'author'};3216}3217}elsif($line=~m/--BEGIN/) {3218push@comment,$line;3219last;3220}elsif($lineeq"") {3221last;3222}3223}3224push@comment, <$fd>;3225$tag{'comment'} = \@comment;3226close$fdorreturn;3227if(!defined$tag{'name'}) {3228return3229};3230return%tag3231}32323233sub parse_commit_text {3234my($commit_text,$withparents) =@_;3235my@commit_lines=split'\n',$commit_text;3236my%co;32373238pop@commit_lines;# Remove '\0'32393240if(!@commit_lines) {3241return;3242}32433244my$header=shift@commit_lines;3245if($header!~m/^[0-9a-fA-F]{40}/) {3246return;3247}3248($co{'id'},my@parents) =split' ',$header;3249while(my$line=shift@commit_lines) {3250last if$lineeq"\n";3251if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3252$co{'tree'} =$1;3253}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3254push@parents,$1;3255}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3256$co{'author'} = to_utf8($1);3257$co{'author_epoch'} =$2;3258$co{'author_tz'} =$3;3259if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3260$co{'author_name'} =$1;3261$co{'author_email'} =$2;3262}else{3263$co{'author_name'} =$co{'author'};3264}3265}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3266$co{'committer'} = to_utf8($1);3267$co{'committer_epoch'} =$2;3268$co{'committer_tz'} =$3;3269if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3270$co{'committer_name'} =$1;3271$co{'committer_email'} =$2;3272}else{3273$co{'committer_name'} =$co{'committer'};3274}3275}3276}3277if(!defined$co{'tree'}) {3278return;3279};3280$co{'parents'} = \@parents;3281$co{'parent'} =$parents[0];32823283foreachmy$title(@commit_lines) {3284$title=~s/^ //;3285if($titlene"") {3286$co{'title'} = chop_str($title,80,5);3287# remove leading stuff of merges to make the interesting part visible3288if(length($title) >50) {3289$title=~s/^Automatic //;3290$title=~s/^merge (of|with) /Merge ... /i;3291if(length($title) >50) {3292$title=~s/(http|rsync):\/\///;3293}3294if(length($title) >50) {3295$title=~s/(master|www|rsync)\.//;3296}3297if(length($title) >50) {3298$title=~s/kernel.org:?//;3299}3300if(length($title) >50) {3301$title=~s/\/pub\/scm//;3302}3303}3304$co{'title_short'} = chop_str($title,50,5);3305last;3306}3307}3308if(!defined$co{'title'} ||$co{'title'}eq"") {3309$co{'title'} =$co{'title_short'} ='(no commit message)';3310}3311# remove added spaces3312foreachmy$line(@commit_lines) {3313$line=~s/^ //;3314}3315$co{'comment'} = \@commit_lines;33163317my$age=time-$co{'committer_epoch'};3318$co{'age'} =$age;3319$co{'age_string'} = age_string($age);3320my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3321if($age>60*60*24*7*2) {3322$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3323$co{'age_string_age'} =$co{'age_string'};3324}else{3325$co{'age_string_date'} =$co{'age_string'};3326$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3327}3328return%co;3329}33303331sub parse_commit {3332my($commit_id) =@_;3333my%co;33343335local$/="\0";33363337open my$fd,"-|", git_cmd(),"rev-list",3338"--parents",3339"--header",3340"--max-count=1",3341$commit_id,3342"--",3343or die_error(500,"Open git-rev-list failed");3344%co= parse_commit_text(<$fd>,1);3345close$fd;33463347return%co;3348}33493350sub parse_commits {3351my($commit_id,$maxcount,$skip,$filename,@args) =@_;3352my@cos;33533354$maxcount||=1;3355$skip||=0;33563357local$/="\0";33583359open my$fd,"-|", git_cmd(),"rev-list",3360"--header",3361@args,3362("--max-count=".$maxcount),3363("--skip=".$skip),3364@extra_options,3365$commit_id,3366"--",3367($filename? ($filename) : ())3368or die_error(500,"Open git-rev-list failed");3369while(my$line= <$fd>) {3370my%co= parse_commit_text($line);3371push@cos, \%co;3372}3373close$fd;33743375returnwantarray?@cos: \@cos;3376}33773378# parse line of git-diff-tree "raw" output3379sub parse_difftree_raw_line {3380my$line=shift;3381my%res;33823383# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3384# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3385if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3386$res{'from_mode'} =$1;3387$res{'to_mode'} =$2;3388$res{'from_id'} =$3;3389$res{'to_id'} =$4;3390$res{'status'} =$5;3391$res{'similarity'} =$6;3392if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3393($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3394}else{3395$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3396}3397}3398# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3399# combined diff (for merge commit)3400elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3401$res{'nparents'} =length($1);3402$res{'from_mode'} = [split(' ',$2) ];3403$res{'to_mode'} =pop@{$res{'from_mode'}};3404$res{'from_id'} = [split(' ',$3) ];3405$res{'to_id'} =pop@{$res{'from_id'}};3406$res{'status'} = [split('',$4) ];3407$res{'to_file'} = unquote($5);3408}3409# 'c512b523472485aef4fff9e57b229d9d243c967f'3410elsif($line=~m/^([0-9a-fA-F]{40})$/) {3411$res{'commit'} =$1;3412}34133414returnwantarray?%res: \%res;3415}34163417# wrapper: return parsed line of git-diff-tree "raw" output3418# (the argument might be raw line, or parsed info)3419sub parsed_difftree_line {3420my$line_or_ref=shift;34213422if(ref($line_or_ref)eq"HASH") {3423# pre-parsed (or generated by hand)3424return$line_or_ref;3425}else{3426return parse_difftree_raw_line($line_or_ref);3427}3428}34293430# parse line of git-ls-tree output3431sub parse_ls_tree_line {3432my$line=shift;3433my%opts=@_;3434my%res;34353436if($opts{'-l'}) {3437#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3438$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;34393440$res{'mode'} =$1;3441$res{'type'} =$2;3442$res{'hash'} =$3;3443$res{'size'} =$4;3444if($opts{'-z'}) {3445$res{'name'} =$5;3446}else{3447$res{'name'} = unquote($5);3448}3449}else{3450#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3451$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;34523453$res{'mode'} =$1;3454$res{'type'} =$2;3455$res{'hash'} =$3;3456if($opts{'-z'}) {3457$res{'name'} =$4;3458}else{3459$res{'name'} = unquote($4);3460}3461}34623463returnwantarray?%res: \%res;3464}34653466# generates _two_ hashes, references to which are passed as 2 and 3 argument3467sub parse_from_to_diffinfo {3468my($diffinfo,$from,$to,@parents) =@_;34693470if($diffinfo->{'nparents'}) {3471# combined diff3472$from->{'file'} = [];3473$from->{'href'} = [];3474 fill_from_file_info($diffinfo,@parents)3475unlessexists$diffinfo->{'from_file'};3476for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3477$from->{'file'}[$i] =3478defined$diffinfo->{'from_file'}[$i] ?3479$diffinfo->{'from_file'}[$i] :3480$diffinfo->{'to_file'};3481if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3482$from->{'href'}[$i] = href(action=>"blob",3483 hash_base=>$parents[$i],3484 hash=>$diffinfo->{'from_id'}[$i],3485 file_name=>$from->{'file'}[$i]);3486}else{3487$from->{'href'}[$i] =undef;3488}3489}3490}else{3491# ordinary (not combined) diff3492$from->{'file'} =$diffinfo->{'from_file'};3493if($diffinfo->{'status'}ne"A") {# not new (added) file3494$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3495 hash=>$diffinfo->{'from_id'},3496 file_name=>$from->{'file'});3497}else{3498delete$from->{'href'};3499}3500}35013502$to->{'file'} =$diffinfo->{'to_file'};3503if(!is_deleted($diffinfo)) {# file exists in result3504$to->{'href'} = href(action=>"blob", hash_base=>$hash,3505 hash=>$diffinfo->{'to_id'},3506 file_name=>$to->{'file'});3507}else{3508delete$to->{'href'};3509}3510}35113512## ......................................................................3513## parse to array of hashes functions35143515sub git_get_heads_list {3516my($limit,@classes) =@_;3517@classes= ('heads')unless@classes;3518my@patterns=map{"refs/$_"}@classes;3519my@headslist;35203521open my$fd,'-|', git_cmd(),'for-each-ref',3522($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3523'--format=%(objectname) %(refname) %(subject)%00%(committer)',3524@patterns3525orreturn;3526while(my$line= <$fd>) {3527my%ref_item;35283529chomp$line;3530my($refinfo,$committerinfo) =split(/\0/,$line);3531my($hash,$name,$title) =split(' ',$refinfo,3);3532my($committer,$epoch,$tz) =3533($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3534$ref_item{'fullname'} =$name;3535$name=~s!^refs/(?:head|remote)s/!!;35363537$ref_item{'name'} =$name;3538$ref_item{'id'} =$hash;3539$ref_item{'title'} =$title||'(no commit message)';3540$ref_item{'epoch'} =$epoch;3541if($epoch) {3542$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3543}else{3544$ref_item{'age'} ="unknown";3545}35463547push@headslist, \%ref_item;3548}3549close$fd;35503551returnwantarray?@headslist: \@headslist;3552}35533554sub git_get_tags_list {3555my$limit=shift;3556my@tagslist;35573558open my$fd,'-|', git_cmd(),'for-each-ref',3559($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3560'--format=%(objectname) %(objecttype) %(refname) '.3561'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3562'refs/tags'3563orreturn;3564while(my$line= <$fd>) {3565my%ref_item;35663567chomp$line;3568my($refinfo,$creatorinfo) =split(/\0/,$line);3569my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3570my($creator,$epoch,$tz) =3571($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3572$ref_item{'fullname'} =$name;3573$name=~s!^refs/tags/!!;35743575$ref_item{'type'} =$type;3576$ref_item{'id'} =$id;3577$ref_item{'name'} =$name;3578if($typeeq"tag") {3579$ref_item{'subject'} =$title;3580$ref_item{'reftype'} =$reftype;3581$ref_item{'refid'} =$refid;3582}else{3583$ref_item{'reftype'} =$type;3584$ref_item{'refid'} =$id;3585}35863587if($typeeq"tag"||$typeeq"commit") {3588$ref_item{'epoch'} =$epoch;3589if($epoch) {3590$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3591}else{3592$ref_item{'age'} ="unknown";3593}3594}35953596push@tagslist, \%ref_item;3597}3598close$fd;35993600returnwantarray?@tagslist: \@tagslist;3601}36023603## ----------------------------------------------------------------------3604## filesystem-related functions36053606sub get_file_owner {3607my$path=shift;36083609my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3610my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3611if(!defined$gcos) {3612returnundef;3613}3614my$owner=$gcos;3615$owner=~s/[,;].*$//;3616return to_utf8($owner);3617}36183619# assume that file exists3620sub insert_file {3621my$filename=shift;36223623open my$fd,'<',$filename;3624print map{ to_utf8($_) } <$fd>;3625close$fd;3626}36273628## ......................................................................3629## mimetype related functions36303631sub mimetype_guess_file {3632my$filename=shift;3633my$mimemap=shift;3634-r $mimemaporreturnundef;36353636my%mimemap;3637open(my$mh,'<',$mimemap)orreturnundef;3638while(<$mh>) {3639next ifm/^#/;# skip comments3640my($mimetype,@exts) =split(/\s+/);3641foreachmy$ext(@exts) {3642$mimemap{$ext} =$mimetype;3643}3644}3645close($mh);36463647$filename=~/\.([^.]*)$/;3648return$mimemap{$1};3649}36503651sub mimetype_guess {3652my$filename=shift;3653my$mime;3654$filename=~/\./orreturnundef;36553656if($mimetypes_file) {3657my$file=$mimetypes_file;3658if($file!~m!^/!) {# if it is relative path3659# it is relative to project3660$file="$projectroot/$project/$file";3661}3662$mime= mimetype_guess_file($filename,$file);3663}3664$mime||= mimetype_guess_file($filename,'/etc/mime.types');3665return$mime;3666}36673668sub blob_mimetype {3669my$fd=shift;3670my$filename=shift;36713672if($filename) {3673my$mime= mimetype_guess($filename);3674$mimeandreturn$mime;3675}36763677# just in case3678return$default_blob_plain_mimetypeunless$fd;36793680if(-T $fd) {3681return'text/plain';3682}elsif(!$filename) {3683return'application/octet-stream';3684}elsif($filename=~m/\.png$/i) {3685return'image/png';3686}elsif($filename=~m/\.gif$/i) {3687return'image/gif';3688}elsif($filename=~m/\.jpe?g$/i) {3689return'image/jpeg';3690}else{3691return'application/octet-stream';3692}3693}36943695sub blob_contenttype {3696my($fd,$file_name,$type) =@_;36973698$type||= blob_mimetype($fd,$file_name);3699if($typeeq'text/plain'&&defined$default_text_plain_charset) {3700$type.="; charset=$default_text_plain_charset";3701}37023703return$type;3704}37053706# guess file syntax for syntax highlighting; return undef if no highlighting3707# the name of syntax can (in the future) depend on syntax highlighter used3708sub guess_file_syntax {3709my($highlight,$mimetype,$file_name) =@_;3710returnundefunless($highlight&&defined$file_name);3711my$basename= basename($file_name,'.in');3712return$highlight_basename{$basename}3713ifexists$highlight_basename{$basename};37143715$basename=~/\.([^.]*)$/;3716my$ext=$1orreturnundef;3717return$highlight_ext{$ext}3718ifexists$highlight_ext{$ext};37193720returnundef;3721}37223723# run highlighter and return FD of its output,3724# or return original FD if no highlighting3725sub run_highlighter {3726my($fd,$highlight,$syntax) =@_;3727return$fdunless($highlight&&defined$syntax);37283729close$fd;3730open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3731 quote_command($highlight_bin).3732" --replace-tabs=8 --fragment --syntax$syntax|"3733or die_error(500,"Couldn't open file or run syntax highlighter");3734return$fd;3735}37363737## ======================================================================3738## functions printing HTML: header, footer, error page37393740sub get_page_title {3741my$title= to_utf8($site_name);37423743return$titleunless(defined$project);3744$title.=" - ". to_utf8($project);37453746return$titleunless(defined$action);3747$title.="/$action";# $action is US-ASCII (7bit ASCII)37483749return$titleunless(defined$file_name);3750$title.=" - ". esc_path($file_name);3751if($actioneq"tree"&&$file_name!~ m|/$|) {3752$title.="/";3753}37543755return$title;3756}37573758sub get_content_type_html {3759# require explicit support from the UA if we are to send the page as3760# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3761# we have to do this because MSIE sometimes globs '*/*', pretending to3762# support xhtml+xml but choking when it gets what it asked for.3763if(defined$cgi->http('HTTP_ACCEPT') &&3764$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3765$cgi->Accept('application/xhtml+xml') !=0) {3766return'application/xhtml+xml';3767}else{3768return'text/html';3769}3770}37713772sub print_feed_meta {3773if(defined$project) {3774my%href_params= get_feed_info();3775if(!exists$href_params{'-title'}) {3776$href_params{'-title'} ='log';3777}37783779foreachmy$format(qw(RSS Atom)) {3780my$type=lc($format);3781my%link_attr= (3782'-rel'=>'alternate',3783'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3784'-type'=>"application/$type+xml"3785);37863787$href_params{'action'} =$type;3788$link_attr{'-href'} = href(%href_params);3789print"<link ".3790"rel=\"$link_attr{'-rel'}\"".3791"title=\"$link_attr{'-title'}\"".3792"href=\"$link_attr{'-href'}\"".3793"type=\"$link_attr{'-type'}\"".3794"/>\n";37953796$href_params{'extra_options'} ='--no-merges';3797$link_attr{'-href'} = href(%href_params);3798$link_attr{'-title'} .=' (no merges)';3799print"<link ".3800"rel=\"$link_attr{'-rel'}\"".3801"title=\"$link_attr{'-title'}\"".3802"href=\"$link_attr{'-href'}\"".3803"type=\"$link_attr{'-type'}\"".3804"/>\n";3805}38063807}else{3808printf('<link rel="alternate" title="%sprojects list" '.3809'href="%s" type="text/plain; charset=utf-8" />'."\n",3810 esc_attr($site_name), href(project=>undef, action=>"project_index"));3811printf('<link rel="alternate" title="%sprojects feeds" '.3812'href="%s" type="text/x-opml" />'."\n",3813 esc_attr($site_name), href(project=>undef, action=>"opml"));3814}3815}38163817sub print_header_links {3818my$status=shift;38193820# print out each stylesheet that exist, providing backwards capability3821# for those people who defined $stylesheet in a config file3822if(defined$stylesheet) {3823print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3824}else{3825foreachmy$stylesheet(@stylesheets) {3826next unless$stylesheet;3827print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3828}3829}3830 print_feed_meta()3831if($statuseq'200 OK');3832if(defined$favicon) {3833printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);3834}3835}38363837sub print_nav_breadcrumbs {3838my%opts=@_;38393840print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3841if(defined$project) {3842print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3843if(defined$action) {3844my$action_print=$action;3845if(defined$opts{-action_extra}) {3846$action_print=$cgi->a({-href => href(action=>$action)},3847$action);3848}3849print" /$action_print";3850}3851if(defined$opts{-action_extra}) {3852print" /$opts{-action_extra}";3853}3854print"\n";3855}3856}38573858sub print_search_form {3859if(!defined$searchtext) {3860$searchtext="";3861}3862my$search_hash;3863if(defined$hash_base) {3864$search_hash=$hash_base;3865}elsif(defined$hash) {3866$search_hash=$hash;3867}else{3868$search_hash="HEAD";3869}3870my$action=$my_uri;3871my$use_pathinfo= gitweb_check_feature('pathinfo');3872if($use_pathinfo) {3873$action.="/".esc_url($project);3874}3875print$cgi->startform(-method=>"get", -action =>$action) .3876"<div class=\"search\">\n".3877(!$use_pathinfo&&3878$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3879$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3880$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3881$cgi->popup_menu(-name =>'st', -default=>'commit',3882-values=> ['commit','grep','author','committer','pickaxe']) .3883$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3884" search:\n",3885$cgi->textfield(-name =>"s", -value =>$searchtext, -override =>1) ."\n".3886"<span title=\"Extended regular expression\">".3887$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3888-checked =>$search_use_regexp) .3889"</span>".3890"</div>".3891$cgi->end_form() ."\n";3892}38933894sub git_header_html {3895my$status=shift||"200 OK";3896my$expires=shift;3897my%opts=@_;38983899my$title= get_page_title();3900my$content_type= get_content_type_html();3901print$cgi->header(-type=>$content_type, -charset =>'utf-8',3902-status=>$status, -expires =>$expires)3903unless($opts{'-no_http_header'});3904my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3905print<<EOF;3906<?xml version="1.0" encoding="utf-8"?>3907<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3908<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3909<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3910<!-- git core binaries version$git_version-->3911<head>3912<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3913<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3914<meta name="robots" content="index, nofollow"/>3915<title>$title</title>3916EOF3917# the stylesheet, favicon etc urls won't work correctly with path_info3918# unless we set the appropriate base URL3919if($ENV{'PATH_INFO'}) {3920print"<base href=\"".esc_url($base_url)."\"/>\n";3921}3922 print_header_links($status);39233924if(defined$site_html_head_string) {3925print to_utf8($site_html_head_string);3926}39273928print"</head>\n".3929"<body>\n";39303931if(defined$site_header&& -f $site_header) {3932 insert_file($site_header);3933}39343935print"<div class=\"page_header\">\n";3936if(defined$logo) {3937print$cgi->a({-href => esc_url($logo_url),3938-title =>$logo_label},3939$cgi->img({-src => esc_url($logo),3940-width =>72, -height =>27,3941-alt =>"git",3942-class=>"logo"}));3943}3944 print_nav_breadcrumbs(%opts);3945print"</div>\n";39463947my$have_search= gitweb_check_feature('search');3948if(defined$project&&$have_search) {3949 print_search_form();3950}3951}39523953sub git_footer_html {3954my$feed_class='rss_logo';39553956print"<div class=\"page_footer\">\n";3957if(defined$project) {3958my$descr= git_get_project_description($project);3959if(defined$descr) {3960print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3961}39623963my%href_params= get_feed_info();3964if(!%href_params) {3965$feed_class.=' generic';3966}3967$href_params{'-title'} ||='log';39683969foreachmy$format(qw(RSS Atom)) {3970$href_params{'action'} =lc($format);3971print$cgi->a({-href => href(%href_params),3972-title =>"$href_params{'-title'}$formatfeed",3973-class=>$feed_class},$format)."\n";3974}39753976}else{3977print$cgi->a({-href => href(project=>undef, action=>"opml"),3978-class=>$feed_class},"OPML") ." ";3979print$cgi->a({-href => href(project=>undef, action=>"project_index"),3980-class=>$feed_class},"TXT") ."\n";3981}3982print"</div>\n";# class="page_footer"39833984if(defined$t0&& gitweb_check_feature('timed')) {3985print"<div id=\"generating_info\">\n";3986print'This page took '.3987'<span id="generating_time" class="time_span">'.3988 tv_interval($t0, [ gettimeofday() ]).3989' seconds </span>'.3990' and '.3991'<span id="generating_cmd">'.3992$number_of_git_cmds.3993'</span> git commands '.3994" to generate.\n";3995print"</div>\n";# class="page_footer"3996}39973998if(defined$site_footer&& -f $site_footer) {3999 insert_file($site_footer);4000}40014002print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;4003if(defined$action&&4004$actioneq'blame_incremental') {4005print qq!<script type="text/javascript">\n!.4006 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.4007 qq!"!. href() .qq!");\n!.4008 qq!</script>\n!;4009}else{4010my($jstimezone,$tz_cookie,$datetime_class) =4011 gitweb_get_feature('javascript-timezone');40124013print qq!<script type="text/javascript">\n!.4014 qq!window.onload = function () {\n!;4015if(gitweb_check_feature('javascript-actions')) {4016print qq! fixLinks();\n!;4017}4018if($jstimezone&&$tz_cookie&&$datetime_class) {4019print qq! var tz_cookie = { name:'$tz_cookie', expires:14, path:'/'};\n!.# in days4020 qq! onloadTZSetup('$jstimezone', tz_cookie,'$datetime_class');\n!;4021}4022print qq!};\n!.4023 qq!</script>\n!;4024}40254026print"</body>\n".4027"</html>";4028}40294030# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])4031# Example: die_error(404, 'Hash not found')4032# By convention, use the following status codes (as defined in RFC 2616):4033# 400: Invalid or missing CGI parameters, or4034# requested object exists but has wrong type.4035# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on4036# this server or project.4037# 404: Requested object/revision/project doesn't exist.4038# 500: The server isn't configured properly, or4039# an internal error occurred (e.g. failed assertions caused by bugs), or4040# an unknown error occurred (e.g. the git binary died unexpectedly).4041# 503: The server is currently unavailable (because it is overloaded,4042# or down for maintenance). Generally, this is a temporary state.4043sub die_error {4044my$status=shift||500;4045my$error= esc_html(shift) ||"Internal Server Error";4046my$extra=shift;4047my%opts=@_;40484049my%http_responses= (4050400=>'400 Bad Request',4051403=>'403 Forbidden',4052404=>'404 Not Found',4053500=>'500 Internal Server Error',4054503=>'503 Service Unavailable',4055);4056 git_header_html($http_responses{$status},undef,%opts);4057print<<EOF;4058<div class="page_body">4059<br /><br />4060$status-$error4061<br />4062EOF4063if(defined$extra) {4064print"<hr />\n".4065"$extra\n";4066}4067print"</div>\n";40684069 git_footer_html();4070goto DONE_GITWEB4071unless($opts{'-error_handler'});4072}40734074## ----------------------------------------------------------------------4075## functions printing or outputting HTML: navigation40764077sub git_print_page_nav {4078my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;4079$extra=''if!defined$extra;# pager or formats40804081my@navs=qw(summary shortlog log commit commitdiff tree);4082if($suppress) {4083@navs=grep{$_ne$suppress}@navs;4084}40854086my%arg=map{$_=> {action=>$_} }@navs;4087if(defined$head) {4088for(qw(commit commitdiff)) {4089$arg{$_}{'hash'} =$head;4090}4091if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {4092for(qw(shortlog log)) {4093$arg{$_}{'hash'} =$head;4094}4095}4096}40974098$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;4099$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;41004101my@actions= gitweb_get_feature('actions');4102my%repl= (4103'%'=>'%',4104'n'=>$project,# project name4105'f'=>$git_dir,# project path within filesystem4106'h'=>$treehead||'',# current hash ('h' parameter)4107'b'=>$treebase||'',# hash base ('hb' parameter)4108);4109while(@actions) {4110my($label,$link,$pos) =splice(@actions,0,3);4111# insert4112@navs=map{$_eq$pos? ($_,$label) :$_}@navs;4113# munch munch4114$link=~s/%([%nfhb])/$repl{$1}/g;4115$arg{$label}{'_href'} =$link;4116}41174118print"<div class=\"page_nav\">\n".4119(join" | ",4120map{$_eq$current?4121$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4122}@navs);4123print"<br/>\n$extra<br/>\n".4124"</div>\n";4125}41264127# returns a submenu for the nagivation of the refs views (tags, heads,4128# remotes) with the current view disabled and the remotes view only4129# available if the feature is enabled4130sub format_ref_views {4131my($current) =@_;4132my@ref_views=qw{tags heads};4133push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4134returnjoin" | ",map{4135$_eq$current?$_:4136$cgi->a({-href => href(action=>$_)},$_)4137}@ref_views4138}41394140sub format_paging_nav {4141my($action,$page,$has_next_link) =@_;4142my$paging_nav;414341444145if($page>0) {4146$paging_nav.=4147$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4148" ⋅ ".4149$cgi->a({-href => href(-replay=>1, page=>$page-1),4150-accesskey =>"p", -title =>"Alt-p"},"prev");4151}else{4152$paging_nav.="first ⋅ prev";4153}41544155if($has_next_link) {4156$paging_nav.=" ⋅ ".4157$cgi->a({-href => href(-replay=>1, page=>$page+1),4158-accesskey =>"n", -title =>"Alt-n"},"next");4159}else{4160$paging_nav.=" ⋅ next";4161}41624163return$paging_nav;4164}41654166## ......................................................................4167## functions printing or outputting HTML: div41684169sub git_print_header_div {4170my($action,$title,$hash,$hash_base) =@_;4171my%args= ();41724173$args{'action'} =$action;4174$args{'hash'} =$hashif$hash;4175$args{'hash_base'} =$hash_baseif$hash_base;41764177print"<div class=\"header\">\n".4178$cgi->a({-href => href(%args), -class=>"title"},4179$title?$title:$action) .4180"\n</div>\n";4181}41824183sub format_repo_url {4184my($name,$url) =@_;4185return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4186}41874188# Group output by placing it in a DIV element and adding a header.4189# Options for start_div() can be provided by passing a hash reference as the4190# first parameter to the function.4191# Options to git_print_header_div() can be provided by passing an array4192# reference. This must follow the options to start_div if they are present.4193# The content can be a scalar, which is output as-is, a scalar reference, which4194# is output after html escaping, an IO handle passed either as *handle or4195# *handle{IO}, or a function reference. In the latter case all following4196# parameters will be taken as argument to the content function call.4197sub git_print_section {4198my($div_args,$header_args,$content);4199my$arg=shift;4200if(ref($arg)eq'HASH') {4201$div_args=$arg;4202$arg=shift;4203}4204if(ref($arg)eq'ARRAY') {4205$header_args=$arg;4206$arg=shift;4207}4208$content=$arg;42094210print$cgi->start_div($div_args);4211 git_print_header_div(@$header_args);42124213if(ref($content)eq'CODE') {4214$content->(@_);4215}elsif(ref($content)eq'SCALAR') {4216print esc_html($$content);4217}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4218print<$content>;4219}elsif(!ref($content) &&defined($content)) {4220print$content;4221}42224223print$cgi->end_div;4224}42254226sub format_timestamp_html {4227my$date=shift;4228my$strtime=$date->{'rfc2822'};42294230my(undef,undef,$datetime_class) =4231 gitweb_get_feature('javascript-timezone');4232if($datetime_class) {4233$strtime= qq!<span class="$datetime_class">$strtime</span>!;4234}42354236my$localtime_format='(%02d:%02d%s)';4237if($date->{'hour_local'} <6) {4238$localtime_format='(<span class="atnight">%02d:%02d</span>%s)';4239}4240$strtime.=' '.4241sprintf($localtime_format,4242$date->{'hour_local'},$date->{'minute_local'},$date->{'tz_local'});42434244return$strtime;4245}42464247# Outputs the author name and date in long form4248sub git_print_authorship {4249my$co=shift;4250my%opts=@_;4251my$tag=$opts{-tag} ||'div';4252my$author=$co->{'author_name'};42534254my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4255print"<$tagclass=\"author_date\">".4256 format_search_author($author,"author", esc_html($author)) .4257" [".format_timestamp_html(\%ad)."]".4258 git_get_avatar($co->{'author_email'}, -pad_before =>1) .4259"</$tag>\n";4260}42614262# Outputs table rows containing the full author or committer information,4263# in the format expected for 'commit' view (& similar).4264# Parameters are a commit hash reference, followed by the list of people4265# to output information for. If the list is empty it defaults to both4266# author and committer.4267sub git_print_authorship_rows {4268my$co=shift;4269# too bad we can't use @people = @_ || ('author', 'committer')4270my@people=@_;4271@people= ('author','committer')unless@people;4272foreachmy$who(@people) {4273my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4274print"<tr><td>$who</td><td>".4275 format_search_author($co->{"${who}_name"},$who,4276 esc_html($co->{"${who}_name"})) ." ".4277 format_search_author($co->{"${who}_email"},$who,4278 esc_html("<".$co->{"${who}_email"} .">")) .4279"</td><td rowspan=\"2\">".4280 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4281"</td></tr>\n".4282"<tr>".4283"<td></td><td>".4284 format_timestamp_html(\%wd) .4285"</td>".4286"</tr>\n";4287}4288}42894290sub git_print_page_path {4291my$name=shift;4292my$type=shift;4293my$hb=shift;429442954296print"<div class=\"page_path\">";4297print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4298-title =>'tree root'}, to_utf8("[$project]"));4299print" / ";4300if(defined$name) {4301my@dirname=split'/',$name;4302my$basename=pop@dirname;4303my$fullname='';43044305foreachmy$dir(@dirname) {4306$fullname.= ($fullname?'/':'') .$dir;4307print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4308 hash_base=>$hb),4309-title =>$fullname}, esc_path($dir));4310print" / ";4311}4312if(defined$type&&$typeeq'blob') {4313print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4314 hash_base=>$hb),4315-title =>$name}, esc_path($basename));4316}elsif(defined$type&&$typeeq'tree') {4317print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4318 hash_base=>$hb),4319-title =>$name}, esc_path($basename));4320print" / ";4321}else{4322print esc_path($basename);4323}4324}4325print"<br/></div>\n";4326}43274328sub git_print_log {4329my$log=shift;4330my%opts=@_;43314332if($opts{'-remove_title'}) {4333# remove title, i.e. first line of log4334shift@$log;4335}4336# remove leading empty lines4337while(defined$log->[0] &&$log->[0]eq"") {4338shift@$log;4339}43404341# print log4342my$signoff=0;4343my$empty=0;4344foreachmy$line(@$log) {4345if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {4346$signoff=1;4347$empty=0;4348if(!$opts{'-remove_signoff'}) {4349print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4350next;4351}else{4352# remove signoff lines4353next;4354}4355}else{4356$signoff=0;4357}43584359# print only one empty line4360# do not print empty line after signoff4361if($lineeq"") {4362next if($empty||$signoff);4363$empty=1;4364}else{4365$empty=0;4366}43674368print format_log_line_html($line) ."<br/>\n";4369}43704371if($opts{'-final_empty_line'}) {4372# end with single empty line4373print"<br/>\n"unless$empty;4374}4375}43764377# return link target (what link points to)4378sub git_get_link_target {4379my$hash=shift;4380my$link_target;43814382# read link4383open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4384orreturn;4385{4386local$/=undef;4387$link_target= <$fd>;4388}4389close$fd4390orreturn;43914392return$link_target;4393}43944395# given link target, and the directory (basedir) the link is in,4396# return target of link relative to top directory (top tree);4397# return undef if it is not possible (including absolute links).4398sub normalize_link_target {4399my($link_target,$basedir) =@_;44004401# absolute symlinks (beginning with '/') cannot be normalized4402return if(substr($link_target,0,1)eq'/');44034404# normalize link target to path from top (root) tree (dir)4405my$path;4406if($basedir) {4407$path=$basedir.'/'.$link_target;4408}else{4409# we are in top (root) tree (dir)4410$path=$link_target;4411}44124413# remove //, /./, and /../4414my@path_parts;4415foreachmy$part(split('/',$path)) {4416# discard '.' and ''4417next if(!$part||$parteq'.');4418# handle '..'4419if($parteq'..') {4420if(@path_parts) {4421pop@path_parts;4422}else{4423# link leads outside repository (outside top dir)4424return;4425}4426}else{4427push@path_parts,$part;4428}4429}4430$path=join('/',@path_parts);44314432return$path;4433}44344435# print tree entry (row of git_tree), but without encompassing <tr> element4436sub git_print_tree_entry {4437my($t,$basedir,$hash_base,$have_blame) =@_;44384439my%base_key= ();4440$base_key{'hash_base'} =$hash_baseifdefined$hash_base;44414442# The format of a table row is: mode list link. Where mode is4443# the mode of the entry, list is the name of the entry, an href,4444# and link is the action links of the entry.44454446print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4447if(exists$t->{'size'}) {4448print"<td class=\"size\">$t->{'size'}</td>\n";4449}4450if($t->{'type'}eq"blob") {4451print"<td class=\"list\">".4452$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4453 file_name=>"$basedir$t->{'name'}",%base_key),4454-class=>"list"}, esc_path($t->{'name'}));4455if(S_ISLNK(oct$t->{'mode'})) {4456my$link_target= git_get_link_target($t->{'hash'});4457if($link_target) {4458my$norm_target= normalize_link_target($link_target,$basedir);4459if(defined$norm_target) {4460print" -> ".4461$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4462 file_name=>$norm_target),4463-title =>$norm_target}, esc_path($link_target));4464}else{4465print" -> ". esc_path($link_target);4466}4467}4468}4469print"</td>\n";4470print"<td class=\"link\">";4471print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4472 file_name=>"$basedir$t->{'name'}",%base_key)},4473"blob");4474if($have_blame) {4475print" | ".4476$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4477 file_name=>"$basedir$t->{'name'}",%base_key)},4478"blame");4479}4480if(defined$hash_base) {4481print" | ".4482$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4483 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4484"history");4485}4486print" | ".4487$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4488 file_name=>"$basedir$t->{'name'}")},4489"raw");4490print"</td>\n";44914492}elsif($t->{'type'}eq"tree") {4493print"<td class=\"list\">";4494print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4495 file_name=>"$basedir$t->{'name'}",4496%base_key)},4497 esc_path($t->{'name'}));4498print"</td>\n";4499print"<td class=\"link\">";4500print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4501 file_name=>"$basedir$t->{'name'}",4502%base_key)},4503"tree");4504if(defined$hash_base) {4505print" | ".4506$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4507 file_name=>"$basedir$t->{'name'}")},4508"history");4509}4510print"</td>\n";4511}else{4512# unknown object: we can only present history for it4513# (this includes 'commit' object, i.e. submodule support)4514print"<td class=\"list\">".4515 esc_path($t->{'name'}) .4516"</td>\n";4517print"<td class=\"link\">";4518if(defined$hash_base) {4519print$cgi->a({-href => href(action=>"history",4520 hash_base=>$hash_base,4521 file_name=>"$basedir$t->{'name'}")},4522"history");4523}4524print"</td>\n";4525}4526}45274528## ......................................................................4529## functions printing large fragments of HTML45304531# get pre-image filenames for merge (combined) diff4532sub fill_from_file_info {4533my($diff,@parents) =@_;45344535$diff->{'from_file'} = [ ];4536$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4537for(my$i=0;$i<$diff->{'nparents'};$i++) {4538if($diff->{'status'}[$i]eq'R'||4539$diff->{'status'}[$i]eq'C') {4540$diff->{'from_file'}[$i] =4541 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4542}4543}45444545return$diff;4546}45474548# is current raw difftree line of file deletion4549sub is_deleted {4550my$diffinfo=shift;45514552return$diffinfo->{'to_id'}eq('0' x 40);4553}45544555# does patch correspond to [previous] difftree raw line4556# $diffinfo - hashref of parsed raw diff format4557# $patchinfo - hashref of parsed patch diff format4558# (the same keys as in $diffinfo)4559sub is_patch_split {4560my($diffinfo,$patchinfo) =@_;45614562returndefined$diffinfo&&defined$patchinfo4563&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4564}456545664567sub git_difftree_body {4568my($difftree,$hash,@parents) =@_;4569my($parent) =$parents[0];4570my$have_blame= gitweb_check_feature('blame');4571print"<div class=\"list_head\">\n";4572if($#{$difftree} >10) {4573print(($#{$difftree} +1) ." files changed:\n");4574}4575print"</div>\n";45764577print"<table class=\"".4578(@parents>1?"combined ":"") .4579"diff_tree\">\n";45804581# header only for combined diff in 'commitdiff' view4582my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4583if($has_header) {4584# table header4585print"<thead><tr>\n".4586"<th></th><th></th>\n";# filename, patchN link4587for(my$i=0;$i<@parents;$i++) {4588my$par=$parents[$i];4589print"<th>".4590$cgi->a({-href => href(action=>"commitdiff",4591 hash=>$hash, hash_parent=>$par),4592-title =>'commitdiff to parent number '.4593($i+1) .': '.substr($par,0,7)},4594$i+1) .4595" </th>\n";4596}4597print"</tr></thead>\n<tbody>\n";4598}45994600my$alternate=1;4601my$patchno=0;4602foreachmy$line(@{$difftree}) {4603my$diff= parsed_difftree_line($line);46044605if($alternate) {4606print"<tr class=\"dark\">\n";4607}else{4608print"<tr class=\"light\">\n";4609}4610$alternate^=1;46114612if(exists$diff->{'nparents'}) {# combined diff46134614 fill_from_file_info($diff,@parents)4615unlessexists$diff->{'from_file'};46164617if(!is_deleted($diff)) {4618# file exists in the result (child) commit4619print"<td>".4620$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4621 file_name=>$diff->{'to_file'},4622 hash_base=>$hash),4623-class=>"list"}, esc_path($diff->{'to_file'})) .4624"</td>\n";4625}else{4626print"<td>".4627 esc_path($diff->{'to_file'}) .4628"</td>\n";4629}46304631if($actioneq'commitdiff') {4632# link to patch4633$patchno++;4634print"<td class=\"link\">".4635$cgi->a({-href => href(-anchor=>"patch$patchno")},4636"patch") .4637" | ".4638"</td>\n";4639}46404641my$has_history=0;4642my$not_deleted=0;4643for(my$i=0;$i<$diff->{'nparents'};$i++) {4644my$hash_parent=$parents[$i];4645my$from_hash=$diff->{'from_id'}[$i];4646my$from_path=$diff->{'from_file'}[$i];4647my$status=$diff->{'status'}[$i];46484649$has_history||= ($statusne'A');4650$not_deleted||= ($statusne'D');46514652if($statuseq'A') {4653print"<td class=\"link\"align=\"right\"> | </td>\n";4654}elsif($statuseq'D') {4655print"<td class=\"link\">".4656$cgi->a({-href => href(action=>"blob",4657 hash_base=>$hash,4658 hash=>$from_hash,4659 file_name=>$from_path)},4660"blob". ($i+1)) .4661" | </td>\n";4662}else{4663if($diff->{'to_id'}eq$from_hash) {4664print"<td class=\"link nochange\">";4665}else{4666print"<td class=\"link\">";4667}4668print$cgi->a({-href => href(action=>"blobdiff",4669 hash=>$diff->{'to_id'},4670 hash_parent=>$from_hash,4671 hash_base=>$hash,4672 hash_parent_base=>$hash_parent,4673 file_name=>$diff->{'to_file'},4674 file_parent=>$from_path)},4675"diff". ($i+1)) .4676" | </td>\n";4677}4678}46794680print"<td class=\"link\">";4681if($not_deleted) {4682print$cgi->a({-href => href(action=>"blob",4683 hash=>$diff->{'to_id'},4684 file_name=>$diff->{'to_file'},4685 hash_base=>$hash)},4686"blob");4687print" | "if($has_history);4688}4689if($has_history) {4690print$cgi->a({-href => href(action=>"history",4691 file_name=>$diff->{'to_file'},4692 hash_base=>$hash)},4693"history");4694}4695print"</td>\n";46964697print"</tr>\n";4698next;# instead of 'else' clause, to avoid extra indent4699}4700# else ordinary diff47014702my($to_mode_oct,$to_mode_str,$to_file_type);4703my($from_mode_oct,$from_mode_str,$from_file_type);4704if($diff->{'to_mode'}ne('0' x 6)) {4705$to_mode_oct=oct$diff->{'to_mode'};4706if(S_ISREG($to_mode_oct)) {# only for regular file4707$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4708}4709$to_file_type= file_type($diff->{'to_mode'});4710}4711if($diff->{'from_mode'}ne('0' x 6)) {4712$from_mode_oct=oct$diff->{'from_mode'};4713if(S_ISREG($from_mode_oct)) {# only for regular file4714$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4715}4716$from_file_type= file_type($diff->{'from_mode'});4717}47184719if($diff->{'status'}eq"A") {# created4720my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4721$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4722$mode_chng.="]</span>";4723print"<td>";4724print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4725 hash_base=>$hash, file_name=>$diff->{'file'}),4726-class=>"list"}, esc_path($diff->{'file'}));4727print"</td>\n";4728print"<td>$mode_chng</td>\n";4729print"<td class=\"link\">";4730if($actioneq'commitdiff') {4731# link to patch4732$patchno++;4733print$cgi->a({-href => href(-anchor=>"patch$patchno")},4734"patch") .4735" | ";4736}4737print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4738 hash_base=>$hash, file_name=>$diff->{'file'})},4739"blob");4740print"</td>\n";47414742}elsif($diff->{'status'}eq"D") {# deleted4743my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4744print"<td>";4745print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4746 hash_base=>$parent, file_name=>$diff->{'file'}),4747-class=>"list"}, esc_path($diff->{'file'}));4748print"</td>\n";4749print"<td>$mode_chng</td>\n";4750print"<td class=\"link\">";4751if($actioneq'commitdiff') {4752# link to patch4753$patchno++;4754print$cgi->a({-href => href(-anchor=>"patch$patchno")},4755"patch") .4756" | ";4757}4758print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4759 hash_base=>$parent, file_name=>$diff->{'file'})},4760"blob") ." | ";4761if($have_blame) {4762print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4763 file_name=>$diff->{'file'})},4764"blame") ." | ";4765}4766print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4767 file_name=>$diff->{'file'})},4768"history");4769print"</td>\n";47704771}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4772my$mode_chnge="";4773if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4774$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4775if($from_file_typene$to_file_type) {4776$mode_chnge.=" from$from_file_typeto$to_file_type";4777}4778if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4779if($from_mode_str&&$to_mode_str) {4780$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4781}elsif($to_mode_str) {4782$mode_chnge.=" mode:$to_mode_str";4783}4784}4785$mode_chnge.="]</span>\n";4786}4787print"<td>";4788print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4789 hash_base=>$hash, file_name=>$diff->{'file'}),4790-class=>"list"}, esc_path($diff->{'file'}));4791print"</td>\n";4792print"<td>$mode_chnge</td>\n";4793print"<td class=\"link\">";4794if($actioneq'commitdiff') {4795# link to patch4796$patchno++;4797print$cgi->a({-href => href(-anchor=>"patch$patchno")},4798"patch") .4799" | ";4800}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4801# "commit" view and modified file (not onlu mode changed)4802print$cgi->a({-href => href(action=>"blobdiff",4803 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4804 hash_base=>$hash, hash_parent_base=>$parent,4805 file_name=>$diff->{'file'})},4806"diff") .4807" | ";4808}4809print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4810 hash_base=>$hash, file_name=>$diff->{'file'})},4811"blob") ." | ";4812if($have_blame) {4813print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4814 file_name=>$diff->{'file'})},4815"blame") ." | ";4816}4817print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4818 file_name=>$diff->{'file'})},4819"history");4820print"</td>\n";48214822}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4823my%status_name= ('R'=>'moved','C'=>'copied');4824my$nstatus=$status_name{$diff->{'status'}};4825my$mode_chng="";4826if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4827# mode also for directories, so we cannot use $to_mode_str4828$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4829}4830print"<td>".4831$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4832 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4833-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4834"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4835$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4836 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4837-class=>"list"}, esc_path($diff->{'from_file'})) .4838" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4839"<td class=\"link\">";4840if($actioneq'commitdiff') {4841# link to patch4842$patchno++;4843print$cgi->a({-href => href(-anchor=>"patch$patchno")},4844"patch") .4845" | ";4846}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4847# "commit" view and modified file (not only pure rename or copy)4848print$cgi->a({-href => href(action=>"blobdiff",4849 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4850 hash_base=>$hash, hash_parent_base=>$parent,4851 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4852"diff") .4853" | ";4854}4855print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4856 hash_base=>$parent, file_name=>$diff->{'to_file'})},4857"blob") ." | ";4858if($have_blame) {4859print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4860 file_name=>$diff->{'to_file'})},4861"blame") ." | ";4862}4863print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4864 file_name=>$diff->{'to_file'})},4865"history");4866print"</td>\n";48674868}# we should not encounter Unmerged (U) or Unknown (X) status4869print"</tr>\n";4870}4871print"</tbody>"if$has_header;4872print"</table>\n";4873}48744875sub print_sidebyside_diff_chunk {4876my@chunk=@_;4877my(@ctx,@rem,@add);48784879return unless@chunk;48804881# incomplete last line might be among removed or added lines,4882# or both, or among context lines: find which4883for(my$i=1;$i<@chunk;$i++) {4884if($chunk[$i][0]eq'incomplete') {4885$chunk[$i][0] =$chunk[$i-1][0];4886}4887}48884889# guardian4890push@chunk, ["",""];48914892foreachmy$line_info(@chunk) {4893my($class,$line) =@$line_info;48944895# print chunk headers4896if($class&&$classeq'chunk_header') {4897print$line;4898next;4899}49004901## print from accumulator when type of class of lines change4902# empty contents block on start rem/add block, or end of chunk4903if(@ctx&& (!$class||$classeq'rem'||$classeq'add')) {4904print join'',4905'<div class="chunk_block ctx">',4906'<div class="old">',4907@ctx,4908'</div>',4909'<div class="new">',4910@ctx,4911'</div>',4912'</div>';4913@ctx= ();4914}4915# empty add/rem block on start context block, or end of chunk4916if((@rem||@add) && (!$class||$classeq'ctx')) {4917if(!@add) {4918# pure removal4919print join'',4920'<div class="chunk_block rem">',4921'<div class="old">',4922@rem,4923'</div>',4924'</div>';4925}elsif(!@rem) {4926# pure addition4927print join'',4928'<div class="chunk_block add">',4929'<div class="new">',4930@add,4931'</div>',4932'</div>';4933}else{4934# assume that it is change4935print join'',4936'<div class="chunk_block chg">',4937'<div class="old">',4938@rem,4939'</div>',4940'<div class="new">',4941@add,4942'</div>',4943'</div>';4944}4945@rem=@add= ();4946}49474948## adding lines to accumulator4949# guardian value4950last unless$line;4951# rem, add or change4952if($classeq'rem') {4953push@rem,$line;4954}elsif($classeq'add') {4955push@add,$line;4956}4957# context line4958if($classeq'ctx') {4959push@ctx,$line;4960}4961}4962}49634964sub git_patchset_body {4965my($fd,$diff_style,$difftree,$hash,@hash_parents) =@_;4966my($hash_parent) =$hash_parents[0];49674968my$is_combined= (@hash_parents>1);4969my$patch_idx=0;4970my$patch_number=0;4971my$patch_line;4972my$diffinfo;4973my$to_name;4974my(%from,%to);4975my@chunk;# for side-by-side diff49764977print"<div class=\"patchset\">\n";49784979# skip to first patch4980while($patch_line= <$fd>) {4981chomp$patch_line;49824983last if($patch_line=~m/^diff /);4984}49854986 PATCH:4987while($patch_line) {49884989# parse "git diff" header line4990if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4991# $1 is from_name, which we do not use4992$to_name= unquote($2);4993$to_name=~s!^b/!!;4994}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4995# $1 is 'cc' or 'combined', which we do not use4996$to_name= unquote($2);4997}else{4998$to_name=undef;4999}50005001# check if current patch belong to current raw line5002# and parse raw git-diff line if needed5003if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {5004# this is continuation of a split patch5005print"<div class=\"patch cont\">\n";5006}else{5007# advance raw git-diff output if needed5008$patch_idx++ifdefined$diffinfo;50095010# read and prepare patch information5011$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);50125013# compact combined diff output can have some patches skipped5014# find which patch (using pathname of result) we are at now;5015if($is_combined) {5016while($to_namene$diffinfo->{'to_file'}) {5017print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5018 format_diff_cc_simplified($diffinfo,@hash_parents) .5019"</div>\n";# class="patch"50205021$patch_idx++;5022$patch_number++;50235024last if$patch_idx>$#$difftree;5025$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);5026}5027}50285029# modifies %from, %to hashes5030 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);50315032# this is first patch for raw difftree line with $patch_idx index5033# we index @$difftree array from 0, but number patches from 15034print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";5035}50365037# git diff header5038#assert($patch_line =~ m/^diff /) if DEBUG;5039#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed5040$patch_number++;5041# print "git diff" header5042print format_git_diff_header_line($patch_line,$diffinfo,5043 \%from, \%to);50445045# print extended diff header5046print"<div class=\"diff extended_header\">\n";5047 EXTENDED_HEADER:5048while($patch_line= <$fd>) {5049chomp$patch_line;50505051last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);50525053print format_extended_diff_header_line($patch_line,$diffinfo,5054 \%from, \%to);5055}5056print"</div>\n";# class="diff extended_header"50575058# from-file/to-file diff header5059if(!$patch_line) {5060print"</div>\n";# class="patch"5061last PATCH;5062}5063next PATCH if($patch_line=~m/^diff /);5064#assert($patch_line =~ m/^---/) if DEBUG;50655066my$last_patch_line=$patch_line;5067$patch_line= <$fd>;5068chomp$patch_line;5069#assert($patch_line =~ m/^\+\+\+/) if DEBUG;50705071print format_diff_from_to_header($last_patch_line,$patch_line,5072$diffinfo, \%from, \%to,5073@hash_parents);50745075# the patch itself5076 LINE:5077while($patch_line= <$fd>) {5078chomp$patch_line;50795080next PATCH if($patch_line=~m/^diff /);50815082my($class,$line) = process_diff_line($patch_line, \%from, \%to);5083my$diff_classes="diff";5084$diff_classes.="$class"if($class);5085$line="<div class=\"$diff_classes\">$line</div>\n";50865087if($diff_styleeq'sidebyside'&& !$is_combined) {5088if($classeq'chunk_header') {5089 print_sidebyside_diff_chunk(@chunk);5090@chunk= ( [$class,$line] );5091}else{5092push@chunk, [$class,$line];5093}5094}else{5095# default 'inline' style and unknown styles5096print$line;5097}5098}50995100}continue{5101if(@chunk) {5102 print_sidebyside_diff_chunk(@chunk);5103@chunk= ();5104}5105print"</div>\n";# class="patch"5106}51075108# for compact combined (--cc) format, with chunk and patch simplification5109# the patchset might be empty, but there might be unprocessed raw lines5110for(++$patch_idxif$patch_number>0;5111$patch_idx<@$difftree;5112++$patch_idx) {5113# read and prepare patch information5114$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);51155116# generate anchor for "patch" links in difftree / whatchanged part5117print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5118 format_diff_cc_simplified($diffinfo,@hash_parents) .5119"</div>\n";# class="patch"51205121$patch_number++;5122}51235124if($patch_number==0) {5125if(@hash_parents>1) {5126print"<div class=\"diff nodifferences\">Trivial merge</div>\n";5127}else{5128print"<div class=\"diff nodifferences\">No differences found</div>\n";5129}5130}51315132print"</div>\n";# class="patchset"5133}51345135# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .51365137# fills project list info (age, description, owner, category, forks)5138# for each project in the list, removing invalid projects from5139# returned list5140# NOTE: modifies $projlist, but does not remove entries from it5141sub fill_project_list_info {5142my$projlist=shift;5143my@projects;51445145my$show_ctags= gitweb_check_feature('ctags');5146 PROJECT:5147foreachmy$pr(@$projlist) {5148my(@activity) = git_get_last_activity($pr->{'path'});5149unless(@activity) {5150next PROJECT;5151}5152($pr->{'age'},$pr->{'age_string'}) =@activity;5153if(!defined$pr->{'descr'}) {5154my$descr= git_get_project_description($pr->{'path'}) ||"";5155$descr= to_utf8($descr);5156$pr->{'descr_long'} =$descr;5157$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);5158}5159if(!defined$pr->{'owner'}) {5160$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";5161}5162if($show_ctags) {5163$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});5164}5165if($projects_list_group_categories&& !defined$pr->{'category'}) {5166my$cat= git_get_project_category($pr->{'path'}) ||5167$project_list_default_category;5168$pr->{'category'} = to_utf8($cat);5169}51705171push@projects,$pr;5172}51735174return@projects;5175}51765177sub sort_projects_list {5178my($projlist,$order) =@_;5179my@projects;51805181my%order_info= (5182 project => { key =>'path', type =>'str'},5183 descr => { key =>'descr_long', type =>'str'},5184 owner => { key =>'owner', type =>'str'},5185 age => { key =>'age', type =>'num'}5186);5187my$oi=$order_info{$order};5188return@$projlistunlessdefined$oi;5189if($oi->{'type'}eq'str') {5190@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@$projlist;5191}else{5192@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@$projlist;5193}51945195return@projects;5196}51975198# returns a hash of categories, containing the list of project5199# belonging to each category5200sub build_projlist_by_category {5201my($projlist,$from,$to) =@_;5202my%categories;52035204$from=0unlessdefined$from;5205$to=$#$projlistif(!defined$to||$#$projlist<$to);52065207for(my$i=$from;$i<=$to;$i++) {5208my$pr=$projlist->[$i];5209push@{$categories{$pr->{'category'} }},$pr;5210}52115212returnwantarray?%categories: \%categories;5213}52145215# print 'sort by' <th> element, generating 'sort by $name' replay link5216# if that order is not selected5217sub print_sort_th {5218print format_sort_th(@_);5219}52205221sub format_sort_th {5222my($name,$order,$header) =@_;5223my$sort_th="";5224$header||=ucfirst($name);52255226if($ordereq$name) {5227$sort_th.="<th>$header</th>\n";5228}else{5229$sort_th.="<th>".5230$cgi->a({-href => href(-replay=>1, order=>$name),5231-class=>"header"},$header) .5232"</th>\n";5233}52345235return$sort_th;5236}52375238sub git_project_list_rows {5239my($projlist,$from,$to,$check_forks) =@_;52405241$from=0unlessdefined$from;5242$to=$#$projlistif(!defined$to||$#$projlist<$to);52435244my$alternate=1;5245for(my$i=$from;$i<=$to;$i++) {5246my$pr=$projlist->[$i];52475248if($alternate) {5249print"<tr class=\"dark\">\n";5250}else{5251print"<tr class=\"light\">\n";5252}5253$alternate^=1;52545255if($check_forks) {5256print"<td>";5257if($pr->{'forks'}) {5258my$nforks=scalar@{$pr->{'forks'}};5259if($nforks>0) {5260print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5261-title =>"$nforksforks"},"+");5262}else{5263print$cgi->span({-title =>"$nforksforks"},"+");5264}5265}5266print"</td>\n";5267}5268print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5269-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".5270"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5271-class=>"list", -title =>$pr->{'descr_long'}},5272 esc_html($pr->{'descr'})) ."</td>\n".5273"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5274print"<td class=\"". age_class($pr->{'age'}) ."\">".5275(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".5276"<td class=\"link\">".5277$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5278$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5279$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5280$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5281($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5282"</td>\n".5283"</tr>\n";5284}5285}52865287sub git_project_list_body {5288# actually uses global variable $project5289my($projlist,$order,$from,$to,$extra,$no_header) =@_;5290my@projects=@$projlist;52915292my$check_forks= gitweb_check_feature('forks');5293my$show_ctags= gitweb_check_feature('ctags');5294my$tagfilter=$show_ctags?$input_params{'ctag'} :undef;5295$check_forks=undef5296if($tagfilter||$search_regexp);52975298# filtering out forks before filling info allows to do less work5299@projects= filter_forks_from_projects_list(\@projects)5300if($check_forks);5301@projects= fill_project_list_info(\@projects);5302# searching projects require filling to be run before it5303@projects= search_projects_list(\@projects,5304'search_regexp'=>$search_regexp,5305'tagfilter'=>$tagfilter)5306if($tagfilter||$search_regexp);53075308$order||=$default_projects_order;5309$from=0unlessdefined$from;5310$to=$#projectsif(!defined$to||$#projects<$to);53115312# short circuit5313if($from>$to) {5314print"<center>\n".5315"<b>No such projects found</b><br />\n".5316"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5317"</center>\n<br />\n";5318return;5319}53205321@projects= sort_projects_list(\@projects,$order);53225323if($show_ctags) {5324my$ctags= git_gather_all_ctags(\@projects);5325my$cloud= git_populate_project_tagcloud($ctags);5326print git_show_project_tagcloud($cloud,64);5327}53285329print"<table class=\"project_list\">\n";5330unless($no_header) {5331print"<tr>\n";5332if($check_forks) {5333print"<th></th>\n";5334}5335 print_sort_th('project',$order,'Project');5336 print_sort_th('descr',$order,'Description');5337 print_sort_th('owner',$order,'Owner');5338 print_sort_th('age',$order,'Last Change');5339print"<th></th>\n".# for links5340"</tr>\n";5341}53425343if($projects_list_group_categories) {5344# only display categories with projects in the $from-$to window5345@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5346my%categories= build_projlist_by_category(\@projects,$from,$to);5347foreachmy$cat(sort keys%categories) {5348unless($cateq"") {5349print"<tr>\n";5350if($check_forks) {5351print"<td></td>\n";5352}5353print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5354print"</tr>\n";5355}53565357 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5358}5359}else{5360 git_project_list_rows(\@projects,$from,$to,$check_forks);5361}53625363if(defined$extra) {5364print"<tr>\n";5365if($check_forks) {5366print"<td></td>\n";5367}5368print"<td colspan=\"5\">$extra</td>\n".5369"</tr>\n";5370}5371print"</table>\n";5372}53735374sub git_log_body {5375# uses global variable $project5376my($commitlist,$from,$to,$refs,$extra) =@_;53775378$from=0unlessdefined$from;5379$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);53805381for(my$i=0;$i<=$to;$i++) {5382my%co= %{$commitlist->[$i]};5383next if!%co;5384my$commit=$co{'id'};5385my$ref= format_ref_marker($refs,$commit);5386 git_print_header_div('commit',5387"<span class=\"age\">$co{'age_string'}</span>".5388 esc_html($co{'title'}) .$ref,5389$commit);5390print"<div class=\"title_text\">\n".5391"<div class=\"log_link\">\n".5392$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5393" | ".5394$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5395" | ".5396$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5397"<br/>\n".5398"</div>\n";5399 git_print_authorship(\%co, -tag =>'span');5400print"<br/>\n</div>\n";54015402print"<div class=\"log_body\">\n";5403 git_print_log($co{'comment'}, -final_empty_line=>1);5404print"</div>\n";5405}5406if($extra) {5407print"<div class=\"page_nav\">\n";5408print"$extra\n";5409print"</div>\n";5410}5411}54125413sub git_shortlog_body {5414# uses global variable $project5415my($commitlist,$from,$to,$refs,$extra) =@_;54165417$from=0unlessdefined$from;5418$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);54195420print"<table class=\"shortlog\">\n";5421my$alternate=1;5422for(my$i=$from;$i<=$to;$i++) {5423my%co= %{$commitlist->[$i]};5424my$commit=$co{'id'};5425my$ref= format_ref_marker($refs,$commit);5426if($alternate) {5427print"<tr class=\"dark\">\n";5428}else{5429print"<tr class=\"light\">\n";5430}5431$alternate^=1;5432# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5433print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5434 format_author_html('td', \%co,10) ."<td>";5435print format_subject_html($co{'title'},$co{'title_short'},5436 href(action=>"commit", hash=>$commit),$ref);5437print"</td>\n".5438"<td class=\"link\">".5439$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5440$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5441$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5442my$snapshot_links= format_snapshot_links($commit);5443if(defined$snapshot_links) {5444print" | ".$snapshot_links;5445}5446print"</td>\n".5447"</tr>\n";5448}5449if(defined$extra) {5450print"<tr>\n".5451"<td colspan=\"4\">$extra</td>\n".5452"</tr>\n";5453}5454print"</table>\n";5455}54565457sub git_history_body {5458# Warning: assumes constant type (blob or tree) during history5459my($commitlist,$from,$to,$refs,$extra,5460$file_name,$file_hash,$ftype) =@_;54615462$from=0unlessdefined$from;5463$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});54645465print"<table class=\"history\">\n";5466my$alternate=1;5467for(my$i=$from;$i<=$to;$i++) {5468my%co= %{$commitlist->[$i]};5469if(!%co) {5470next;5471}5472my$commit=$co{'id'};54735474my$ref= format_ref_marker($refs,$commit);54755476if($alternate) {5477print"<tr class=\"dark\">\n";5478}else{5479print"<tr class=\"light\">\n";5480}5481$alternate^=1;5482print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5483# shortlog: format_author_html('td', \%co, 10)5484 format_author_html('td', \%co,15,3) ."<td>";5485# originally git_history used chop_str($co{'title'}, 50)5486print format_subject_html($co{'title'},$co{'title_short'},5487 href(action=>"commit", hash=>$commit),$ref);5488print"</td>\n".5489"<td class=\"link\">".5490$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5491$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");54925493if($ftypeeq'blob') {5494my$blob_current=$file_hash;5495my$blob_parent= git_get_hash_by_path($commit,$file_name);5496if(defined$blob_current&&defined$blob_parent&&5497$blob_currentne$blob_parent) {5498print" | ".5499$cgi->a({-href => href(action=>"blobdiff",5500 hash=>$blob_current, hash_parent=>$blob_parent,5501 hash_base=>$hash_base, hash_parent_base=>$commit,5502 file_name=>$file_name)},5503"diff to current");5504}5505}5506print"</td>\n".5507"</tr>\n";5508}5509if(defined$extra) {5510print"<tr>\n".5511"<td colspan=\"4\">$extra</td>\n".5512"</tr>\n";5513}5514print"</table>\n";5515}55165517sub git_tags_body {5518# uses global variable $project5519my($taglist,$from,$to,$extra) =@_;5520$from=0unlessdefined$from;5521$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);55225523print"<table class=\"tags\">\n";5524my$alternate=1;5525for(my$i=$from;$i<=$to;$i++) {5526my$entry=$taglist->[$i];5527my%tag=%$entry;5528my$comment=$tag{'subject'};5529my$comment_short;5530if(defined$comment) {5531$comment_short= chop_str($comment,30,5);5532}5533if($alternate) {5534print"<tr class=\"dark\">\n";5535}else{5536print"<tr class=\"light\">\n";5537}5538$alternate^=1;5539if(defined$tag{'age'}) {5540print"<td><i>$tag{'age'}</i></td>\n";5541}else{5542print"<td></td>\n";5543}5544print"<td>".5545$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5546-class=>"list name"}, esc_html($tag{'name'})) .5547"</td>\n".5548"<td>";5549if(defined$comment) {5550print format_subject_html($comment,$comment_short,5551 href(action=>"tag", hash=>$tag{'id'}));5552}5553print"</td>\n".5554"<td class=\"selflink\">";5555if($tag{'type'}eq"tag") {5556print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");5557}else{5558print" ";5559}5560print"</td>\n".5561"<td class=\"link\">"." | ".5562$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});5563if($tag{'reftype'}eq"commit") {5564print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .5565" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");5566}elsif($tag{'reftype'}eq"blob") {5567print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");5568}5569print"</td>\n".5570"</tr>";5571}5572if(defined$extra) {5573print"<tr>\n".5574"<td colspan=\"5\">$extra</td>\n".5575"</tr>\n";5576}5577print"</table>\n";5578}55795580sub git_heads_body {5581# uses global variable $project5582my($headlist,$head_at,$from,$to,$extra) =@_;5583$from=0unlessdefined$from;5584$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);55855586print"<table class=\"heads\">\n";5587my$alternate=1;5588for(my$i=$from;$i<=$to;$i++) {5589my$entry=$headlist->[$i];5590my%ref=%$entry;5591my$curr=defined$head_at&&$ref{'id'}eq$head_at;5592if($alternate) {5593print"<tr class=\"dark\">\n";5594}else{5595print"<tr class=\"light\">\n";5596}5597$alternate^=1;5598print"<td><i>$ref{'age'}</i></td>\n".5599($curr?"<td class=\"current_head\">":"<td>") .5600$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),5601-class=>"list name"},esc_html($ref{'name'})) .5602"</td>\n".5603"<td class=\"link\">".5604$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".5605$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".5606$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .5607"</td>\n".5608"</tr>";5609}5610if(defined$extra) {5611print"<tr>\n".5612"<td colspan=\"3\">$extra</td>\n".5613"</tr>\n";5614}5615print"</table>\n";5616}56175618# Display a single remote block5619sub git_remote_block {5620my($remote,$rdata,$limit,$head) =@_;56215622my$heads=$rdata->{'heads'};5623my$fetch=$rdata->{'fetch'};5624my$push=$rdata->{'push'};56255626my$urls_table="<table class=\"projects_list\">\n";56275628if(defined$fetch) {5629if($fetcheq$push) {5630$urls_table.= format_repo_url("URL",$fetch);5631}else{5632$urls_table.= format_repo_url("Fetch URL",$fetch);5633$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;5634}5635}elsif(defined$push) {5636$urls_table.= format_repo_url("Push URL",$push);5637}else{5638$urls_table.= format_repo_url("","No remote URL");5639}56405641$urls_table.="</table>\n";56425643my$dots;5644if(defined$limit&&$limit<@$heads) {5645$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");5646}56475648print$urls_table;5649 git_heads_body($heads,$head,0,$limit,$dots);5650}56515652# Display a list of remote names with the respective fetch and push URLs5653sub git_remotes_list {5654my($remotedata,$limit) =@_;5655print"<table class=\"heads\">\n";5656my$alternate=1;5657my@remotes=sort keys%$remotedata;56585659my$limited=$limit&&$limit<@remotes;56605661$#remotes=$limit-1if$limited;56625663while(my$remote=shift@remotes) {5664my$rdata=$remotedata->{$remote};5665my$fetch=$rdata->{'fetch'};5666my$push=$rdata->{'push'};5667if($alternate) {5668print"<tr class=\"dark\">\n";5669}else{5670print"<tr class=\"light\">\n";5671}5672$alternate^=1;5673print"<td>".5674$cgi->a({-href=> href(action=>'remotes', hash=>$remote),5675-class=>"list name"},esc_html($remote)) .5676"</td>";5677print"<td class=\"link\">".5678(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .5679" | ".5680(defined$push?$cgi->a({-href=>$push},"push") :"push") .5681"</td>";56825683print"</tr>\n";5684}56855686if($limited) {5687print"<tr>\n".5688"<td colspan=\"3\">".5689$cgi->a({-href => href(action=>"remotes")},"...") .5690"</td>\n"."</tr>\n";5691}56925693print"</table>";5694}56955696# Display remote heads grouped by remote, unless there are too many5697# remotes, in which case we only display the remote names5698sub git_remotes_body {5699my($remotedata,$limit,$head) =@_;5700if($limitand$limit<keys%$remotedata) {5701 git_remotes_list($remotedata,$limit);5702}else{5703 fill_remote_heads($remotedata);5704while(my($remote,$rdata) =each%$remotedata) {5705 git_print_section({-class=>"remote", -id=>$remote},5706["remotes",$remote,$remote],sub{5707 git_remote_block($remote,$rdata,$limit,$head);5708});5709}5710}5711}57125713sub git_search_message {5714my%co=@_;57155716my$greptype;5717if($searchtypeeq'commit') {5718$greptype="--grep=";5719}elsif($searchtypeeq'author') {5720$greptype="--author=";5721}elsif($searchtypeeq'committer') {5722$greptype="--committer=";5723}5724$greptype.=$searchtext;5725my@commitlist= parse_commits($hash,101, (100*$page),undef,5726$greptype,'--regexp-ignore-case',5727$search_use_regexp?'--extended-regexp':'--fixed-strings');57285729my$paging_nav='';5730if($page>0) {5731$paging_nav.=5732$cgi->a({-href => href(-replay=>1, page=>undef)},5733"first") .5734" ⋅ ".5735$cgi->a({-href => href(-replay=>1, page=>$page-1),5736-accesskey =>"p", -title =>"Alt-p"},"prev");5737}else{5738$paging_nav.="first ⋅ prev";5739}5740my$next_link='';5741if($#commitlist>=100) {5742$next_link=5743$cgi->a({-href => href(-replay=>1, page=>$page+1),5744-accesskey =>"n", -title =>"Alt-n"},"next");5745$paging_nav.=" ⋅$next_link";5746}else{5747$paging_nav.=" ⋅ next";5748}57495750 git_header_html();57515752 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);5753 git_print_header_div('commit', esc_html($co{'title'}),$hash);5754if($page==0&& !@commitlist) {5755print"<p>No match.</p>\n";5756}else{5757 git_search_grep_body(\@commitlist,0,99,$next_link);5758}57595760 git_footer_html();5761}57625763sub git_search_changes {5764my%co=@_;57655766local$/="\n";5767open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,5768'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",5769($search_use_regexp?'--pickaxe-regex': ())5770or die_error(500,"Open git-log failed");57715772 git_header_html();57735774 git_print_page_nav('','',$hash,$co{'tree'},$hash);5775 git_print_header_div('commit', esc_html($co{'title'}),$hash);57765777print"<table class=\"pickaxe search\">\n";5778my$alternate=1;5779undef%co;5780my@files;5781while(my$line= <$fd>) {5782chomp$line;5783next unless$line;57845785my%set= parse_difftree_raw_line($line);5786if(defined$set{'commit'}) {5787# finish previous commit5788if(%co) {5789print"</td>\n".5790"<td class=\"link\">".5791$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},5792"commit") .5793" | ".5794$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},5795 hash_base=>$co{'id'})},5796"tree") .5797"</td>\n".5798"</tr>\n";5799}58005801if($alternate) {5802print"<tr class=\"dark\">\n";5803}else{5804print"<tr class=\"light\">\n";5805}5806$alternate^=1;5807%co= parse_commit($set{'commit'});5808my$author= chop_and_escape_str($co{'author_name'},15,5);5809print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5810"<td><i>$author</i></td>\n".5811"<td>".5812$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5813-class=>"list subject"},5814 chop_and_escape_str($co{'title'},50) ."<br/>");5815}elsif(defined$set{'to_id'}) {5816next if($set{'to_id'} =~m/^0{40}$/);58175818print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},5819 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),5820-class=>"list"},5821"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .5822"<br/>\n";5823}5824}5825close$fd;58265827# finish last commit (warning: repetition!)5828if(%co) {5829print"</td>\n".5830"<td class=\"link\">".5831$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},5832"commit") .5833" | ".5834$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},5835 hash_base=>$co{'id'})},5836"tree") .5837"</td>\n".5838"</tr>\n";5839}58405841print"</table>\n";58425843 git_footer_html();5844}58455846sub git_search_files {5847my%co=@_;58485849local$/="\n";5850open my$fd,"-|", git_cmd(),'grep','-n','-z',5851$search_use_regexp? ('-E','-i') :'-F',5852$searchtext,$co{'tree'}5853or die_error(500,"Open git-grep failed");58545855 git_header_html();58565857 git_print_page_nav('','',$hash,$co{'tree'},$hash);5858 git_print_header_div('commit', esc_html($co{'title'}),$hash);58595860print"<table class=\"grep_search\">\n";5861my$alternate=1;5862my$matches=0;5863my$lastfile='';5864my$file_href;5865while(my$line= <$fd>) {5866chomp$line;5867my($file,$lno,$ltext,$binary);5868last if($matches++>1000);5869if($line=~/^Binary file (.+) matches$/) {5870$file=$1;5871$binary=1;5872}else{5873($file,$lno,$ltext) =split(/\0/,$line,3);5874$file=~s/^$co{'tree'}://;5875}5876if($filene$lastfile) {5877$lastfileand print"</td></tr>\n";5878if($alternate++) {5879print"<tr class=\"dark\">\n";5880}else{5881print"<tr class=\"light\">\n";5882}5883$file_href= href(action=>"blob", hash_base=>$co{'id'},5884 file_name=>$file);5885print"<td class=\"list\">".5886$cgi->a({-href =>$file_href, -class=>"list"}, esc_path($file));5887print"</td><td>\n";5888$lastfile=$file;5889}5890if($binary) {5891print"<div class=\"binary\">Binary file</div>\n";5892}else{5893$ltext= untabify($ltext);5894if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {5895$ltext= esc_html($1, -nbsp=>1);5896$ltext.='<span class="match">';5897$ltext.= esc_html($2, -nbsp=>1);5898$ltext.='</span>';5899$ltext.= esc_html($3, -nbsp=>1);5900}else{5901$ltext= esc_html($ltext, -nbsp=>1);5902}5903print"<div class=\"pre\">".5904$cgi->a({-href =>$file_href.'#l'.$lno,5905-class=>"linenr"},sprintf('%4i',$lno)) .5906' '.$ltext."</div>\n";5907}5908}5909if($lastfile) {5910print"</td></tr>\n";5911if($matches>1000) {5912print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";5913}5914}else{5915print"<div class=\"diff nodifferences\">No matches found</div>\n";5916}5917close$fd;59185919print"</table>\n";59205921 git_footer_html();5922}59235924sub git_search_grep_body {5925my($commitlist,$from,$to,$extra) =@_;5926$from=0unlessdefined$from;5927$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);59285929print"<table class=\"commit_search\">\n";5930my$alternate=1;5931for(my$i=$from;$i<=$to;$i++) {5932my%co= %{$commitlist->[$i]};5933if(!%co) {5934next;5935}5936my$commit=$co{'id'};5937if($alternate) {5938print"<tr class=\"dark\">\n";5939}else{5940print"<tr class=\"light\">\n";5941}5942$alternate^=1;5943print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5944 format_author_html('td', \%co,15,5) .5945"<td>".5946$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5947-class=>"list subject"},5948 chop_and_escape_str($co{'title'},50) ."<br/>");5949my$comment=$co{'comment'};5950foreachmy$line(@$comment) {5951if($line=~m/^(.*?)($search_regexp)(.*)$/i) {5952my($lead,$match,$trail) = ($1,$2,$3);5953$match= chop_str($match,70,5,'center');5954my$contextlen=int((80-length($match))/2);5955$contextlen=30if($contextlen>30);5956$lead= chop_str($lead,$contextlen,10,'left');5957$trail= chop_str($trail,$contextlen,10,'right');59585959$lead= esc_html($lead);5960$match= esc_html($match);5961$trail= esc_html($trail);59625963print"$lead<span class=\"match\">$match</span>$trail<br />";5964}5965}5966print"</td>\n".5967"<td class=\"link\">".5968$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .5969" | ".5970$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .5971" | ".5972$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");5973print"</td>\n".5974"</tr>\n";5975}5976if(defined$extra) {5977print"<tr>\n".5978"<td colspan=\"3\">$extra</td>\n".5979"</tr>\n";5980}5981print"</table>\n";5982}59835984## ======================================================================5985## ======================================================================5986## actions59875988sub git_project_list {5989my$order=$input_params{'order'};5990if(defined$order&&$order!~m/none|project|descr|owner|age/) {5991 die_error(400,"Unknown order parameter");5992}59935994my@list= git_get_projects_list();5995if(!@list) {5996 die_error(404,"No projects found");5997}59985999 git_header_html();6000if(defined$home_text&& -f $home_text) {6001print"<div class=\"index_include\">\n";6002 insert_file($home_text);6003print"</div>\n";6004}6005print$cgi->startform(-method=>"get") .6006"<p class=\"projsearch\">Search:\n".6007$cgi->textfield(-name =>"s", -value =>$searchtext, -override =>1) ."\n".6008"</p>".6009$cgi->end_form() ."\n";6010 git_project_list_body(\@list,$order);6011 git_footer_html();6012}60136014sub git_forks {6015my$order=$input_params{'order'};6016if(defined$order&&$order!~m/none|project|descr|owner|age/) {6017 die_error(400,"Unknown order parameter");6018}60196020my@list= git_get_projects_list($project);6021if(!@list) {6022 die_error(404,"No forks found");6023}60246025 git_header_html();6026 git_print_page_nav('','');6027 git_print_header_div('summary',"$projectforks");6028 git_project_list_body(\@list,$order);6029 git_footer_html();6030}60316032sub git_project_index {6033my@projects= git_get_projects_list();6034if(!@projects) {6035 die_error(404,"No projects found");6036}60376038print$cgi->header(6039-type =>'text/plain',6040-charset =>'utf-8',6041-content_disposition =>'inline; filename="index.aux"');60426043foreachmy$pr(@projects) {6044if(!exists$pr->{'owner'}) {6045$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");6046}60476048my($path,$owner) = ($pr->{'path'},$pr->{'owner'});6049# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '6050$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6051$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6052$path=~s/ /\+/g;6053$owner=~s/ /\+/g;60546055print"$path$owner\n";6056}6057}60586059sub git_summary {6060my$descr= git_get_project_description($project) ||"none";6061my%co= parse_commit("HEAD");6062my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();6063my$head=$co{'id'};6064my$remote_heads= gitweb_check_feature('remote_heads');60656066my$owner= git_get_project_owner($project);60676068my$refs= git_get_references();6069# These get_*_list functions return one more to allow us to see if6070# there are more ...6071my@taglist= git_get_tags_list(16);6072my@headlist= git_get_heads_list(16);6073my%remotedata=$remote_heads? git_get_remotes_list() : ();6074my@forklist;6075my$check_forks= gitweb_check_feature('forks');60766077if($check_forks) {6078# find forks of a project6079@forklist= git_get_projects_list($project);6080# filter out forks of forks6081@forklist= filter_forks_from_projects_list(\@forklist)6082if(@forklist);6083}60846085 git_header_html();6086 git_print_page_nav('summary','',$head);60876088print"<div class=\"title\"> </div>\n";6089print"<table class=\"projects_list\">\n".6090"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".6091"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";6092if(defined$cd{'rfc2822'}) {6093print"<tr id=\"metadata_lchange\"><td>last change</td>".6094"<td>".format_timestamp_html(\%cd)."</td></tr>\n";6095}60966097# use per project git URL list in $projectroot/$project/cloneurl6098# or make project git URL from git base URL and project name6099my$url_tag="URL";6100my@url_list= git_get_project_url_list($project);6101@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;6102foreachmy$git_url(@url_list) {6103next unless$git_url;6104print format_repo_url($url_tag,$git_url);6105$url_tag="";6106}61076108# Tag cloud6109my$show_ctags= gitweb_check_feature('ctags');6110if($show_ctags) {6111my$ctags= git_get_project_ctags($project);6112if(%$ctags) {6113# without ability to add tags, don't show if there are none6114my$cloud= git_populate_project_tagcloud($ctags);6115print"<tr id=\"metadata_ctags\">".6116"<td>content tags</td>".6117"<td>".git_show_project_tagcloud($cloud,48)."</td>".6118"</tr>\n";6119}6120}61216122print"</table>\n";61236124# If XSS prevention is on, we don't include README.html.6125# TODO: Allow a readme in some safe format.6126if(!$prevent_xss&& -s "$projectroot/$project/README.html") {6127print"<div class=\"title\">readme</div>\n".6128"<div class=\"readme\">\n";6129 insert_file("$projectroot/$project/README.html");6130print"\n</div>\n";# class="readme"6131}61326133# we need to request one more than 16 (0..15) to check if6134# those 16 are all6135my@commitlist=$head? parse_commits($head,17) : ();6136if(@commitlist) {6137 git_print_header_div('shortlog');6138 git_shortlog_body(\@commitlist,0,15,$refs,6139$#commitlist<=15?undef:6140$cgi->a({-href => href(action=>"shortlog")},"..."));6141}61426143if(@taglist) {6144 git_print_header_div('tags');6145 git_tags_body(\@taglist,0,15,6146$#taglist<=15?undef:6147$cgi->a({-href => href(action=>"tags")},"..."));6148}61496150if(@headlist) {6151 git_print_header_div('heads');6152 git_heads_body(\@headlist,$head,0,15,6153$#headlist<=15?undef:6154$cgi->a({-href => href(action=>"heads")},"..."));6155}61566157if(%remotedata) {6158 git_print_header_div('remotes');6159 git_remotes_body(\%remotedata,15,$head);6160}61616162if(@forklist) {6163 git_print_header_div('forks');6164 git_project_list_body(\@forklist,'age',0,15,6165$#forklist<=15?undef:6166$cgi->a({-href => href(action=>"forks")},"..."),6167'no_header');6168}61696170 git_footer_html();6171}61726173sub git_tag {6174my%tag= parse_tag($hash);61756176if(!%tag) {6177 die_error(404,"Unknown tag object");6178}61796180my$head= git_get_head_hash($project);6181 git_header_html();6182 git_print_page_nav('','',$head,undef,$head);6183 git_print_header_div('commit', esc_html($tag{'name'}),$hash);6184print"<div class=\"title_text\">\n".6185"<table class=\"object_header\">\n".6186"<tr>\n".6187"<td>object</td>\n".6188"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6189$tag{'object'}) ."</td>\n".6190"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6191$tag{'type'}) ."</td>\n".6192"</tr>\n";6193if(defined($tag{'author'})) {6194 git_print_authorship_rows(\%tag,'author');6195}6196print"</table>\n\n".6197"</div>\n";6198print"<div class=\"page_body\">";6199my$comment=$tag{'comment'};6200foreachmy$line(@$comment) {6201chomp$line;6202print esc_html($line, -nbsp=>1) ."<br/>\n";6203}6204print"</div>\n";6205 git_footer_html();6206}62076208sub git_blame_common {6209my$format=shift||'porcelain';6210if($formateq'porcelain'&&$input_params{'javascript'}) {6211$format='incremental';6212$action='blame_incremental';# for page title etc6213}62146215# permissions6216 gitweb_check_feature('blame')6217or die_error(403,"Blame view not allowed");62186219# error checking6220 die_error(400,"No file name given")unless$file_name;6221$hash_base||= git_get_head_hash($project);6222 die_error(404,"Couldn't find base commit")unless$hash_base;6223my%co= parse_commit($hash_base)6224or die_error(404,"Commit not found");6225my$ftype="blob";6226if(!defined$hash) {6227$hash= git_get_hash_by_path($hash_base,$file_name,"blob")6228or die_error(404,"Error looking up file");6229}else{6230$ftype= git_get_type($hash);6231if($ftype!~"blob") {6232 die_error(400,"Object is not a blob");6233}6234}62356236my$fd;6237if($formateq'incremental') {6238# get file contents (as base)6239open$fd,"-|", git_cmd(),'cat-file','blob',$hash6240or die_error(500,"Open git-cat-file failed");6241}elsif($formateq'data') {6242# run git-blame --incremental6243open$fd,"-|", git_cmd(),"blame","--incremental",6244$hash_base,"--",$file_name6245or die_error(500,"Open git-blame --incremental failed");6246}else{6247# run git-blame --porcelain6248open$fd,"-|", git_cmd(),"blame",'-p',6249$hash_base,'--',$file_name6250or die_error(500,"Open git-blame --porcelain failed");6251}62526253# incremental blame data returns early6254if($formateq'data') {6255print$cgi->header(6256-type=>"text/plain", -charset =>"utf-8",6257-status=>"200 OK");6258local$| =1;# output autoflush6259while(my$line= <$fd>) {6260print to_utf8($line);6261}6262close$fd6263or print"ERROR$!\n";62646265print'END';6266if(defined$t0&& gitweb_check_feature('timed')) {6267print' '.6268 tv_interval($t0, [ gettimeofday() ]).6269' '.$number_of_git_cmds;6270}6271print"\n";62726273return;6274}62756276# page header6277 git_header_html();6278my$formats_nav=6279$cgi->a({-href => href(action=>"blob", -replay=>1)},6280"blob") .6281" | ";6282if($formateq'incremental') {6283$formats_nav.=6284$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},6285"blame") ." (non-incremental)";6286}else{6287$formats_nav.=6288$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},6289"blame") ." (incremental)";6290}6291$formats_nav.=6292" | ".6293$cgi->a({-href => href(action=>"history", -replay=>1)},6294"history") .6295" | ".6296$cgi->a({-href => href(action=>$action, file_name=>$file_name)},6297"HEAD");6298 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6299 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6300 git_print_page_path($file_name,$ftype,$hash_base);63016302# page body6303if($formateq'incremental') {6304print"<noscript>\n<div class=\"error\"><center><b>\n".6305"This page requires JavaScript to run.\nUse ".6306$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},6307'this page').6308" instead.\n".6309"</b></center></div>\n</noscript>\n";63106311print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;6312}63136314print qq!<div class="page_body">\n!;6315print qq!<div id="progress_info">.../ ...</div>\n!6316if($formateq'incremental');6317print qq!<table id="blame_table"class="blame" width="100%">\n!.6318#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.6319 qq!<thead>\n!.6320 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.6321 qq!</thead>\n!.6322 qq!<tbody>\n!;63236324my@rev_color=qw(light dark);6325my$num_colors=scalar(@rev_color);6326my$current_color=0;63276328if($formateq'incremental') {6329my$color_class=$rev_color[$current_color];63306331#contents of a file6332my$linenr=0;6333 LINE:6334while(my$line= <$fd>) {6335chomp$line;6336$linenr++;63376338print qq!<tr id="l$linenr"class="$color_class">!.6339 qq!<td class="sha1"><a href=""> </a></td>!.6340 qq!<td class="linenr">!.6341 qq!<a class="linenr" href="">$linenr</a></td>!;6342print qq!<td class="pre">! . esc_html($line) ."</td>\n";6343print qq!</tr>\n!;6344}63456346}else{# porcelain, i.e. ordinary blame6347my%metainfo= ();# saves information about commits63486349# blame data6350 LINE:6351while(my$line= <$fd>) {6352chomp$line;6353# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]6354# no <lines in group> for subsequent lines in group of lines6355my($full_rev,$orig_lineno,$lineno,$group_size) =6356($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);6357if(!exists$metainfo{$full_rev}) {6358$metainfo{$full_rev} = {'nprevious'=>0};6359}6360my$meta=$metainfo{$full_rev};6361my$data;6362while($data= <$fd>) {6363chomp$data;6364last if($data=~s/^\t//);# contents of line6365if($data=~/^(\S+)(?: (.*))?$/) {6366$meta->{$1} =$2unlessexists$meta->{$1};6367}6368if($data=~/^previous /) {6369$meta->{'nprevious'}++;6370}6371}6372my$short_rev=substr($full_rev,0,8);6373my$author=$meta->{'author'};6374my%date=6375 parse_date($meta->{'author-time'},$meta->{'author-tz'});6376my$date=$date{'iso-tz'};6377if($group_size) {6378$current_color= ($current_color+1) %$num_colors;6379}6380my$tr_class=$rev_color[$current_color];6381$tr_class.=' boundary'if(exists$meta->{'boundary'});6382$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);6383$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);6384print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";6385if($group_size) {6386print"<td class=\"sha1\"";6387print" title=\"". esc_html($author) .",$date\"";6388print" rowspan=\"$group_size\""if($group_size>1);6389print">";6390print$cgi->a({-href => href(action=>"commit",6391 hash=>$full_rev,6392 file_name=>$file_name)},6393 esc_html($short_rev));6394if($group_size>=2) {6395my@author_initials= ($author=~/\b([[:upper:]])\B/g);6396if(@author_initials) {6397print"<br />".6398 esc_html(join('',@author_initials));6399# or join('.', ...)6400}6401}6402print"</td>\n";6403}6404# 'previous' <sha1 of parent commit> <filename at commit>6405if(exists$meta->{'previous'} &&6406$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {6407$meta->{'parent'} =$1;6408$meta->{'file_parent'} = unquote($2);6409}6410my$linenr_commit=6411exists($meta->{'parent'}) ?6412$meta->{'parent'} :$full_rev;6413my$linenr_filename=6414exists($meta->{'file_parent'}) ?6415$meta->{'file_parent'} : unquote($meta->{'filename'});6416my$blamed= href(action =>'blame',6417 file_name =>$linenr_filename,6418 hash_base =>$linenr_commit);6419print"<td class=\"linenr\">";6420print$cgi->a({ -href =>"$blamed#l$orig_lineno",6421-class=>"linenr"},6422 esc_html($lineno));6423print"</td>";6424print"<td class=\"pre\">". esc_html($data) ."</td>\n";6425print"</tr>\n";6426}# end while64276428}64296430# footer6431print"</tbody>\n".6432"</table>\n";# class="blame"6433print"</div>\n";# class="blame_body"6434close$fd6435or print"Reading blob failed\n";64366437 git_footer_html();6438}64396440sub git_blame {6441 git_blame_common();6442}64436444sub git_blame_incremental {6445 git_blame_common('incremental');6446}64476448sub git_blame_data {6449 git_blame_common('data');6450}64516452sub git_tags {6453my$head= git_get_head_hash($project);6454 git_header_html();6455 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6456 git_print_header_div('summary',$project);64576458my@tagslist= git_get_tags_list();6459if(@tagslist) {6460 git_tags_body(\@tagslist);6461}6462 git_footer_html();6463}64646465sub git_heads {6466my$head= git_get_head_hash($project);6467 git_header_html();6468 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6469 git_print_header_div('summary',$project);64706471my@headslist= git_get_heads_list();6472if(@headslist) {6473 git_heads_body(\@headslist,$head);6474}6475 git_footer_html();6476}64776478# used both for single remote view and for list of all the remotes6479sub git_remotes {6480 gitweb_check_feature('remote_heads')6481or die_error(403,"Remote heads view is disabled");64826483my$head= git_get_head_hash($project);6484my$remote=$input_params{'hash'};64856486my$remotedata= git_get_remotes_list($remote);6487 die_error(500,"Unable to get remote information")unlessdefined$remotedata;64886489unless(%$remotedata) {6490 die_error(404,defined$remote?6491"Remote$remotenot found":6492"No remotes found");6493}64946495 git_header_html(undef,undef, -action_extra =>$remote);6496 git_print_page_nav('','',$head,undef,$head,6497 format_ref_views($remote?'':'remotes'));64986499 fill_remote_heads($remotedata);6500if(defined$remote) {6501 git_print_header_div('remotes',"$remoteremote for$project");6502 git_remote_block($remote,$remotedata->{$remote},undef,$head);6503}else{6504 git_print_header_div('summary',"$projectremotes");6505 git_remotes_body($remotedata,undef,$head);6506}65076508 git_footer_html();6509}65106511sub git_blob_plain {6512my$type=shift;6513my$expires;65146515if(!defined$hash) {6516if(defined$file_name) {6517my$base=$hash_base|| git_get_head_hash($project);6518$hash= git_get_hash_by_path($base,$file_name,"blob")6519or die_error(404,"Cannot find file");6520}else{6521 die_error(400,"No file name defined");6522}6523}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6524# blobs defined by non-textual hash id's can be cached6525$expires="+1d";6526}65276528open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6529or die_error(500,"Open git-cat-file blob '$hash' failed");65306531# content-type (can include charset)6532$type= blob_contenttype($fd,$file_name,$type);65336534# "save as" filename, even when no $file_name is given6535my$save_as="$hash";6536if(defined$file_name) {6537$save_as=$file_name;6538}elsif($type=~m/^text\//) {6539$save_as.='.txt';6540}65416542# With XSS prevention on, blobs of all types except a few known safe6543# ones are served with "Content-Disposition: attachment" to make sure6544# they don't run in our security domain. For certain image types,6545# blob view writes an <img> tag referring to blob_plain view, and we6546# want to be sure not to break that by serving the image as an6547# attachment (though Firefox 3 doesn't seem to care).6548my$sandbox=$prevent_xss&&6549$type!~m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;65506551# serve text/* as text/plain6552if($prevent_xss&&6553($type=~m!^text/[a-z]+\b(.*)$!||6554($type=~m!^[a-z]+/[a-z]\+xml\b(.*)$!&& -T $fd))) {6555my$rest=$1;6556$rest=defined$rest?$rest:'';6557$type="text/plain$rest";6558}65596560print$cgi->header(6561-type =>$type,6562-expires =>$expires,6563-content_disposition =>6564($sandbox?'attachment':'inline')6565.'; filename="'.$save_as.'"');6566local$/=undef;6567binmode STDOUT,':raw';6568print<$fd>;6569binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6570close$fd;6571}65726573sub git_blob {6574my$expires;65756576if(!defined$hash) {6577if(defined$file_name) {6578my$base=$hash_base|| git_get_head_hash($project);6579$hash= git_get_hash_by_path($base,$file_name,"blob")6580or die_error(404,"Cannot find file");6581}else{6582 die_error(400,"No file name defined");6583}6584}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6585# blobs defined by non-textual hash id's can be cached6586$expires="+1d";6587}65886589my$have_blame= gitweb_check_feature('blame');6590open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6591or die_error(500,"Couldn't cat$file_name,$hash");6592my$mimetype= blob_mimetype($fd,$file_name);6593# use 'blob_plain' (aka 'raw') view for files that cannot be displayed6594if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {6595close$fd;6596return git_blob_plain($mimetype);6597}6598# we can have blame only for text/* mimetype6599$have_blame&&= ($mimetype=~m!^text/!);66006601my$highlight= gitweb_check_feature('highlight');6602my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);6603$fd= run_highlighter($fd,$highlight,$syntax)6604if$syntax;66056606 git_header_html(undef,$expires);6607my$formats_nav='';6608if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6609if(defined$file_name) {6610if($have_blame) {6611$formats_nav.=6612$cgi->a({-href => href(action=>"blame", -replay=>1)},6613"blame") .6614" | ";6615}6616$formats_nav.=6617$cgi->a({-href => href(action=>"history", -replay=>1)},6618"history") .6619" | ".6620$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6621"raw") .6622" | ".6623$cgi->a({-href => href(action=>"blob",6624 hash_base=>"HEAD", file_name=>$file_name)},6625"HEAD");6626}else{6627$formats_nav.=6628$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6629"raw");6630}6631 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6632 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6633}else{6634print"<div class=\"page_nav\">\n".6635"<br/><br/></div>\n".6636"<div class=\"title\">".esc_html($hash)."</div>\n";6637}6638 git_print_page_path($file_name,"blob",$hash_base);6639print"<div class=\"page_body\">\n";6640if($mimetype=~m!^image/!) {6641print qq!<img type="!.esc_attr($mimetype).qq!"!;6642if($file_name) {6643print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;6644}6645print qq! src="! .6646 href(action=>"blob_plain", hash=>$hash,6647 hash_base=>$hash_base, file_name=>$file_name) .6648 qq!"/>\n!;6649}else{6650my$nr;6651while(my$line= <$fd>) {6652chomp$line;6653$nr++;6654$line= untabify($line);6655printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,6656$nr, esc_attr(href(-replay =>1)),$nr,$nr,6657$syntax? sanitize($line) : esc_html($line, -nbsp=>1);6658}6659}6660close$fd6661or print"Reading blob failed.\n";6662print"</div>";6663 git_footer_html();6664}66656666sub git_tree {6667if(!defined$hash_base) {6668$hash_base="HEAD";6669}6670if(!defined$hash) {6671if(defined$file_name) {6672$hash= git_get_hash_by_path($hash_base,$file_name,"tree");6673}else{6674$hash=$hash_base;6675}6676}6677 die_error(404,"No such tree")unlessdefined($hash);66786679my$show_sizes= gitweb_check_feature('show-sizes');6680my$have_blame= gitweb_check_feature('blame');66816682my@entries= ();6683{6684local$/="\0";6685open my$fd,"-|", git_cmd(),"ls-tree",'-z',6686($show_sizes?'-l': ()),@extra_options,$hash6687or die_error(500,"Open git-ls-tree failed");6688@entries=map{chomp;$_} <$fd>;6689close$fd6690or die_error(404,"Reading tree failed");6691}66926693my$refs= git_get_references();6694my$ref= format_ref_marker($refs,$hash_base);6695 git_header_html();6696my$basedir='';6697if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6698my@views_nav= ();6699if(defined$file_name) {6700push@views_nav,6701$cgi->a({-href => href(action=>"history", -replay=>1)},6702"history"),6703$cgi->a({-href => href(action=>"tree",6704 hash_base=>"HEAD", file_name=>$file_name)},6705"HEAD"),6706}6707my$snapshot_links= format_snapshot_links($hash);6708if(defined$snapshot_links) {6709# FIXME: Should be available when we have no hash base as well.6710push@views_nav,$snapshot_links;6711}6712 git_print_page_nav('tree','',$hash_base,undef,undef,6713join(' | ',@views_nav));6714 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);6715}else{6716undef$hash_base;6717print"<div class=\"page_nav\">\n";6718print"<br/><br/></div>\n";6719print"<div class=\"title\">".esc_html($hash)."</div>\n";6720}6721if(defined$file_name) {6722$basedir=$file_name;6723if($basedirne''&&substr($basedir, -1)ne'/') {6724$basedir.='/';6725}6726 git_print_page_path($file_name,'tree',$hash_base);6727}6728print"<div class=\"page_body\">\n";6729print"<table class=\"tree\">\n";6730my$alternate=1;6731# '..' (top directory) link if possible6732if(defined$hash_base&&6733defined$file_name&&$file_name=~m![^/]+$!) {6734if($alternate) {6735print"<tr class=\"dark\">\n";6736}else{6737print"<tr class=\"light\">\n";6738}6739$alternate^=1;67406741my$up=$file_name;6742$up=~s!/?[^/]+$!!;6743undef$upunless$up;6744# based on git_print_tree_entry6745print'<td class="mode">'. mode_str('040000') ."</td>\n";6746print'<td class="size"> </td>'."\n"if$show_sizes;6747print'<td class="list">';6748print$cgi->a({-href => href(action=>"tree",6749 hash_base=>$hash_base,6750 file_name=>$up)},6751"..");6752print"</td>\n";6753print"<td class=\"link\"></td>\n";67546755print"</tr>\n";6756}6757foreachmy$line(@entries) {6758my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);67596760if($alternate) {6761print"<tr class=\"dark\">\n";6762}else{6763print"<tr class=\"light\">\n";6764}6765$alternate^=1;67666767 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);67686769print"</tr>\n";6770}6771print"</table>\n".6772"</div>";6773 git_footer_html();6774}67756776sub snapshot_name {6777my($project,$hash) =@_;67786779# path/to/project.git -> project6780# path/to/project/.git -> project6781my$name= to_utf8($project);6782$name=~ s,([^/])/*\.git$,$1,;6783$name= basename($name);6784# sanitize name6785$name=~s/[[:cntrl:]]/?/g;67866787my$ver=$hash;6788if($hash=~/^[0-9a-fA-F]+$/) {6789# shorten SHA-1 hash6790my$full_hash= git_get_full_hash($project,$hash);6791if($full_hash=~/^$hash/&&length($hash) >7) {6792$ver= git_get_short_hash($project,$hash);6793}6794}elsif($hash=~m!^refs/tags/(.*)$!) {6795# tags don't need shortened SHA-1 hash6796$ver=$1;6797}else{6798# branches and other need shortened SHA-1 hash6799if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {6800$ver=$1;6801}6802$ver.='-'. git_get_short_hash($project,$hash);6803}6804# in case of hierarchical branch names6805$ver=~s!/!.!g;68066807# name = project-version_string6808$name="$name-$ver";68096810returnwantarray? ($name,$name) :$name;6811}68126813sub git_snapshot {6814my$format=$input_params{'snapshot_format'};6815if(!@snapshot_fmts) {6816 die_error(403,"Snapshots not allowed");6817}6818# default to first supported snapshot format6819$format||=$snapshot_fmts[0];6820if($format!~m/^[a-z0-9]+$/) {6821 die_error(400,"Invalid snapshot format parameter");6822}elsif(!exists($known_snapshot_formats{$format})) {6823 die_error(400,"Unknown snapshot format");6824}elsif($known_snapshot_formats{$format}{'disabled'}) {6825 die_error(403,"Snapshot format not allowed");6826}elsif(!grep($_eq$format,@snapshot_fmts)) {6827 die_error(403,"Unsupported snapshot format");6828}68296830my$type= git_get_type("$hash^{}");6831if(!$type) {6832 die_error(404,'Object does not exist');6833}elsif($typeeq'blob') {6834 die_error(400,'Object is not a tree-ish');6835}68366837my($name,$prefix) = snapshot_name($project,$hash);6838my$filename="$name$known_snapshot_formats{$format}{'suffix'}";6839my$cmd= quote_command(6840 git_cmd(),'archive',6841"--format=$known_snapshot_formats{$format}{'format'}",6842"--prefix=$prefix/",$hash);6843if(exists$known_snapshot_formats{$format}{'compressor'}) {6844$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});6845}68466847$filename=~s/(["\\])/\\$1/g;6848print$cgi->header(6849-type =>$known_snapshot_formats{$format}{'type'},6850-content_disposition =>'inline; filename="'.$filename.'"',6851-status =>'200 OK');68526853open my$fd,"-|",$cmd6854or die_error(500,"Execute git-archive failed");6855binmode STDOUT,':raw';6856print<$fd>;6857binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6858close$fd;6859}68606861sub git_log_generic {6862my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;68636864my$head= git_get_head_hash($project);6865if(!defined$base) {6866$base=$head;6867}6868if(!defined$page) {6869$page=0;6870}6871my$refs= git_get_references();68726873my$commit_hash=$base;6874if(defined$parent) {6875$commit_hash="$parent..$base";6876}6877my@commitlist=6878 parse_commits($commit_hash,101, (100*$page),6879defined$file_name? ($file_name,"--full-history") : ());68806881my$ftype;6882if(!defined$file_hash&&defined$file_name) {6883# some commits could have deleted file in question,6884# and not have it in tree, but one of them has to have it6885for(my$i=0;$i<@commitlist;$i++) {6886$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);6887last ifdefined$file_hash;6888}6889}6890if(defined$file_hash) {6891$ftype= git_get_type($file_hash);6892}6893if(defined$file_name&& !defined$ftype) {6894 die_error(500,"Unknown type of object");6895}6896my%co;6897if(defined$file_name) {6898%co= parse_commit($base)6899or die_error(404,"Unknown commit object");6900}690169026903my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);6904my$next_link='';6905if($#commitlist>=100) {6906$next_link=6907$cgi->a({-href => href(-replay=>1, page=>$page+1),6908-accesskey =>"n", -title =>"Alt-n"},"next");6909}6910my$patch_max= gitweb_get_feature('patches');6911if($patch_max&& !defined$file_name) {6912if($patch_max<0||@commitlist<=$patch_max) {6913$paging_nav.=" ⋅ ".6914$cgi->a({-href => href(action=>"patches", -replay=>1)},6915"patches");6916}6917}69186919 git_header_html();6920 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);6921if(defined$file_name) {6922 git_print_header_div('commit', esc_html($co{'title'}),$base);6923}else{6924 git_print_header_div('summary',$project)6925}6926 git_print_page_path($file_name,$ftype,$hash_base)6927if(defined$file_name);69286929$body_subr->(\@commitlist,0,99,$refs,$next_link,6930$file_name,$file_hash,$ftype);69316932 git_footer_html();6933}69346935sub git_log {6936 git_log_generic('log', \&git_log_body,6937$hash,$hash_parent);6938}69396940sub git_commit {6941$hash||=$hash_base||"HEAD";6942my%co= parse_commit($hash)6943or die_error(404,"Unknown commit object");69446945my$parent=$co{'parent'};6946my$parents=$co{'parents'};# listref69476948# we need to prepare $formats_nav before any parameter munging6949my$formats_nav;6950if(!defined$parent) {6951# --root commitdiff6952$formats_nav.='(initial)';6953}elsif(@$parents==1) {6954# single parent commit6955$formats_nav.=6956'(parent: '.6957$cgi->a({-href => href(action=>"commit",6958 hash=>$parent)},6959 esc_html(substr($parent,0,7))) .6960')';6961}else{6962# merge commit6963$formats_nav.=6964'(merge: '.6965join(' ',map{6966$cgi->a({-href => href(action=>"commit",6967 hash=>$_)},6968 esc_html(substr($_,0,7)));6969}@$parents) .6970')';6971}6972if(gitweb_check_feature('patches') &&@$parents<=1) {6973$formats_nav.=" | ".6974$cgi->a({-href => href(action=>"patch", -replay=>1)},6975"patch");6976}69776978if(!defined$parent) {6979$parent="--root";6980}6981my@difftree;6982open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",6983@diff_opts,6984(@$parents<=1?$parent:'-c'),6985$hash,"--"6986or die_error(500,"Open git-diff-tree failed");6987@difftree=map{chomp;$_} <$fd>;6988close$fdor die_error(404,"Reading git-diff-tree failed");69896990# non-textual hash id's can be cached6991my$expires;6992if($hash=~m/^[0-9a-fA-F]{40}$/) {6993$expires="+1d";6994}6995my$refs= git_get_references();6996my$ref= format_ref_marker($refs,$co{'id'});69976998 git_header_html(undef,$expires);6999 git_print_page_nav('commit','',7000$hash,$co{'tree'},$hash,7001$formats_nav);70027003if(defined$co{'parent'}) {7004 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);7005}else{7006 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);7007}7008print"<div class=\"title_text\">\n".7009"<table class=\"object_header\">\n";7010 git_print_authorship_rows(\%co);7011print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";7012print"<tr>".7013"<td>tree</td>".7014"<td class=\"sha1\">".7015$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),7016class=>"list"},$co{'tree'}) .7017"</td>".7018"<td class=\"link\">".7019$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},7020"tree");7021my$snapshot_links= format_snapshot_links($hash);7022if(defined$snapshot_links) {7023print" | ".$snapshot_links;7024}7025print"</td>".7026"</tr>\n";70277028foreachmy$par(@$parents) {7029print"<tr>".7030"<td>parent</td>".7031"<td class=\"sha1\">".7032$cgi->a({-href => href(action=>"commit", hash=>$par),7033class=>"list"},$par) .7034"</td>".7035"<td class=\"link\">".7036$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .7037" | ".7038$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .7039"</td>".7040"</tr>\n";7041}7042print"</table>".7043"</div>\n";70447045print"<div class=\"page_body\">\n";7046 git_print_log($co{'comment'});7047print"</div>\n";70487049 git_difftree_body(\@difftree,$hash,@$parents);70507051 git_footer_html();7052}70537054sub git_object {7055# object is defined by:7056# - hash or hash_base alone7057# - hash_base and file_name7058my$type;70597060# - hash or hash_base alone7061if($hash|| ($hash_base&& !defined$file_name)) {7062my$object_id=$hash||$hash_base;70637064open my$fd,"-|", quote_command(7065 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'7066or die_error(404,"Object does not exist");7067$type= <$fd>;7068chomp$type;7069close$fd7070or die_error(404,"Object does not exist");70717072# - hash_base and file_name7073}elsif($hash_base&&defined$file_name) {7074$file_name=~ s,/+$,,;70757076system(git_cmd(),"cat-file",'-e',$hash_base) ==07077or die_error(404,"Base object does not exist");70787079# here errors should not hapen7080open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name7081or die_error(500,"Open git-ls-tree failed");7082my$line= <$fd>;7083close$fd;70847085#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'7086unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {7087 die_error(404,"File or directory for given base does not exist");7088}7089$type=$2;7090$hash=$3;7091}else{7092 die_error(400,"Not enough information to find object");7093}70947095print$cgi->redirect(-uri => href(action=>$type, -full=>1,7096 hash=>$hash, hash_base=>$hash_base,7097 file_name=>$file_name),7098-status =>'302 Found');7099}71007101sub git_blobdiff {7102my$format=shift||'html';7103my$diff_style=$input_params{'diff_style'} ||'inline';71047105my$fd;7106my@difftree;7107my%diffinfo;7108my$expires;71097110# preparing $fd and %diffinfo for git_patchset_body7111# new style URI7112if(defined$hash_base&&defined$hash_parent_base) {7113if(defined$file_name) {7114# read raw output7115open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7116$hash_parent_base,$hash_base,7117"--", (defined$file_parent?$file_parent: ()),$file_name7118or die_error(500,"Open git-diff-tree failed");7119@difftree=map{chomp;$_} <$fd>;7120close$fd7121or die_error(404,"Reading git-diff-tree failed");7122@difftree7123or die_error(404,"Blob diff not found");71247125}elsif(defined$hash&&7126$hash=~/[0-9a-fA-F]{40}/) {7127# try to find filename from $hash71287129# read filtered raw output7130open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7131$hash_parent_base,$hash_base,"--"7132or die_error(500,"Open git-diff-tree failed");7133@difftree=7134# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'7135# $hash == to_id7136grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}7137map{chomp;$_} <$fd>;7138close$fd7139or die_error(404,"Reading git-diff-tree failed");7140@difftree7141or die_error(404,"Blob diff not found");71427143}else{7144 die_error(400,"Missing one of the blob diff parameters");7145}71467147if(@difftree>1) {7148 die_error(400,"Ambiguous blob diff specification");7149}71507151%diffinfo= parse_difftree_raw_line($difftree[0]);7152$file_parent||=$diffinfo{'from_file'} ||$file_name;7153$file_name||=$diffinfo{'to_file'};71547155$hash_parent||=$diffinfo{'from_id'};7156$hash||=$diffinfo{'to_id'};71577158# non-textual hash id's can be cached7159if($hash_base=~m/^[0-9a-fA-F]{40}$/&&7160$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {7161$expires='+1d';7162}71637164# open patch output7165open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7166'-p', ($formateq'html'?"--full-index": ()),7167$hash_parent_base,$hash_base,7168"--", (defined$file_parent?$file_parent: ()),$file_name7169or die_error(500,"Open git-diff-tree failed");7170}71717172# old/legacy style URI -- not generated anymore since 1.4.3.7173if(!%diffinfo) {7174 die_error('404 Not Found',"Missing one of the blob diff parameters")7175}71767177# header7178if($formateq'html') {7179my$formats_nav=7180$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},7181"raw");7182$formats_nav.= diff_style_nav($diff_style);7183 git_header_html(undef,$expires);7184if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7185 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7186 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7187}else{7188print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";7189print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";7190}7191if(defined$file_name) {7192 git_print_page_path($file_name,"blob",$hash_base);7193}else{7194print"<div class=\"page_path\"></div>\n";7195}71967197}elsif($formateq'plain') {7198print$cgi->header(7199-type =>'text/plain',7200-charset =>'utf-8',7201-expires =>$expires,7202-content_disposition =>'inline; filename="'."$file_name".'.patch"');72037204print"X-Git-Url: ".$cgi->self_url() ."\n\n";72057206}else{7207 die_error(400,"Unknown blobdiff format");7208}72097210# patch7211if($formateq'html') {7212print"<div class=\"page_body\">\n";72137214 git_patchset_body($fd,$diff_style,7215[ \%diffinfo],$hash_base,$hash_parent_base);7216close$fd;72177218print"</div>\n";# class="page_body"7219 git_footer_html();72207221}else{7222while(my$line= <$fd>) {7223$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;7224$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;72257226print$line;72277228last if$line=~m!^\+\+\+!;7229}7230local$/=undef;7231print<$fd>;7232close$fd;7233}7234}72357236sub git_blobdiff_plain {7237 git_blobdiff('plain');7238}72397240# assumes that it is added as later part of already existing navigation,7241# so it returns "| foo | bar" rather than just "foo | bar"7242sub diff_style_nav {7243my($diff_style,$is_combined) =@_;7244$diff_style||='inline';72457246return""if($is_combined);72477248my@styles= (inline =>'inline','sidebyside'=>'side by side');7249my%styles=@styles;7250@styles=7251@styles[map{$_*2}0..$#styles/2];72527253returnjoin'',7254map{" | ".$_}7255map{7256$_eq$diff_style?$styles{$_} :7257$cgi->a({-href => href(-replay=>1, diff_style =>$_)},$styles{$_})7258}@styles;7259}72607261sub git_commitdiff {7262my%params=@_;7263my$format=$params{-format} ||'html';7264my$diff_style=$input_params{'diff_style'} ||'inline';72657266my($patch_max) = gitweb_get_feature('patches');7267if($formateq'patch') {7268 die_error(403,"Patch view not allowed")unless$patch_max;7269}72707271$hash||=$hash_base||"HEAD";7272my%co= parse_commit($hash)7273or die_error(404,"Unknown commit object");72747275# choose format for commitdiff for merge7276if(!defined$hash_parent&& @{$co{'parents'}} >1) {7277$hash_parent='--cc';7278}7279# we need to prepare $formats_nav before almost any parameter munging7280my$formats_nav;7281if($formateq'html') {7282$formats_nav=7283$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},7284"raw");7285if($patch_max&& @{$co{'parents'}} <=1) {7286$formats_nav.=" | ".7287$cgi->a({-href => href(action=>"patch", -replay=>1)},7288"patch");7289}7290$formats_nav.= diff_style_nav($diff_style, @{$co{'parents'}} >1);72917292if(defined$hash_parent&&7293$hash_parentne'-c'&&$hash_parentne'--cc') {7294# commitdiff with two commits given7295my$hash_parent_short=$hash_parent;7296if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {7297$hash_parent_short=substr($hash_parent,0,7);7298}7299$formats_nav.=7300' (from';7301for(my$i=0;$i< @{$co{'parents'}};$i++) {7302if($co{'parents'}[$i]eq$hash_parent) {7303$formats_nav.=' parent '. ($i+1);7304last;7305}7306}7307$formats_nav.=': '.7308$cgi->a({-href => href(-replay=>1,7309 hash=>$hash_parent, hash_base=>undef)},7310 esc_html($hash_parent_short)) .7311')';7312}elsif(!$co{'parent'}) {7313# --root commitdiff7314$formats_nav.=' (initial)';7315}elsif(scalar@{$co{'parents'}} ==1) {7316# single parent commit7317$formats_nav.=7318' (parent: '.7319$cgi->a({-href => href(-replay=>1,7320 hash=>$co{'parent'}, hash_base=>undef)},7321 esc_html(substr($co{'parent'},0,7))) .7322')';7323}else{7324# merge commit7325if($hash_parenteq'--cc') {7326$formats_nav.=' | '.7327$cgi->a({-href => href(-replay=>1,7328 hash=>$hash, hash_parent=>'-c')},7329'combined');7330}else{# $hash_parent eq '-c'7331$formats_nav.=' | '.7332$cgi->a({-href => href(-replay=>1,7333 hash=>$hash, hash_parent=>'--cc')},7334'compact');7335}7336$formats_nav.=7337' (merge: '.7338join(' ',map{7339$cgi->a({-href => href(-replay=>1,7340 hash=>$_, hash_base=>undef)},7341 esc_html(substr($_,0,7)));7342} @{$co{'parents'}} ) .7343')';7344}7345}73467347my$hash_parent_param=$hash_parent;7348if(!defined$hash_parent_param) {7349# --cc for multiple parents, --root for parentless7350$hash_parent_param=7351@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';7352}73537354# read commitdiff7355my$fd;7356my@difftree;7357if($formateq'html') {7358open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7359"--no-commit-id","--patch-with-raw","--full-index",7360$hash_parent_param,$hash,"--"7361or die_error(500,"Open git-diff-tree failed");73627363while(my$line= <$fd>) {7364chomp$line;7365# empty line ends raw part of diff-tree output7366last unless$line;7367push@difftree,scalar parse_difftree_raw_line($line);7368}73697370}elsif($formateq'plain') {7371open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7372'-p',$hash_parent_param,$hash,"--"7373or die_error(500,"Open git-diff-tree failed");7374}elsif($formateq'patch') {7375# For commit ranges, we limit the output to the number of7376# patches specified in the 'patches' feature.7377# For single commits, we limit the output to a single patch,7378# diverging from the git-format-patch default.7379my@commit_spec= ();7380if($hash_parent) {7381if($patch_max>0) {7382push@commit_spec,"-$patch_max";7383}7384push@commit_spec,'-n',"$hash_parent..$hash";7385}else{7386if($params{-single}) {7387push@commit_spec,'-1';7388}else{7389if($patch_max>0) {7390push@commit_spec,"-$patch_max";7391}7392push@commit_spec,"-n";7393}7394push@commit_spec,'--root',$hash;7395}7396open$fd,"-|", git_cmd(),"format-patch",@diff_opts,7397'--encoding=utf8','--stdout',@commit_spec7398or die_error(500,"Open git-format-patch failed");7399}else{7400 die_error(400,"Unknown commitdiff format");7401}74027403# non-textual hash id's can be cached7404my$expires;7405if($hash=~m/^[0-9a-fA-F]{40}$/) {7406$expires="+1d";7407}74087409# write commit message7410if($formateq'html') {7411my$refs= git_get_references();7412my$ref= format_ref_marker($refs,$co{'id'});74137414 git_header_html(undef,$expires);7415 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);7416 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);7417print"<div class=\"title_text\">\n".7418"<table class=\"object_header\">\n";7419 git_print_authorship_rows(\%co);7420print"</table>".7421"</div>\n";7422print"<div class=\"page_body\">\n";7423if(@{$co{'comment'}} >1) {7424print"<div class=\"log\">\n";7425 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);7426print"</div>\n";# class="log"7427}74287429}elsif($formateq'plain') {7430my$refs= git_get_references("tags");7431my$tagname= git_get_rev_name_tags($hash);7432my$filename= basename($project) ."-$hash.patch";74337434print$cgi->header(7435-type =>'text/plain',7436-charset =>'utf-8',7437-expires =>$expires,7438-content_disposition =>'inline; filename="'."$filename".'"');7439my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});7440print"From: ". to_utf8($co{'author'}) ."\n";7441print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";7442print"Subject: ". to_utf8($co{'title'}) ."\n";74437444print"X-Git-Tag:$tagname\n"if$tagname;7445print"X-Git-Url: ".$cgi->self_url() ."\n\n";74467447foreachmy$line(@{$co{'comment'}}) {7448print to_utf8($line) ."\n";7449}7450print"---\n\n";7451}elsif($formateq'patch') {7452my$filename= basename($project) ."-$hash.patch";74537454print$cgi->header(7455-type =>'text/plain',7456-charset =>'utf-8',7457-expires =>$expires,7458-content_disposition =>'inline; filename="'."$filename".'"');7459}74607461# write patch7462if($formateq'html') {7463my$use_parents= !defined$hash_parent||7464$hash_parenteq'-c'||$hash_parenteq'--cc';7465 git_difftree_body(\@difftree,$hash,7466$use_parents? @{$co{'parents'}} :$hash_parent);7467print"<br/>\n";74687469 git_patchset_body($fd,$diff_style,7470 \@difftree,$hash,7471$use_parents? @{$co{'parents'}} :$hash_parent);7472close$fd;7473print"</div>\n";# class="page_body"7474 git_footer_html();74757476}elsif($formateq'plain') {7477local$/=undef;7478print<$fd>;7479close$fd7480or print"Reading git-diff-tree failed\n";7481}elsif($formateq'patch') {7482local$/=undef;7483print<$fd>;7484close$fd7485or print"Reading git-format-patch failed\n";7486}7487}74887489sub git_commitdiff_plain {7490 git_commitdiff(-format =>'plain');7491}74927493# format-patch-style patches7494sub git_patch {7495 git_commitdiff(-format =>'patch', -single =>1);7496}74977498sub git_patches {7499 git_commitdiff(-format =>'patch');7500}75017502sub git_history {7503 git_log_generic('history', \&git_history_body,7504$hash_base,$hash_parent_base,7505$file_name,$hash);7506}75077508sub git_search {7509$searchtype||='commit';75107511# check if appropriate features are enabled7512 gitweb_check_feature('search')7513or die_error(403,"Search is disabled");7514if($searchtypeeq'pickaxe') {7515# pickaxe may take all resources of your box and run for several minutes7516# with every query - so decide by yourself how public you make this feature7517 gitweb_check_feature('pickaxe')7518or die_error(403,"Pickaxe search is disabled");7519}7520if($searchtypeeq'grep') {7521# grep search might be potentially CPU-intensive, too7522 gitweb_check_feature('grep')7523or die_error(403,"Grep search is disabled");7524}75257526if(!defined$searchtext) {7527 die_error(400,"Text field is empty");7528}7529if(!defined$hash) {7530$hash= git_get_head_hash($project);7531}7532my%co= parse_commit($hash);7533if(!%co) {7534 die_error(404,"Unknown commit object");7535}7536if(!defined$page) {7537$page=0;7538}75397540if($searchtypeeq'commit'||7541$searchtypeeq'author'||7542$searchtypeeq'committer') {7543 git_search_message(%co);7544}elsif($searchtypeeq'pickaxe') {7545 git_search_changes(%co);7546}elsif($searchtypeeq'grep') {7547 git_search_files(%co);7548}else{7549 die_error(400,"Unknown search type");7550}7551}75527553sub git_search_help {7554 git_header_html();7555 git_print_page_nav('','',$hash,$hash,$hash);7556print<<EOT;7557<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without7558regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,7559the pattern entered is recognized as the POSIX extended7560<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case7561insensitive).</p>7562<dl>7563<dt><b>commit</b></dt>7564<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>7565EOT7566my$have_grep= gitweb_check_feature('grep');7567if($have_grep) {7568print<<EOT;7569<dt><b>grep</b></dt>7570<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing7571 a different one) are searched for the given pattern. On large trees, this search can take7572a while and put some strain on the server, so please use it with some consideration. Note that7573due to git-grep peculiarity, currently if regexp mode is turned off, the matches are7574case-sensitive.</dd>7575EOT7576}7577print<<EOT;7578<dt><b>author</b></dt>7579<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>7580<dt><b>committer</b></dt>7581<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>7582EOT7583my$have_pickaxe= gitweb_check_feature('pickaxe');7584if($have_pickaxe) {7585print<<EOT;7586<dt><b>pickaxe</b></dt>7587<dd>All commits that caused the string to appear or disappear from any file (changes that7588added, removed or "modified" the string) will be listed. This search can take a while and7589takes a lot of strain on the server, so please use it wisely. Note that since you may be7590interested even in changes just changing the case as well, this search is case sensitive.</dd>7591EOT7592}7593print"</dl>\n";7594 git_footer_html();7595}75967597sub git_shortlog {7598 git_log_generic('shortlog', \&git_shortlog_body,7599$hash,$hash_parent);7600}76017602## ......................................................................7603## feeds (RSS, Atom; OPML)76047605sub git_feed {7606my$format=shift||'atom';7607my$have_blame= gitweb_check_feature('blame');76087609# Atom: http://www.atomenabled.org/developers/syndication/7610# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ7611if($formatne'rss'&&$formatne'atom') {7612 die_error(400,"Unknown web feed format");7613}76147615# log/feed of current (HEAD) branch, log of given branch, history of file/directory7616my$head=$hash||'HEAD';7617my@commitlist= parse_commits($head,150,0,$file_name);76187619my%latest_commit;7620my%latest_date;7621my$content_type="application/$format+xml";7622if(defined$cgi->http('HTTP_ACCEPT') &&7623$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {7624# browser (feed reader) prefers text/xml7625$content_type='text/xml';7626}7627if(defined($commitlist[0])) {7628%latest_commit= %{$commitlist[0]};7629my$latest_epoch=$latest_commit{'committer_epoch'};7630%latest_date= parse_date($latest_epoch,$latest_commit{'comitter_tz'});7631my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7632if(defined$if_modified) {7633my$since;7634if(eval{require HTTP::Date;1; }) {7635$since= HTTP::Date::str2time($if_modified);7636}elsif(eval{require Time::ParseDate;1; }) {7637$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7638}7639if(defined$since&&$latest_epoch<=$since) {7640print$cgi->header(7641-type =>$content_type,7642-charset =>'utf-8',7643-last_modified =>$latest_date{'rfc2822'},7644-status =>'304 Not Modified');7645return;7646}7647}7648print$cgi->header(7649-type =>$content_type,7650-charset =>'utf-8',7651-last_modified =>$latest_date{'rfc2822'});7652}else{7653print$cgi->header(7654-type =>$content_type,7655-charset =>'utf-8');7656}76577658# Optimization: skip generating the body if client asks only7659# for Last-Modified date.7660return if($cgi->request_method()eq'HEAD');76617662# header variables7663my$title="$site_name-$project/$action";7664my$feed_type='log';7665if(defined$hash) {7666$title.=" - '$hash'";7667$feed_type='branch log';7668if(defined$file_name) {7669$title.=" ::$file_name";7670$feed_type='history';7671}7672}elsif(defined$file_name) {7673$title.=" -$file_name";7674$feed_type='history';7675}7676$title.="$feed_type";7677my$descr= git_get_project_description($project);7678if(defined$descr) {7679$descr= esc_html($descr);7680}else{7681$descr="$project".7682($formateq'rss'?'RSS':'Atom') .7683" feed";7684}7685my$owner= git_get_project_owner($project);7686$owner= esc_html($owner);76877688#header7689my$alt_url;7690if(defined$file_name) {7691$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);7692}elsif(defined$hash) {7693$alt_url= href(-full=>1, action=>"log", hash=>$hash);7694}else{7695$alt_url= href(-full=>1, action=>"summary");7696}7697print qq!<?xml version="1.0" encoding="utf-8"?>\n!;7698if($formateq'rss') {7699print<<XML;7700<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">7701<channel>7702XML7703print"<title>$title</title>\n".7704"<link>$alt_url</link>\n".7705"<description>$descr</description>\n".7706"<language>en</language>\n".7707# project owner is responsible for 'editorial' content7708"<managingEditor>$owner</managingEditor>\n";7709if(defined$logo||defined$favicon) {7710# prefer the logo to the favicon, since RSS7711# doesn't allow both7712my$img= esc_url($logo||$favicon);7713print"<image>\n".7714"<url>$img</url>\n".7715"<title>$title</title>\n".7716"<link>$alt_url</link>\n".7717"</image>\n";7718}7719if(%latest_date) {7720print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";7721print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";7722}7723print"<generator>gitweb v.$version/$git_version</generator>\n";7724}elsif($formateq'atom') {7725print<<XML;7726<feed xmlns="http://www.w3.org/2005/Atom">7727XML7728print"<title>$title</title>\n".7729"<subtitle>$descr</subtitle>\n".7730'<link rel="alternate" type="text/html" href="'.7731$alt_url.'" />'."\n".7732'<link rel="self" type="'.$content_type.'" href="'.7733$cgi->self_url() .'" />'."\n".7734"<id>". href(-full=>1) ."</id>\n".7735# use project owner for feed author7736"<author><name>$owner</name></author>\n";7737if(defined$favicon) {7738print"<icon>". esc_url($favicon) ."</icon>\n";7739}7740if(defined$logo) {7741# not twice as wide as tall: 72 x 27 pixels7742print"<logo>". esc_url($logo) ."</logo>\n";7743}7744if(!%latest_date) {7745# dummy date to keep the feed valid until commits trickle in:7746print"<updated>1970-01-01T00:00:00Z</updated>\n";7747}else{7748print"<updated>$latest_date{'iso-8601'}</updated>\n";7749}7750print"<generator version='$version/$git_version'>gitweb</generator>\n";7751}77527753# contents7754for(my$i=0;$i<=$#commitlist;$i++) {7755my%co= %{$commitlist[$i]};7756my$commit=$co{'id'};7757# we read 150, we always show 30 and the ones more recent than 48 hours7758if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {7759last;7760}7761my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});77627763# get list of changed files7764open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7765$co{'parent'} ||"--root",7766$co{'id'},"--", (defined$file_name?$file_name: ())7767ornext;7768my@difftree=map{chomp;$_} <$fd>;7769close$fd7770ornext;77717772# print element (entry, item)7773my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);7774if($formateq'rss') {7775print"<item>\n".7776"<title>". esc_html($co{'title'}) ."</title>\n".7777"<author>". esc_html($co{'author'}) ."</author>\n".7778"<pubDate>$cd{'rfc2822'}</pubDate>\n".7779"<guid isPermaLink=\"true\">$co_url</guid>\n".7780"<link>$co_url</link>\n".7781"<description>". esc_html($co{'title'}) ."</description>\n".7782"<content:encoded>".7783"<![CDATA[\n";7784}elsif($formateq'atom') {7785print"<entry>\n".7786"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".7787"<updated>$cd{'iso-8601'}</updated>\n".7788"<author>\n".7789" <name>". esc_html($co{'author_name'}) ."</name>\n";7790if($co{'author_email'}) {7791print" <email>". esc_html($co{'author_email'}) ."</email>\n";7792}7793print"</author>\n".7794# use committer for contributor7795"<contributor>\n".7796" <name>". esc_html($co{'committer_name'}) ."</name>\n";7797if($co{'committer_email'}) {7798print" <email>". esc_html($co{'committer_email'}) ."</email>\n";7799}7800print"</contributor>\n".7801"<published>$cd{'iso-8601'}</published>\n".7802"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".7803"<id>$co_url</id>\n".7804"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".7805"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";7806}7807my$comment=$co{'comment'};7808print"<pre>\n";7809foreachmy$line(@$comment) {7810$line= esc_html($line);7811print"$line\n";7812}7813print"</pre><ul>\n";7814foreachmy$difftree_line(@difftree) {7815my%difftree= parse_difftree_raw_line($difftree_line);7816next if!$difftree{'from_id'};78177818my$file=$difftree{'file'} ||$difftree{'to_file'};78197820print"<li>".7821"[".7822$cgi->a({-href => href(-full=>1, action=>"blobdiff",7823 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},7824 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},7825 file_name=>$file, file_parent=>$difftree{'from_file'}),7826-title =>"diff"},'D');7827if($have_blame) {7828print$cgi->a({-href => href(-full=>1, action=>"blame",7829 file_name=>$file, hash_base=>$commit),7830-title =>"blame"},'B');7831}7832# if this is not a feed of a file history7833if(!defined$file_name||$file_namene$file) {7834print$cgi->a({-href => href(-full=>1, action=>"history",7835 file_name=>$file, hash=>$commit),7836-title =>"history"},'H');7837}7838$file= esc_path($file);7839print"] ".7840"$file</li>\n";7841}7842if($formateq'rss') {7843print"</ul>]]>\n".7844"</content:encoded>\n".7845"</item>\n";7846}elsif($formateq'atom') {7847print"</ul>\n</div>\n".7848"</content>\n".7849"</entry>\n";7850}7851}78527853# end of feed7854if($formateq'rss') {7855print"</channel>\n</rss>\n";7856}elsif($formateq'atom') {7857print"</feed>\n";7858}7859}78607861sub git_rss {7862 git_feed('rss');7863}78647865sub git_atom {7866 git_feed('atom');7867}78687869sub git_opml {7870my@list= git_get_projects_list();7871if(!@list) {7872 die_error(404,"No projects found");7873}78747875print$cgi->header(7876-type =>'text/xml',7877-charset =>'utf-8',7878-content_disposition =>'inline; filename="opml.xml"');78797880my$title= esc_html($site_name);7881print<<XML;7882<?xml version="1.0" encoding="utf-8"?>7883<opml version="1.0">7884<head>7885 <title>$titleOPML Export</title>7886</head>7887<body>7888<outline text="git RSS feeds">7889XML78907891foreachmy$pr(@list) {7892my%proj=%$pr;7893my$head= git_get_head_hash($proj{'path'});7894if(!defined$head) {7895next;7896}7897$git_dir="$projectroot/$proj{'path'}";7898my%co= parse_commit($head);7899if(!%co) {7900next;7901}79027903my$path= esc_html(chop_str($proj{'path'},25,5));7904my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);7905my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);7906print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";7907}7908print<<XML;7909</outline>7910</body>7911</opml>7912XML7913}