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=$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# this must be last entry (for manipulation from JavaScript) 763 javascript =>"js" 764); 765our%cgi_param_mapping=@cgi_param_mapping; 766 767# we will also need to know the possible actions, for validation 768our%actions= ( 769"blame"=> \&git_blame, 770"blame_incremental"=> \&git_blame_incremental, 771"blame_data"=> \&git_blame_data, 772"blobdiff"=> \&git_blobdiff, 773"blobdiff_plain"=> \&git_blobdiff_plain, 774"blob"=> \&git_blob, 775"blob_plain"=> \&git_blob_plain, 776"commitdiff"=> \&git_commitdiff, 777"commitdiff_plain"=> \&git_commitdiff_plain, 778"commit"=> \&git_commit, 779"forks"=> \&git_forks, 780"heads"=> \&git_heads, 781"history"=> \&git_history, 782"log"=> \&git_log, 783"patch"=> \&git_patch, 784"patches"=> \&git_patches, 785"remotes"=> \&git_remotes, 786"rss"=> \&git_rss, 787"atom"=> \&git_atom, 788"search"=> \&git_search, 789"search_help"=> \&git_search_help, 790"shortlog"=> \&git_shortlog, 791"summary"=> \&git_summary, 792"tag"=> \&git_tag, 793"tags"=> \&git_tags, 794"tree"=> \&git_tree, 795"snapshot"=> \&git_snapshot, 796"object"=> \&git_object, 797# those below don't need $project 798"opml"=> \&git_opml, 799"project_list"=> \&git_project_list, 800"project_index"=> \&git_project_index, 801); 802 803# finally, we have the hash of allowed extra_options for the commands that 804# allow them 805our%allowed_options= ( 806"--no-merges"=> [qw(rss atom log shortlog history)], 807); 808 809# fill %input_params with the CGI parameters. All values except for 'opt' 810# should be single values, but opt can be an array. We should probably 811# build an array of parameters that can be multi-valued, but since for the time 812# being it's only this one, we just single it out 813sub evaluate_query_params { 814our$cgi; 815 816while(my($name,$symbol) =each%cgi_param_mapping) { 817if($symboleq'opt') { 818$input_params{$name} = [$cgi->param($symbol) ]; 819}else{ 820$input_params{$name} =$cgi->param($symbol); 821} 822} 823} 824 825# now read PATH_INFO and update the parameter list for missing parameters 826sub evaluate_path_info { 827return ifdefined$input_params{'project'}; 828return if!$path_info; 829$path_info=~ s,^/+,,; 830return if!$path_info; 831 832# find which part of PATH_INFO is project 833my$project=$path_info; 834$project=~ s,/+$,,; 835while($project&& !check_head_link("$projectroot/$project")) { 836$project=~ s,/*[^/]*$,,; 837} 838return unless$project; 839$input_params{'project'} =$project; 840 841# do not change any parameters if an action is given using the query string 842return if$input_params{'action'}; 843$path_info=~ s,^\Q$project\E/*,,; 844 845# next, check if we have an action 846my$action=$path_info; 847$action=~ s,/.*$,,; 848if(exists$actions{$action}) { 849$path_info=~ s,^$action/*,,; 850$input_params{'action'} =$action; 851} 852 853# list of actions that want hash_base instead of hash, but can have no 854# pathname (f) parameter 855my@wants_base= ( 856'tree', 857'history', 858); 859 860# we want to catch, among others 861# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 862my($parentrefname,$parentpathname,$refname,$pathname) = 863($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/); 864 865# first, analyze the 'current' part 866if(defined$pathname) { 867# we got "branch:filename" or "branch:dir/" 868# we could use git_get_type(branch:pathname), but: 869# - it needs $git_dir 870# - it does a git() call 871# - the convention of terminating directories with a slash 872# makes it superfluous 873# - embedding the action in the PATH_INFO would make it even 874# more superfluous 875$pathname=~ s,^/+,,; 876if(!$pathname||substr($pathname, -1)eq"/") { 877$input_params{'action'} ||="tree"; 878$pathname=~ s,/$,,; 879}else{ 880# the default action depends on whether we had parent info 881# or not 882if($parentrefname) { 883$input_params{'action'} ||="blobdiff_plain"; 884}else{ 885$input_params{'action'} ||="blob_plain"; 886} 887} 888$input_params{'hash_base'} ||=$refname; 889$input_params{'file_name'} ||=$pathname; 890}elsif(defined$refname) { 891# we got "branch". In this case we have to choose if we have to 892# set hash or hash_base. 893# 894# Most of the actions without a pathname only want hash to be 895# set, except for the ones specified in @wants_base that want 896# hash_base instead. It should also be noted that hand-crafted 897# links having 'history' as an action and no pathname or hash 898# set will fail, but that happens regardless of PATH_INFO. 899if(defined$parentrefname) { 900# if there is parent let the default be 'shortlog' action 901# (for http://git.example.com/repo.git/A..B links); if there 902# is no parent, dispatch will detect type of object and set 903# action appropriately if required (if action is not set) 904$input_params{'action'} ||="shortlog"; 905} 906if($input_params{'action'} && 907grep{$_eq$input_params{'action'} }@wants_base) { 908$input_params{'hash_base'} ||=$refname; 909}else{ 910$input_params{'hash'} ||=$refname; 911} 912} 913 914# next, handle the 'parent' part, if present 915if(defined$parentrefname) { 916# a missing pathspec defaults to the 'current' filename, allowing e.g. 917# someproject/blobdiff/oldrev..newrev:/filename 918if($parentpathname) { 919$parentpathname=~ s,^/+,,; 920$parentpathname=~ s,/$,,; 921$input_params{'file_parent'} ||=$parentpathname; 922}else{ 923$input_params{'file_parent'} ||=$input_params{'file_name'}; 924} 925# we assume that hash_parent_base is wanted if a path was specified, 926# or if the action wants hash_base instead of hash 927if(defined$input_params{'file_parent'} || 928grep{$_eq$input_params{'action'} }@wants_base) { 929$input_params{'hash_parent_base'} ||=$parentrefname; 930}else{ 931$input_params{'hash_parent'} ||=$parentrefname; 932} 933} 934 935# for the snapshot action, we allow URLs in the form 936# $project/snapshot/$hash.ext 937# where .ext determines the snapshot and gets removed from the 938# passed $refname to provide the $hash. 939# 940# To be able to tell that $refname includes the format extension, we 941# require the following two conditions to be satisfied: 942# - the hash input parameter MUST have been set from the $refname part 943# of the URL (i.e. they must be equal) 944# - the snapshot format MUST NOT have been defined already (e.g. from 945# CGI parameter sf) 946# It's also useless to try any matching unless $refname has a dot, 947# so we check for that too 948if(defined$input_params{'action'} && 949$input_params{'action'}eq'snapshot'&& 950defined$refname&&index($refname,'.') != -1&& 951$refnameeq$input_params{'hash'} && 952!defined$input_params{'snapshot_format'}) { 953# We loop over the known snapshot formats, checking for 954# extensions. Allowed extensions are both the defined suffix 955# (which includes the initial dot already) and the snapshot 956# format key itself, with a prepended dot 957while(my($fmt,$opt) =each%known_snapshot_formats) { 958my$hash=$refname; 959unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 960next; 961} 962my$sfx=$1; 963# a valid suffix was found, so set the snapshot format 964# and reset the hash parameter 965$input_params{'snapshot_format'} =$fmt; 966$input_params{'hash'} =$hash; 967# we also set the format suffix to the one requested 968# in the URL: this way a request for e.g. .tgz returns 969# a .tgz instead of a .tar.gz 970$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 971last; 972} 973} 974} 975 976our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 977$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 978$searchtext,$search_regexp); 979sub evaluate_and_validate_params { 980our$action=$input_params{'action'}; 981if(defined$action) { 982if(!validate_action($action)) { 983 die_error(400,"Invalid action parameter"); 984} 985} 986 987# parameters which are pathnames 988our$project=$input_params{'project'}; 989if(defined$project) { 990if(!validate_project($project)) { 991undef$project; 992 die_error(404,"No such project"); 993} 994} 995 996our$file_name=$input_params{'file_name'}; 997if(defined$file_name) { 998if(!validate_pathname($file_name)) { 999 die_error(400,"Invalid file parameter");1000}1001}10021003our$file_parent=$input_params{'file_parent'};1004if(defined$file_parent) {1005if(!validate_pathname($file_parent)) {1006 die_error(400,"Invalid file parent parameter");1007}1008}10091010# parameters which are refnames1011our$hash=$input_params{'hash'};1012if(defined$hash) {1013if(!validate_refname($hash)) {1014 die_error(400,"Invalid hash parameter");1015}1016}10171018our$hash_parent=$input_params{'hash_parent'};1019if(defined$hash_parent) {1020if(!validate_refname($hash_parent)) {1021 die_error(400,"Invalid hash parent parameter");1022}1023}10241025our$hash_base=$input_params{'hash_base'};1026if(defined$hash_base) {1027if(!validate_refname($hash_base)) {1028 die_error(400,"Invalid hash base parameter");1029}1030}10311032our@extra_options= @{$input_params{'extra_options'}};1033# @extra_options is always defined, since it can only be (currently) set from1034# CGI, and $cgi->param() returns the empty array in array context if the param1035# is not set1036foreachmy$opt(@extra_options) {1037if(not exists$allowed_options{$opt}) {1038 die_error(400,"Invalid option parameter");1039}1040if(not grep(/^$action$/, @{$allowed_options{$opt}})) {1041 die_error(400,"Invalid option parameter for this action");1042}1043}10441045our$hash_parent_base=$input_params{'hash_parent_base'};1046if(defined$hash_parent_base) {1047if(!validate_refname($hash_parent_base)) {1048 die_error(400,"Invalid hash parent base parameter");1049}1050}10511052# other parameters1053our$page=$input_params{'page'};1054if(defined$page) {1055if($page=~m/[^0-9]/) {1056 die_error(400,"Invalid page parameter");1057}1058}10591060our$searchtype=$input_params{'searchtype'};1061if(defined$searchtype) {1062if($searchtype=~m/[^a-z]/) {1063 die_error(400,"Invalid searchtype parameter");1064}1065}10661067our$search_use_regexp=$input_params{'search_use_regexp'};10681069our$searchtext=$input_params{'searchtext'};1070our$search_regexp;1071if(defined$searchtext) {1072if(length($searchtext) <2) {1073 die_error(403,"At least two characters are required for search parameter");1074}1075$search_regexp=$search_use_regexp?$searchtext:quotemeta$searchtext;1076}1077}10781079# path to the current git repository1080our$git_dir;1081sub evaluate_git_dir {1082our$git_dir="$projectroot/$project"if$project;1083}10841085our(@snapshot_fmts,$git_avatar);1086sub configure_gitweb_features {1087# list of supported snapshot formats1088our@snapshot_fmts= gitweb_get_feature('snapshot');1089@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);10901091# check that the avatar feature is set to a known provider name,1092# and for each provider check if the dependencies are satisfied.1093# if the provider name is invalid or the dependencies are not met,1094# reset $git_avatar to the empty string.1095our($git_avatar) = gitweb_get_feature('avatar');1096if($git_avatareq'gravatar') {1097$git_avatar=''unless(eval{require Digest::MD5;1; });1098}elsif($git_avatareq'picon') {1099# no dependencies1100}else{1101$git_avatar='';1102}1103}11041105# custom error handler: 'die <message>' is Internal Server Error1106sub handle_errors_html {1107my$msg=shift;# it is already HTML escaped11081109# to avoid infinite loop where error occurs in die_error,1110# change handler to default handler, disabling handle_errors_html1111 set_message("Error occured when inside die_error:\n$msg");11121113# you cannot jump out of die_error when called as error handler;1114# the subroutine set via CGI::Carp::set_message is called _after_1115# HTTP headers are already written, so it cannot write them itself1116 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1117}1118set_message(\&handle_errors_html);11191120# dispatch1121sub dispatch {1122if(!defined$action) {1123if(defined$hash) {1124$action= git_get_type($hash);1125}elsif(defined$hash_base&&defined$file_name) {1126$action= git_get_type("$hash_base:$file_name");1127}elsif(defined$project) {1128$action='summary';1129}else{1130$action='project_list';1131}1132}1133if(!defined($actions{$action})) {1134 die_error(400,"Unknown action");1135}1136if($action!~m/^(?:opml|project_list|project_index)$/&&1137!$project) {1138 die_error(400,"Project needed");1139}1140$actions{$action}->();1141}11421143sub reset_timer {1144our$t0= [ gettimeofday() ]1145ifdefined$t0;1146our$number_of_git_cmds=0;1147}11481149our$first_request=1;1150sub run_request {1151 reset_timer();11521153 evaluate_uri();1154if($first_request) {1155 evaluate_gitweb_config();1156 evaluate_git_version();1157}1158if($per_request_config) {1159if(ref($per_request_config)eq'CODE') {1160$per_request_config->();1161}elsif(!$first_request) {1162 evaluate_gitweb_config();1163}1164}1165 check_loadavg();11661167# $projectroot and $projects_list might be set in gitweb config file1168$projects_list||=$projectroot;11691170 evaluate_query_params();1171 evaluate_path_info();1172 evaluate_and_validate_params();1173 evaluate_git_dir();11741175 configure_gitweb_features();11761177 dispatch();1178}11791180our$is_last_request=sub{1};1181our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1182our$CGI='CGI';1183our$cgi;1184sub configure_as_fcgi {1185require CGI::Fast;1186our$CGI='CGI::Fast';11871188my$request_number=0;1189# let each child service 100 requests1190our$is_last_request=sub{ ++$request_number>100};1191}1192sub evaluate_argv {1193my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1194 configure_as_fcgi()1195if$script_name=~/\.fcgi$/;11961197return unless(@ARGV);11981199require Getopt::Long;1200 Getopt::Long::GetOptions(1201'fastcgi|fcgi|f'=> \&configure_as_fcgi,1202'nproc|n=i'=>sub{1203my($arg,$val) =@_;1204return unlesseval{require FCGI::ProcManager;1; };1205my$proc_manager= FCGI::ProcManager->new({1206 n_processes =>$val,1207});1208our$pre_listen_hook=sub{$proc_manager->pm_manage() };1209our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1210our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1211},1212);1213}12141215sub run {1216 evaluate_argv();12171218$first_request=1;1219$pre_listen_hook->()1220if$pre_listen_hook;12211222 REQUEST:1223while($cgi=$CGI->new()) {1224$pre_dispatch_hook->()1225if$pre_dispatch_hook;12261227 run_request();12281229$post_dispatch_hook->()1230if$post_dispatch_hook;1231$first_request=0;12321233last REQUEST if($is_last_request->());1234}12351236 DONE_GITWEB:12371;1238}12391240run();12411242if(defined caller) {1243# wrapped in a subroutine processing requests,1244# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1245return;1246}else{1247# pure CGI script, serving single request1248exit;1249}12501251## ======================================================================1252## action links12531254# possible values of extra options1255# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1256# -replay => 1 - start from a current view (replay with modifications)1257# -path_info => 0|1 - don't use/use path_info URL (if possible)1258# -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone1259sub href {1260my%params=@_;1261# default is to use -absolute url() i.e. $my_uri1262my$href=$params{-full} ?$my_url:$my_uri;12631264# implicit -replay, must be first of implicit params1265$params{-replay} =1if(keys%params==1&&$params{-anchor});12661267$params{'project'} =$projectunlessexists$params{'project'};12681269if($params{-replay}) {1270while(my($name,$symbol) =each%cgi_param_mapping) {1271if(!exists$params{$name}) {1272$params{$name} =$input_params{$name};1273}1274}1275}12761277my$use_pathinfo= gitweb_check_feature('pathinfo');1278if(defined$params{'project'} &&1279(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1280# try to put as many parameters as possible in PATH_INFO:1281# - project name1282# - action1283# - hash_parent or hash_parent_base:/file_parent1284# - hash or hash_base:/filename1285# - the snapshot_format as an appropriate suffix12861287# When the script is the root DirectoryIndex for the domain,1288# $href here would be something like http://gitweb.example.com/1289# Thus, we strip any trailing / from $href, to spare us double1290# slashes in the final URL1291$href=~ s,/$,,;12921293# Then add the project name, if present1294$href.="/".esc_path_info($params{'project'});1295delete$params{'project'};12961297# since we destructively absorb parameters, we keep this1298# boolean that remembers if we're handling a snapshot1299my$is_snapshot=$params{'action'}eq'snapshot';13001301# Summary just uses the project path URL, any other action is1302# added to the URL1303if(defined$params{'action'}) {1304$href.="/".esc_path_info($params{'action'})1305unless$params{'action'}eq'summary';1306delete$params{'action'};1307}13081309# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1310# stripping nonexistent or useless pieces1311$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1312||$params{'hash_parent'} ||$params{'hash'});1313if(defined$params{'hash_base'}) {1314if(defined$params{'hash_parent_base'}) {1315$href.= esc_path_info($params{'hash_parent_base'});1316# skip the file_parent if it's the same as the file_name1317if(defined$params{'file_parent'}) {1318if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1319delete$params{'file_parent'};1320}elsif($params{'file_parent'} !~/\.\./) {1321$href.=":/".esc_path_info($params{'file_parent'});1322delete$params{'file_parent'};1323}1324}1325$href.="..";1326delete$params{'hash_parent'};1327delete$params{'hash_parent_base'};1328}elsif(defined$params{'hash_parent'}) {1329$href.= esc_path_info($params{'hash_parent'})."..";1330delete$params{'hash_parent'};1331}13321333$href.= esc_path_info($params{'hash_base'});1334if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1335$href.=":/".esc_path_info($params{'file_name'});1336delete$params{'file_name'};1337}1338delete$params{'hash'};1339delete$params{'hash_base'};1340}elsif(defined$params{'hash'}) {1341$href.= esc_path_info($params{'hash'});1342delete$params{'hash'};1343}13441345# If the action was a snapshot, we can absorb the1346# snapshot_format parameter too1347if($is_snapshot) {1348my$fmt=$params{'snapshot_format'};1349# snapshot_format should always be defined when href()1350# is called, but just in case some code forgets, we1351# fall back to the default1352$fmt||=$snapshot_fmts[0];1353$href.=$known_snapshot_formats{$fmt}{'suffix'};1354delete$params{'snapshot_format'};1355}1356}13571358# now encode the parameters explicitly1359my@result= ();1360for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1361my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1362if(defined$params{$name}) {1363if(ref($params{$name})eq"ARRAY") {1364foreachmy$par(@{$params{$name}}) {1365push@result,$symbol."=". esc_param($par);1366}1367}else{1368push@result,$symbol."=". esc_param($params{$name});1369}1370}1371}1372$href.="?".join(';',@result)ifscalar@result;13731374# final transformation: trailing spaces must be escaped (URI-encoded)1375$href=~s/(\s+)$/CGI::escape($1)/e;13761377if($params{-anchor}) {1378$href.="#".esc_param($params{-anchor});1379}13801381return$href;1382}138313841385## ======================================================================1386## validation, quoting/unquoting and escaping13871388sub validate_action {1389my$input=shift||returnundef;1390returnundefunlessexists$actions{$input};1391return$input;1392}13931394sub validate_project {1395my$input=shift||returnundef;1396if(!validate_pathname($input) ||1397!(-d "$projectroot/$input") ||1398!check_export_ok("$projectroot/$input") ||1399($strict_export&& !project_in_list($input))) {1400returnundef;1401}else{1402return$input;1403}1404}14051406sub validate_pathname {1407my$input=shift||returnundef;14081409# no '.' or '..' as elements of path, i.e. no '.' nor '..'1410# at the beginning, at the end, and between slashes.1411# also this catches doubled slashes1412if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1413returnundef;1414}1415# no null characters1416if($input=~m!\0!) {1417returnundef;1418}1419return$input;1420}14211422sub validate_refname {1423my$input=shift||returnundef;14241425# textual hashes are O.K.1426if($input=~m/^[0-9a-fA-F]{40}$/) {1427return$input;1428}1429# it must be correct pathname1430$input= validate_pathname($input)1431orreturnundef;1432# restrictions on ref name according to git-check-ref-format1433if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1434returnundef;1435}1436return$input;1437}14381439# decode sequences of octets in utf8 into Perl's internal form,1440# which is utf-8 with utf8 flag set if needed. gitweb writes out1441# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1442sub to_utf8 {1443my$str=shift;1444returnundefunlessdefined$str;1445if(utf8::valid($str)) {1446 utf8::decode($str);1447return$str;1448}else{1449return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1450}1451}14521453# quote unsafe chars, but keep the slash, even when it's not1454# correct, but quoted slashes look too horrible in bookmarks1455sub esc_param {1456my$str=shift;1457returnundefunlessdefined$str;1458$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1459$str=~s/ /\+/g;1460return$str;1461}14621463# the quoting rules for path_info fragment are slightly different1464sub esc_path_info {1465my$str=shift;1466returnundefunlessdefined$str;14671468# path_info doesn't treat '+' as space (specially), but '?' must be escaped1469$str=~s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;14701471return$str;1472}14731474# quote unsafe chars in whole URL, so some characters cannot be quoted1475sub esc_url {1476my$str=shift;1477returnundefunlessdefined$str;1478$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1479$str=~s/ /\+/g;1480return$str;1481}14821483# quote unsafe characters in HTML attributes1484sub esc_attr {14851486# for XHTML conformance escaping '"' to '"' is not enough1487return esc_html(@_);1488}14891490# replace invalid utf8 character with SUBSTITUTION sequence1491sub esc_html {1492my$str=shift;1493my%opts=@_;14941495returnundefunlessdefined$str;14961497$str= to_utf8($str);1498$str=$cgi->escapeHTML($str);1499if($opts{'-nbsp'}) {1500$str=~s/ / /g;1501}1502$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1503return$str;1504}15051506# quote control characters and escape filename to HTML1507sub esc_path {1508my$str=shift;1509my%opts=@_;15101511returnundefunlessdefined$str;15121513$str= to_utf8($str);1514$str=$cgi->escapeHTML($str);1515if($opts{'-nbsp'}) {1516$str=~s/ / /g;1517}1518$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1519return$str;1520}15211522# Make control characters "printable", using character escape codes (CEC)1523sub quot_cec {1524my$cntrl=shift;1525my%opts=@_;1526my%es= (# character escape codes, aka escape sequences1527"\t"=>'\t',# tab (HT)1528"\n"=>'\n',# line feed (LF)1529"\r"=>'\r',# carrige return (CR)1530"\f"=>'\f',# form feed (FF)1531"\b"=>'\b',# backspace (BS)1532"\a"=>'\a',# alarm (bell) (BEL)1533"\e"=>'\e',# escape (ESC)1534"\013"=>'\v',# vertical tab (VT)1535"\000"=>'\0',# nul character (NUL)1536);1537my$chr= ( (exists$es{$cntrl})1538?$es{$cntrl}1539:sprintf('\%2x',ord($cntrl)) );1540if($opts{-nohtml}) {1541return$chr;1542}else{1543return"<span class=\"cntrl\">$chr</span>";1544}1545}15461547# Alternatively use unicode control pictures codepoints,1548# Unicode "printable representation" (PR)1549sub quot_upr {1550my$cntrl=shift;1551my%opts=@_;15521553my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1554if($opts{-nohtml}) {1555return$chr;1556}else{1557return"<span class=\"cntrl\">$chr</span>";1558}1559}15601561# git may return quoted and escaped filenames1562sub unquote {1563my$str=shift;15641565sub unq {1566my$seq=shift;1567my%es= (# character escape codes, aka escape sequences1568't'=>"\t",# tab (HT, TAB)1569'n'=>"\n",# newline (NL)1570'r'=>"\r",# return (CR)1571'f'=>"\f",# form feed (FF)1572'b'=>"\b",# backspace (BS)1573'a'=>"\a",# alarm (bell) (BEL)1574'e'=>"\e",# escape (ESC)1575'v'=>"\013",# vertical tab (VT)1576);15771578if($seq=~m/^[0-7]{1,3}$/) {1579# octal char sequence1580returnchr(oct($seq));1581}elsif(exists$es{$seq}) {1582# C escape sequence, aka character escape code1583return$es{$seq};1584}1585# quoted ordinary character1586return$seq;1587}15881589if($str=~m/^"(.*)"$/) {1590# needs unquoting1591$str=$1;1592$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1593}1594return$str;1595}15961597# escape tabs (convert tabs to spaces)1598sub untabify {1599my$line=shift;16001601while((my$pos=index($line,"\t")) != -1) {1602if(my$count= (8- ($pos%8))) {1603my$spaces=' ' x $count;1604$line=~s/\t/$spaces/;1605}1606}16071608return$line;1609}16101611sub project_in_list {1612my$project=shift;1613my@list= git_get_projects_list();1614return@list&&scalar(grep{$_->{'path'}eq$project}@list);1615}16161617## ----------------------------------------------------------------------1618## HTML aware string manipulation16191620# Try to chop given string on a word boundary between position1621# $len and $len+$add_len. If there is no word boundary there,1622# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1623# (marking chopped part) would be longer than given string.1624sub chop_str {1625my$str=shift;1626my$len=shift;1627my$add_len=shift||10;1628my$where=shift||'right';# 'left' | 'center' | 'right'16291630# Make sure perl knows it is utf8 encoded so we don't1631# cut in the middle of a utf8 multibyte char.1632$str= to_utf8($str);16331634# allow only $len chars, but don't cut a word if it would fit in $add_len1635# if it doesn't fit, cut it if it's still longer than the dots we would add1636# remove chopped character entities entirely16371638# when chopping in the middle, distribute $len into left and right part1639# return early if chopping wouldn't make string shorter1640if($whereeq'center') {1641return$strif($len+5>=length($str));# filler is length 51642$len=int($len/2);1643}else{1644return$strif($len+4>=length($str));# filler is length 41645}16461647# regexps: ending and beginning with word part up to $add_len1648my$endre=qr/.{$len}\w{0,$add_len}/;1649my$begre=qr/\w{0,$add_len}.{$len}/;16501651if($whereeq'left') {1652$str=~m/^(.*?)($begre)$/;1653my($lead,$body) = ($1,$2);1654if(length($lead) >4) {1655$lead=" ...";1656}1657return"$lead$body";16581659}elsif($whereeq'center') {1660$str=~m/^($endre)(.*)$/;1661my($left,$str) = ($1,$2);1662$str=~m/^(.*?)($begre)$/;1663my($mid,$right) = ($1,$2);1664if(length($mid) >5) {1665$mid=" ... ";1666}1667return"$left$mid$right";16681669}else{1670$str=~m/^($endre)(.*)$/;1671my$body=$1;1672my$tail=$2;1673if(length($tail) >4) {1674$tail="... ";1675}1676return"$body$tail";1677}1678}16791680# takes the same arguments as chop_str, but also wraps a <span> around the1681# result with a title attribute if it does get chopped. Additionally, the1682# string is HTML-escaped.1683sub chop_and_escape_str {1684my($str) =@_;16851686my$chopped= chop_str(@_);1687if($choppedeq$str) {1688return esc_html($chopped);1689}else{1690$str=~s/[[:cntrl:]]/?/g;1691return$cgi->span({-title=>$str}, esc_html($chopped));1692}1693}16941695## ----------------------------------------------------------------------1696## functions returning short strings16971698# CSS class for given age value (in seconds)1699sub age_class {1700my$age=shift;17011702if(!defined$age) {1703return"noage";1704}elsif($age<60*60*2) {1705return"age0";1706}elsif($age<60*60*24*2) {1707return"age1";1708}else{1709return"age2";1710}1711}17121713# convert age in seconds to "nn units ago" string1714sub age_string {1715my$age=shift;1716my$age_str;17171718if($age>60*60*24*365*2) {1719$age_str= (int$age/60/60/24/365);1720$age_str.=" years ago";1721}elsif($age>60*60*24*(365/12)*2) {1722$age_str=int$age/60/60/24/(365/12);1723$age_str.=" months ago";1724}elsif($age>60*60*24*7*2) {1725$age_str=int$age/60/60/24/7;1726$age_str.=" weeks ago";1727}elsif($age>60*60*24*2) {1728$age_str=int$age/60/60/24;1729$age_str.=" days ago";1730}elsif($age>60*60*2) {1731$age_str=int$age/60/60;1732$age_str.=" hours ago";1733}elsif($age>60*2) {1734$age_str=int$age/60;1735$age_str.=" min ago";1736}elsif($age>2) {1737$age_str=int$age;1738$age_str.=" sec ago";1739}else{1740$age_str.=" right now";1741}1742return$age_str;1743}17441745useconstant{1746 S_IFINVALID =>0030000,1747 S_IFGITLINK =>0160000,1748};17491750# submodule/subproject, a commit object reference1751sub S_ISGITLINK {1752my$mode=shift;17531754return(($mode& S_IFMT) == S_IFGITLINK)1755}17561757# convert file mode in octal to symbolic file mode string1758sub mode_str {1759my$mode=oct shift;17601761if(S_ISGITLINK($mode)) {1762return'm---------';1763}elsif(S_ISDIR($mode& S_IFMT)) {1764return'drwxr-xr-x';1765}elsif(S_ISLNK($mode)) {1766return'lrwxrwxrwx';1767}elsif(S_ISREG($mode)) {1768# git cares only about the executable bit1769if($mode& S_IXUSR) {1770return'-rwxr-xr-x';1771}else{1772return'-rw-r--r--';1773};1774}else{1775return'----------';1776}1777}17781779# convert file mode in octal to file type string1780sub file_type {1781my$mode=shift;17821783if($mode!~m/^[0-7]+$/) {1784return$mode;1785}else{1786$mode=oct$mode;1787}17881789if(S_ISGITLINK($mode)) {1790return"submodule";1791}elsif(S_ISDIR($mode& S_IFMT)) {1792return"directory";1793}elsif(S_ISLNK($mode)) {1794return"symlink";1795}elsif(S_ISREG($mode)) {1796return"file";1797}else{1798return"unknown";1799}1800}18011802# convert file mode in octal to file type description string1803sub file_type_long {1804my$mode=shift;18051806if($mode!~m/^[0-7]+$/) {1807return$mode;1808}else{1809$mode=oct$mode;1810}18111812if(S_ISGITLINK($mode)) {1813return"submodule";1814}elsif(S_ISDIR($mode& S_IFMT)) {1815return"directory";1816}elsif(S_ISLNK($mode)) {1817return"symlink";1818}elsif(S_ISREG($mode)) {1819if($mode& S_IXUSR) {1820return"executable";1821}else{1822return"file";1823};1824}else{1825return"unknown";1826}1827}182818291830## ----------------------------------------------------------------------1831## functions returning short HTML fragments, or transforming HTML fragments1832## which don't belong to other sections18331834# format line of commit message.1835sub format_log_line_html {1836my$line=shift;18371838$line= esc_html($line, -nbsp=>1);1839$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1840$cgi->a({-href => href(action=>"object", hash=>$1),1841-class=>"text"},$1);1842}eg;18431844return$line;1845}18461847# format marker of refs pointing to given object18481849# the destination action is chosen based on object type and current context:1850# - for annotated tags, we choose the tag view unless it's the current view1851# already, in which case we go to shortlog view1852# - for other refs, we keep the current view if we're in history, shortlog or1853# log view, and select shortlog otherwise1854sub format_ref_marker {1855my($refs,$id) =@_;1856my$markers='';18571858if(defined$refs->{$id}) {1859foreachmy$ref(@{$refs->{$id}}) {1860# this code exploits the fact that non-lightweight tags are the1861# only indirect objects, and that they are the only objects for which1862# we want to use tag instead of shortlog as action1863my($type,$name) =qw();1864my$indirect= ($ref=~s/\^\{\}$//);1865# e.g. tags/v2.6.11 or heads/next1866if($ref=~m!^(.*?)s?/(.*)$!) {1867$type=$1;1868$name=$2;1869}else{1870$type="ref";1871$name=$ref;1872}18731874my$class=$type;1875$class.=" indirect"if$indirect;18761877my$dest_action="shortlog";18781879if($indirect) {1880$dest_action="tag"unless$actioneq"tag";1881}elsif($action=~/^(history|(short)?log)$/) {1882$dest_action=$action;1883}18841885my$dest="";1886$dest.="refs/"unless$ref=~ m!^refs/!;1887$dest.=$ref;18881889my$link=$cgi->a({1890-href => href(1891 action=>$dest_action,1892 hash=>$dest1893)},$name);18941895$markers.=" <span class=\"".esc_attr($class)."\"title=\"".esc_attr($ref)."\">".1896$link."</span>";1897}1898}18991900if($markers) {1901return' <span class="refs">'.$markers.'</span>';1902}else{1903return"";1904}1905}19061907# format, perhaps shortened and with markers, title line1908sub format_subject_html {1909my($long,$short,$href,$extra) =@_;1910$extra=''unlessdefined($extra);19111912if(length($short) <length($long)) {1913$long=~s/[[:cntrl:]]/?/g;1914return$cgi->a({-href =>$href, -class=>"list subject",1915-title => to_utf8($long)},1916 esc_html($short)) .$extra;1917}else{1918return$cgi->a({-href =>$href, -class=>"list subject"},1919 esc_html($long)) .$extra;1920}1921}19221923# Rather than recomputing the url for an email multiple times, we cache it1924# after the first hit. This gives a visible benefit in views where the avatar1925# for the same email is used repeatedly (e.g. shortlog).1926# The cache is shared by all avatar engines (currently gravatar only), which1927# are free to use it as preferred. Since only one avatar engine is used for any1928# given page, there's no risk for cache conflicts.1929our%avatar_cache= ();19301931# Compute the picon url for a given email, by using the picon search service over at1932# http://www.cs.indiana.edu/picons/search.html1933sub picon_url {1934my$email=lc shift;1935if(!$avatar_cache{$email}) {1936my($user,$domain) =split('@',$email);1937$avatar_cache{$email} =1938"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1939"$domain/$user/".1940"users+domains+unknown/up/single";1941}1942return$avatar_cache{$email};1943}19441945# Compute the gravatar url for a given email, if it's not in the cache already.1946# Gravatar stores only the part of the URL before the size, since that's the1947# one computationally more expensive. This also allows reuse of the cache for1948# different sizes (for this particular engine).1949sub gravatar_url {1950my$email=lc shift;1951my$size=shift;1952$avatar_cache{$email} ||=1953"http://www.gravatar.com/avatar/".1954 Digest::MD5::md5_hex($email) ."?s=";1955return$avatar_cache{$email} .$size;1956}19571958# Insert an avatar for the given $email at the given $size if the feature1959# is enabled.1960sub git_get_avatar {1961my($email,%opts) =@_;1962my$pre_white= ($opts{-pad_before} ?" ":"");1963my$post_white= ($opts{-pad_after} ?" ":"");1964$opts{-size} ||='default';1965my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1966my$url="";1967if($git_avatareq'gravatar') {1968$url= gravatar_url($email,$size);1969}elsif($git_avatareq'picon') {1970$url= picon_url($email);1971}1972# Other providers can be added by extending the if chain, defining $url1973# as needed. If no variant puts something in $url, we assume avatars1974# are completely disabled/unavailable.1975if($url) {1976return$pre_white.1977"<img width=\"$size\"".1978"class=\"avatar\"".1979"src=\"".esc_url($url)."\"".1980"alt=\"\"".1981"/>".$post_white;1982}else{1983return"";1984}1985}19861987sub format_search_author {1988my($author,$searchtype,$displaytext) =@_;1989my$have_search= gitweb_check_feature('search');19901991if($have_search) {1992my$performed="";1993if($searchtypeeq'author') {1994$performed="authored";1995}elsif($searchtypeeq'committer') {1996$performed="committed";1997}19981999return$cgi->a({-href => href(action=>"search", hash=>$hash,2000 searchtext=>$author,2001 searchtype=>$searchtype),class=>"list",2002 title=>"Search for commits$performedby$author"},2003$displaytext);20042005}else{2006return$displaytext;2007}2008}20092010# format the author name of the given commit with the given tag2011# the author name is chopped and escaped according to the other2012# optional parameters (see chop_str).2013sub format_author_html {2014my$tag=shift;2015my$co=shift;2016my$author= chop_and_escape_str($co->{'author_name'},@_);2017return"<$tagclass=\"author\">".2018 format_search_author($co->{'author_name'},"author",2019 git_get_avatar($co->{'author_email'}, -pad_after =>1) .2020$author) .2021"</$tag>";2022}20232024# format git diff header line, i.e. "diff --(git|combined|cc) ..."2025sub format_git_diff_header_line {2026my$line=shift;2027my$diffinfo=shift;2028my($from,$to) =@_;20292030if($diffinfo->{'nparents'}) {2031# combined diff2032$line=~s!^(diff (.*?) )"?.*$!$1!;2033if($to->{'href'}) {2034$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2035 esc_path($to->{'file'}));2036}else{# file was deleted (no href)2037$line.= esc_path($to->{'file'});2038}2039}else{2040# "ordinary" diff2041$line=~s!^(diff (.*?) )"?a/.*$!$1!;2042if($from->{'href'}) {2043$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},2044'a/'. esc_path($from->{'file'}));2045}else{# file was added (no href)2046$line.='a/'. esc_path($from->{'file'});2047}2048$line.=' ';2049if($to->{'href'}) {2050$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2051'b/'. esc_path($to->{'file'}));2052}else{# file was deleted2053$line.='b/'. esc_path($to->{'file'});2054}2055}20562057return"<div class=\"diff header\">$line</div>\n";2058}20592060# format extended diff header line, before patch itself2061sub format_extended_diff_header_line {2062my$line=shift;2063my$diffinfo=shift;2064my($from,$to) =@_;20652066# match <path>2067if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {2068$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},2069 esc_path($from->{'file'}));2070}2071if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {2072$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},2073 esc_path($to->{'file'}));2074}2075# match single <mode>2076if($line=~m/\s(\d{6})$/) {2077$line.='<span class="info"> ('.2078 file_type_long($1) .2079')</span>';2080}2081# match <hash>2082if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {2083# can match only for combined diff2084$line='index ';2085for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2086if($from->{'href'}[$i]) {2087$line.=$cgi->a({-href=>$from->{'href'}[$i],2088-class=>"hash"},2089substr($diffinfo->{'from_id'}[$i],0,7));2090}else{2091$line.='0' x 7;2092}2093# separator2094$line.=','if($i<$diffinfo->{'nparents'} -1);2095}2096$line.='..';2097if($to->{'href'}) {2098$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2099substr($diffinfo->{'to_id'},0,7));2100}else{2101$line.='0' x 7;2102}21032104}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {2105# can match only for ordinary diff2106my($from_link,$to_link);2107if($from->{'href'}) {2108$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},2109substr($diffinfo->{'from_id'},0,7));2110}else{2111$from_link='0' x 7;2112}2113if($to->{'href'}) {2114$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2115substr($diffinfo->{'to_id'},0,7));2116}else{2117$to_link='0' x 7;2118}2119my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});2120$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;2121}21222123return$line."<br/>\n";2124}21252126# format from-file/to-file diff header2127sub format_diff_from_to_header {2128my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2129my$line;2130my$result='';21312132$line=$from_line;2133#assert($line =~ m/^---/) if DEBUG;2134# no extra formatting for "^--- /dev/null"2135if(!$diffinfo->{'nparents'}) {2136# ordinary (single parent) diff2137if($line=~m!^--- "?a/!) {2138if($from->{'href'}) {2139$line='--- a/'.2140$cgi->a({-href=>$from->{'href'}, -class=>"path"},2141 esc_path($from->{'file'}));2142}else{2143$line='--- a/'.2144 esc_path($from->{'file'});2145}2146}2147$result.= qq!<div class="diff from_file">$line</div>\n!;21482149}else{2150# combined diff (merge commit)2151for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2152if($from->{'href'}[$i]) {2153$line='--- '.2154$cgi->a({-href=>href(action=>"blobdiff",2155 hash_parent=>$diffinfo->{'from_id'}[$i],2156 hash_parent_base=>$parents[$i],2157 file_parent=>$from->{'file'}[$i],2158 hash=>$diffinfo->{'to_id'},2159 hash_base=>$hash,2160 file_name=>$to->{'file'}),2161-class=>"path",2162-title=>"diff". ($i+1)},2163$i+1) .2164'/'.2165$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2166 esc_path($from->{'file'}[$i]));2167}else{2168$line='--- /dev/null';2169}2170$result.= qq!<div class="diff from_file">$line</div>\n!;2171}2172}21732174$line=$to_line;2175#assert($line =~ m/^\+\+\+/) if DEBUG;2176# no extra formatting for "^+++ /dev/null"2177if($line=~m!^\+\+\+ "?b/!) {2178if($to->{'href'}) {2179$line='+++ b/'.2180$cgi->a({-href=>$to->{'href'}, -class=>"path"},2181 esc_path($to->{'file'}));2182}else{2183$line='+++ b/'.2184 esc_path($to->{'file'});2185}2186}2187$result.= qq!<div class="diff to_file">$line</div>\n!;21882189return$result;2190}21912192# create note for patch simplified by combined diff2193sub format_diff_cc_simplified {2194my($diffinfo,@parents) =@_;2195my$result='';21962197$result.="<div class=\"diff header\">".2198"diff --cc ";2199if(!is_deleted($diffinfo)) {2200$result.=$cgi->a({-href => href(action=>"blob",2201 hash_base=>$hash,2202 hash=>$diffinfo->{'to_id'},2203 file_name=>$diffinfo->{'to_file'}),2204-class=>"path"},2205 esc_path($diffinfo->{'to_file'}));2206}else{2207$result.= esc_path($diffinfo->{'to_file'});2208}2209$result.="</div>\n".# class="diff header"2210"<div class=\"diff nodifferences\">".2211"Simple merge".2212"</div>\n";# class="diff nodifferences"22132214return$result;2215}22162217# format patch (diff) line (not to be used for diff headers)2218sub format_diff_line {2219my$line=shift;2220my($from,$to) =@_;2221my$diff_class="";22222223chomp$line;22242225if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2226# combined diff2227my$prefix=substr($line,0,scalar@{$from->{'href'}});2228if($line=~m/^\@{3}/) {2229$diff_class=" chunk_header";2230}elsif($line=~m/^\\/) {2231$diff_class=" incomplete";2232}elsif($prefix=~tr/+/+/) {2233$diff_class=" add";2234}elsif($prefix=~tr/-/-/) {2235$diff_class=" rem";2236}2237}else{2238# assume ordinary diff2239my$char=substr($line,0,1);2240if($chareq'+') {2241$diff_class=" add";2242}elsif($chareq'-') {2243$diff_class=" rem";2244}elsif($chareq'@') {2245$diff_class=" chunk_header";2246}elsif($chareq"\\") {2247$diff_class=" incomplete";2248}2249}2250$line= untabify($line);2251if($from&&$to&&$line=~m/^\@{2} /) {2252my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2253$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;22542255$from_lines=0unlessdefined$from_lines;2256$to_lines=0unlessdefined$to_lines;22572258if($from->{'href'}) {2259$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2260-class=>"list"},$from_text);2261}2262if($to->{'href'}) {2263$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2264-class=>"list"},$to_text);2265}2266$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2267"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2268return"<div class=\"diff$diff_class\">$line</div>\n";2269}elsif($from&&$to&&$line=~m/^\@{3}/) {2270my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2271my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);22722273@from_text=split(' ',$ranges);2274for(my$i=0;$i<@from_text; ++$i) {2275($from_start[$i],$from_nlines[$i]) =2276(split(',',substr($from_text[$i],1)),0);2277}22782279$to_text=pop@from_text;2280$to_start=pop@from_start;2281$to_nlines=pop@from_nlines;22822283$line="<span class=\"chunk_info\">$prefix";2284for(my$i=0;$i<@from_text; ++$i) {2285if($from->{'href'}[$i]) {2286$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2287-class=>"list"},$from_text[$i]);2288}else{2289$line.=$from_text[$i];2290}2291$line.=" ";2292}2293if($to->{'href'}) {2294$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2295-class=>"list"},$to_text);2296}else{2297$line.=$to_text;2298}2299$line.="$prefix</span>".2300"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2301return"<div class=\"diff$diff_class\">$line</div>\n";2302}2303return"<div class=\"diff$diff_class\">". esc_html($line, -nbsp=>1) ."</div>\n";2304}23052306# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2307# linked. Pass the hash of the tree/commit to snapshot.2308sub format_snapshot_links {2309my($hash) =@_;2310my$num_fmts=@snapshot_fmts;2311if($num_fmts>1) {2312# A parenthesized list of links bearing format names.2313# e.g. "snapshot (_tar.gz_ _zip_)"2314return"snapshot (".join(' ',map2315$cgi->a({2316-href => href(2317 action=>"snapshot",2318 hash=>$hash,2319 snapshot_format=>$_2320)2321},$known_snapshot_formats{$_}{'display'})2322,@snapshot_fmts) .")";2323}elsif($num_fmts==1) {2324# A single "snapshot" link whose tooltip bears the format name.2325# i.e. "_snapshot_"2326my($fmt) =@snapshot_fmts;2327return2328$cgi->a({2329-href => href(2330 action=>"snapshot",2331 hash=>$hash,2332 snapshot_format=>$fmt2333),2334-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2335},"snapshot");2336}else{# $num_fmts == 02337returnundef;2338}2339}23402341## ......................................................................2342## functions returning values to be passed, perhaps after some2343## transformation, to other functions; e.g. returning arguments to href()23442345# returns hash to be passed to href to generate gitweb URL2346# in -title key it returns description of link2347sub get_feed_info {2348my$format=shift||'Atom';2349my%res= (action =>lc($format));23502351# feed links are possible only for project views2352return unless(defined$project);2353# some views should link to OPML, or to generic project feed,2354# or don't have specific feed yet (so they should use generic)2355return if($action=~/^(?:tags|heads|forks|tag|search)$/x);23562357my$branch;2358# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2359# from tag links; this also makes possible to detect branch links2360if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2361(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2362$branch=$1;2363}2364# find log type for feed description (title)2365my$type='log';2366if(defined$file_name) {2367$type="history of$file_name";2368$type.="/"if($actioneq'tree');2369$type.=" on '$branch'"if(defined$branch);2370}else{2371$type="log of$branch"if(defined$branch);2372}23732374$res{-title} =$type;2375$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2376$res{'file_name'} =$file_name;23772378return%res;2379}23802381## ----------------------------------------------------------------------2382## git utility subroutines, invoking git commands23832384# returns path to the core git executable and the --git-dir parameter as list2385sub git_cmd {2386$number_of_git_cmds++;2387return$GIT,'--git-dir='.$git_dir;2388}23892390# quote the given arguments for passing them to the shell2391# quote_command("command", "arg 1", "arg with ' and ! characters")2392# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2393# Try to avoid using this function wherever possible.2394sub quote_command {2395returnjoin(' ',2396map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2397}23982399# get HEAD ref of given project as hash2400sub git_get_head_hash {2401return git_get_full_hash(shift,'HEAD');2402}24032404sub git_get_full_hash {2405return git_get_hash(@_);2406}24072408sub git_get_short_hash {2409return git_get_hash(@_,'--short=7');2410}24112412sub git_get_hash {2413my($project,$hash,@options) =@_;2414my$o_git_dir=$git_dir;2415my$retval=undef;2416$git_dir="$projectroot/$project";2417if(open my$fd,'-|', git_cmd(),'rev-parse',2418'--verify','-q',@options,$hash) {2419$retval= <$fd>;2420chomp$retvalifdefined$retval;2421close$fd;2422}2423if(defined$o_git_dir) {2424$git_dir=$o_git_dir;2425}2426return$retval;2427}24282429# get type of given object2430sub git_get_type {2431my$hash=shift;24322433open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2434my$type= <$fd>;2435close$fdorreturn;2436chomp$type;2437return$type;2438}24392440# repository configuration2441our$config_file='';2442our%config;24432444# store multiple values for single key as anonymous array reference2445# single values stored directly in the hash, not as [ <value> ]2446sub hash_set_multi {2447my($hash,$key,$value) =@_;24482449if(!exists$hash->{$key}) {2450$hash->{$key} =$value;2451}elsif(!ref$hash->{$key}) {2452$hash->{$key} = [$hash->{$key},$value];2453}else{2454push@{$hash->{$key}},$value;2455}2456}24572458# return hash of git project configuration2459# optionally limited to some section, e.g. 'gitweb'2460sub git_parse_project_config {2461my$section_regexp=shift;2462my%config;24632464local$/="\0";24652466open my$fh,"-|", git_cmd(),"config",'-z','-l',2467orreturn;24682469while(my$keyval= <$fh>) {2470chomp$keyval;2471my($key,$value) =split(/\n/,$keyval,2);24722473 hash_set_multi(\%config,$key,$value)2474if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2475}2476close$fh;24772478return%config;2479}24802481# convert config value to boolean: 'true' or 'false'2482# no value, number > 0, 'true' and 'yes' values are true2483# rest of values are treated as false (never as error)2484sub config_to_bool {2485my$val=shift;24862487return1if!defined$val;# section.key24882489# strip leading and trailing whitespace2490$val=~s/^\s+//;2491$val=~s/\s+$//;24922493return(($val=~/^\d+$/&&$val) ||# section.key = 12494($val=~/^(?:true|yes)$/i));# section.key = true2495}24962497# convert config value to simple decimal number2498# an optional value suffix of 'k', 'm', or 'g' will cause the value2499# to be multiplied by 1024, 1048576, or 10737418242500sub config_to_int {2501my$val=shift;25022503# strip leading and trailing whitespace2504$val=~s/^\s+//;2505$val=~s/\s+$//;25062507if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2508$unit=lc($unit);2509# unknown unit is treated as 12510return$num* ($uniteq'g'?1073741824:2511$uniteq'm'?1048576:2512$uniteq'k'?1024:1);2513}2514return$val;2515}25162517# convert config value to array reference, if needed2518sub config_to_multi {2519my$val=shift;25202521returnref($val) ?$val: (defined($val) ? [$val] : []);2522}25232524sub git_get_project_config {2525my($key,$type) =@_;25262527return unlessdefined$git_dir;25282529# key sanity check2530return unless($key);2531# only subsection, if exists, is case sensitive,2532# and not lowercased by 'git config -z -l'2533if(my($hi,$mi,$lo) = ($key=~/^([^.]*)\.(.*)\.([^.]*)$/)) {2534$key=join(".",lc($hi),$mi,lc($lo));2535}else{2536$key=lc($key);2537}2538$key=~s/^gitweb\.//;2539return if($key=~m/\W/);25402541# type sanity check2542if(defined$type) {2543$type=~s/^--//;2544$type=undef2545unless($typeeq'bool'||$typeeq'int');2546}25472548# get config2549if(!defined$config_file||2550$config_filene"$git_dir/config") {2551%config= git_parse_project_config('gitweb');2552$config_file="$git_dir/config";2553}25542555# check if config variable (key) exists2556return unlessexists$config{"gitweb.$key"};25572558# ensure given type2559if(!defined$type) {2560return$config{"gitweb.$key"};2561}elsif($typeeq'bool') {2562# backward compatibility: 'git config --bool' returns true/false2563return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2564}elsif($typeeq'int') {2565return config_to_int($config{"gitweb.$key"});2566}2567return$config{"gitweb.$key"};2568}25692570# get hash of given path at given ref2571sub git_get_hash_by_path {2572my$base=shift;2573my$path=shift||returnundef;2574my$type=shift;25752576$path=~ s,/+$,,;25772578open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2579or die_error(500,"Open git-ls-tree failed");2580my$line= <$fd>;2581close$fdorreturnundef;25822583if(!defined$line) {2584# there is no tree or hash given by $path at $base2585returnundef;2586}25872588#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2589$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2590if(defined$type&&$typene$2) {2591# type doesn't match2592returnundef;2593}2594return$3;2595}25962597# get path of entry with given hash at given tree-ish (ref)2598# used to get 'from' filename for combined diff (merge commit) for renames2599sub git_get_path_by_hash {2600my$base=shift||return;2601my$hash=shift||return;26022603local$/="\0";26042605open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2606orreturnundef;2607while(my$line= <$fd>) {2608chomp$line;26092610#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2611#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2612if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2613close$fd;2614return$1;2615}2616}2617close$fd;2618returnundef;2619}26202621## ......................................................................2622## git utility functions, directly accessing git repository26232624# get the value of config variable either from file named as the variable2625# itself in the repository ($GIT_DIR/$name file), or from gitweb.$name2626# configuration variable in the repository config file.2627sub git_get_file_or_project_config {2628my($path,$name) =@_;26292630$git_dir="$projectroot/$path";2631open my$fd,'<',"$git_dir/$name"2632orreturn git_get_project_config($name);2633my$conf= <$fd>;2634close$fd;2635if(defined$conf) {2636chomp$conf;2637}2638return$conf;2639}26402641sub git_get_project_description {2642my$path=shift;2643return git_get_file_or_project_config($path,'description');2644}26452646sub git_get_project_category {2647my$path=shift;2648return git_get_file_or_project_config($path,'category');2649}265026512652# supported formats:2653# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2654# - if its contents is a number, use it as tag weight,2655# - otherwise add a tag with weight 12656# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2657# the same value multiple times increases tag weight2658# * `gitweb.ctag' multi-valued repo config variable2659sub git_get_project_ctags {2660my$project=shift;2661my$ctags= {};26622663$git_dir="$projectroot/$project";2664if(opendir my$dh,"$git_dir/ctags") {2665my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2666foreachmy$tagfile(@files) {2667open my$ct,'<',$tagfile2668ornext;2669my$val= <$ct>;2670chomp$valif$val;2671close$ct;26722673(my$ctag=$tagfile) =~ s#.*/##;2674if($val=~/^\d+$/) {2675$ctags->{$ctag} =$val;2676}else{2677$ctags->{$ctag} =1;2678}2679}2680closedir$dh;26812682}elsif(open my$fh,'<',"$git_dir/ctags") {2683while(my$line= <$fh>) {2684chomp$line;2685$ctags->{$line}++if$line;2686}2687close$fh;26882689}else{2690my$taglist= config_to_multi(git_get_project_config('ctag'));2691foreachmy$tag(@$taglist) {2692$ctags->{$tag}++;2693}2694}26952696return$ctags;2697}26982699# return hash, where keys are content tags ('ctags'),2700# and values are sum of weights of given tag in every project2701sub git_gather_all_ctags {2702my$projects=shift;2703my$ctags= {};27042705foreachmy$p(@$projects) {2706foreachmy$ct(keys%{$p->{'ctags'}}) {2707$ctags->{$ct} +=$p->{'ctags'}->{$ct};2708}2709}27102711return$ctags;2712}27132714sub git_populate_project_tagcloud {2715my$ctags=shift;27162717# First, merge different-cased tags; tags vote on casing2718my%ctags_lc;2719foreach(keys%$ctags) {2720$ctags_lc{lc$_}->{count} +=$ctags->{$_};2721if(not$ctags_lc{lc$_}->{topcount}2722or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2723$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2724$ctags_lc{lc$_}->{topname} =$_;2725}2726}27272728my$cloud;2729my$matched=$cgi->param('by_tag');2730if(eval{require HTML::TagCloud;1; }) {2731$cloud= HTML::TagCloud->new;2732foreachmy$ctag(sort keys%ctags_lc) {2733# Pad the title with spaces so that the cloud looks2734# less crammed.2735my$title= esc_html($ctags_lc{$ctag}->{topname});2736$title=~s/ / /g;2737$title=~s/^/ /g;2738$title=~s/$/ /g;2739if(defined$matched&&$matchedeq$ctag) {2740$title=qq(<span class="match">$title</span>);2741}2742$cloud->add($title, href(project=>undef, ctag=>$ctag),2743$ctags_lc{$ctag}->{count});2744}2745}else{2746$cloud= {};2747foreachmy$ctag(keys%ctags_lc) {2748my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2749if(defined$matched&&$matchedeq$ctag) {2750$title=qq(<span class="match">$title</span>);2751}2752$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};2753$cloud->{$ctag}{ctag} =2754$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);2755}2756}2757return$cloud;2758}27592760sub git_show_project_tagcloud {2761my($cloud,$count) =@_;2762if(ref$cloudeq'HTML::TagCloud') {2763return$cloud->html_and_css($count);2764}else{2765my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;2766return2767'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.2768join(', ',map{2769$cloud->{$_}->{'ctag'}2770}splice(@tags,0,$count)) .2771'</div>';2772}2773}27742775sub git_get_project_url_list {2776my$path=shift;27772778$git_dir="$projectroot/$path";2779open my$fd,'<',"$git_dir/cloneurl"2780orreturnwantarray?2781@{ config_to_multi(git_get_project_config('url')) } :2782 config_to_multi(git_get_project_config('url'));2783my@git_project_url_list=map{chomp;$_} <$fd>;2784close$fd;27852786returnwantarray?@git_project_url_list: \@git_project_url_list;2787}27882789sub git_get_projects_list {2790my$filter=shift||'';2791my@list;27922793$filter=~s/\.git$//;27942795if(-d $projects_list) {2796# search in directory2797my$dir=$projects_list;2798# remove the trailing "/"2799$dir=~s!/+$!!;2800my$pfxlen=length("$projects_list");2801my$pfxdepth= ($projects_list=~tr!/!!);2802# when filtering, search only given subdirectory2803if($filter) {2804$dir.="/$filter";2805$dir=~s!/+$!!;2806}28072808 File::Find::find({2809 follow_fast =>1,# follow symbolic links2810 follow_skip =>2,# ignore duplicates2811 dangling_symlinks =>0,# ignore dangling symlinks, silently2812 wanted =>sub{2813# global variables2814our$project_maxdepth;2815our$projectroot;2816# skip project-list toplevel, if we get it.2817return if(m!^[/.]$!);2818# only directories can be git repositories2819return unless(-d $_);2820# don't traverse too deep (Find is super slow on os x)2821# $project_maxdepth excludes depth of $projectroot2822if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2823$File::Find::prune =1;2824return;2825}28262827my$path=substr($File::Find::name,$pfxlen+1);2828# we check related file in $projectroot2829if(check_export_ok("$projectroot/$path")) {2830push@list, { path =>$path};2831$File::Find::prune =1;2832}2833},2834},"$dir");28352836}elsif(-f $projects_list) {2837# read from file(url-encoded):2838# 'git%2Fgit.git Linus+Torvalds'2839# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2840# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2841open my$fd,'<',$projects_listorreturn;2842 PROJECT:2843while(my$line= <$fd>) {2844chomp$line;2845my($path,$owner) =split' ',$line;2846$path= unescape($path);2847$owner= unescape($owner);2848if(!defined$path) {2849next;2850}2851# if $filter is rpovided, check if $path begins with $filter2852if($filter&&$path!~m!^\Q$filter\E/!) {2853next;2854}2855if(check_export_ok("$projectroot/$path")) {2856my$pr= {2857 path =>$path,2858 owner => to_utf8($owner),2859};2860push@list,$pr;2861}2862}2863close$fd;2864}2865return@list;2866}28672868# written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)2869# as side effects it sets 'forks' field to list of forks for forked projects2870sub filter_forks_from_projects_list {2871my$projects=shift;28722873my%trie;# prefix tree of directories (path components)2874# generate trie out of those directories that might contain forks2875foreachmy$pr(@$projects) {2876my$path=$pr->{'path'};2877$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory2878next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'2879next unless($path);# skip '.git' repository: tests, git-instaweb2880next unless(-d $path);# containing directory exists2881$pr->{'forks'} = [];# there can be 0 or more forks of project28822883# add to trie2884my@dirs=split('/',$path);2885# walk the trie, until either runs out of components or out of trie2886my$ref= \%trie;2887while(scalar@dirs&&2888exists($ref->{$dirs[0]})) {2889$ref=$ref->{shift@dirs};2890}2891# create rest of trie structure from rest of components2892foreachmy$dir(@dirs) {2893$ref=$ref->{$dir} = {};2894}2895# create end marker, store $pr as a data2896$ref->{''} =$prif(!exists$ref->{''});2897}28982899# filter out forks, by finding shortest prefix match for paths2900my@filtered;2901 PROJECT:2902foreachmy$pr(@$projects) {2903# trie lookup2904my$ref= \%trie;2905 DIR:2906foreachmy$dir(split('/',$pr->{'path'})) {2907if(exists$ref->{''}) {2908# found [shortest] prefix, is a fork - skip it2909push@{$ref->{''}{'forks'}},$pr;2910next PROJECT;2911}2912if(!exists$ref->{$dir}) {2913# not in trie, cannot have prefix, not a fork2914push@filtered,$pr;2915next PROJECT;2916}2917# If the dir is there, we just walk one step down the trie.2918$ref=$ref->{$dir};2919}2920# we ran out of trie2921# (shouldn't happen: it's either no match, or end marker)2922push@filtered,$pr;2923}29242925return@filtered;2926}29272928# note: fill_project_list_info must be run first,2929# for 'descr_long' and 'ctags' to be filled2930sub search_projects_list {2931my($projlist,%opts) =@_;2932my$tagfilter=$opts{'tagfilter'};2933my$searchtext=$opts{'searchtext'};29342935return@$projlist2936unless($tagfilter||$searchtext);29372938my@projects;2939 PROJECT:2940foreachmy$pr(@$projlist) {29412942if($tagfilter) {2943next unlessref($pr->{'ctags'})eq'HASH';2944next unless2945grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};2946}29472948if($searchtext) {2949next unless2950$pr->{'path'} =~/$searchtext/||2951$pr->{'descr_long'} =~/$searchtext/;2952}29532954push@projects,$pr;2955}29562957return@projects;2958}29592960our$gitweb_project_owner=undef;2961sub git_get_project_list_from_file {29622963return if(defined$gitweb_project_owner);29642965$gitweb_project_owner= {};2966# read from file (url-encoded):2967# 'git%2Fgit.git Linus+Torvalds'2968# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2969# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2970if(-f $projects_list) {2971open(my$fd,'<',$projects_list);2972while(my$line= <$fd>) {2973chomp$line;2974my($pr,$ow) =split' ',$line;2975$pr= unescape($pr);2976$ow= unescape($ow);2977$gitweb_project_owner->{$pr} = to_utf8($ow);2978}2979close$fd;2980}2981}29822983sub git_get_project_owner {2984my$project=shift;2985my$owner;29862987returnundefunless$project;2988$git_dir="$projectroot/$project";29892990if(!defined$gitweb_project_owner) {2991 git_get_project_list_from_file();2992}29932994if(exists$gitweb_project_owner->{$project}) {2995$owner=$gitweb_project_owner->{$project};2996}2997if(!defined$owner){2998$owner= git_get_project_config('owner');2999}3000if(!defined$owner) {3001$owner= get_file_owner("$git_dir");3002}30033004return$owner;3005}30063007sub git_get_last_activity {3008my($path) =@_;3009my$fd;30103011$git_dir="$projectroot/$path";3012open($fd,"-|", git_cmd(),'for-each-ref',3013'--format=%(committer)',3014'--sort=-committerdate',3015'--count=1',3016'refs/heads')orreturn;3017my$most_recent= <$fd>;3018close$fdorreturn;3019if(defined$most_recent&&3020$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {3021my$timestamp=$1;3022my$age=time-$timestamp;3023return($age, age_string($age));3024}3025return(undef,undef);3026}30273028# Implementation note: when a single remote is wanted, we cannot use 'git3029# remote show -n' because that command always work (assuming it's a remote URL3030# if it's not defined), and we cannot use 'git remote show' because that would3031# try to make a network roundtrip. So the only way to find if that particular3032# remote is defined is to walk the list provided by 'git remote -v' and stop if3033# and when we find what we want.3034sub git_get_remotes_list {3035my$wanted=shift;3036my%remotes= ();30373038open my$fd,'-|', git_cmd(),'remote','-v';3039return unless$fd;3040while(my$remote= <$fd>) {3041chomp$remote;3042$remote=~s!\t(.*?)\s+\((\w+)\)$!!;3043next if$wantedand not$remoteeq$wanted;3044my($url,$key) = ($1,$2);30453046$remotes{$remote} ||= {'heads'=> () };3047$remotes{$remote}{$key} =$url;3048}3049close$fdorreturn;3050returnwantarray?%remotes: \%remotes;3051}30523053# Takes a hash of remotes as first parameter and fills it by adding the3054# available remote heads for each of the indicated remotes.3055sub fill_remote_heads {3056my$remotes=shift;3057my@heads=map{"remotes/$_"}keys%$remotes;3058my@remoteheads= git_get_heads_list(undef,@heads);3059foreachmy$remote(keys%$remotes) {3060$remotes->{$remote}{'heads'} = [grep{3061$_->{'name'} =~s!^$remote/!!3062}@remoteheads];3063}3064}30653066sub git_get_references {3067my$type=shift||"";3068my%refs;3069# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113070# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3071open my$fd,"-|", git_cmd(),"show-ref","--dereference",3072($type? ("--","refs/$type") : ())# use -- <pattern> if $type3073orreturn;30743075while(my$line= <$fd>) {3076chomp$line;3077if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3078if(defined$refs{$1}) {3079push@{$refs{$1}},$2;3080}else{3081$refs{$1} = [$2];3082}3083}3084}3085close$fdorreturn;3086return \%refs;3087}30883089sub git_get_rev_name_tags {3090my$hash=shift||returnundef;30913092open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3093orreturn;3094my$name_rev= <$fd>;3095close$fd;30963097if($name_rev=~ m|^$hash tags/(.*)$|) {3098return$1;3099}else{3100# catches also '$hash undefined' output3101returnundef;3102}3103}31043105## ----------------------------------------------------------------------3106## parse to hash functions31073108sub parse_date {3109my$epoch=shift;3110my$tz=shift||"-0000";31113112my%date;3113my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3114my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3115my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3116$date{'hour'} =$hour;3117$date{'minute'} =$min;3118$date{'mday'} =$mday;3119$date{'day'} =$days[$wday];3120$date{'month'} =$months[$mon];3121$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3122$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3123$date{'mday-time'} =sprintf"%d%s%02d:%02d",3124$mday,$months[$mon],$hour,$min;3125$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",31261900+$year,1+$mon,$mday,$hour,$min,$sec;31273128my($tz_sign,$tz_hour,$tz_min) =3129($tz=~m/^([-+])(\d\d)(\d\d)$/);3130$tz_sign= ($tz_signeq'-'? -1: +1);3131my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3132($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3133$date{'hour_local'} =$hour;3134$date{'minute_local'} =$min;3135$date{'tz_local'} =$tz;3136$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",31371900+$year,$mon+1,$mday,3138$hour,$min,$sec,$tz);3139return%date;3140}31413142sub parse_tag {3143my$tag_id=shift;3144my%tag;3145my@comment;31463147open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3148$tag{'id'} =$tag_id;3149while(my$line= <$fd>) {3150chomp$line;3151if($line=~m/^object ([0-9a-fA-F]{40})$/) {3152$tag{'object'} =$1;3153}elsif($line=~m/^type (.+)$/) {3154$tag{'type'} =$1;3155}elsif($line=~m/^tag (.+)$/) {3156$tag{'name'} =$1;3157}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3158$tag{'author'} =$1;3159$tag{'author_epoch'} =$2;3160$tag{'author_tz'} =$3;3161if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3162$tag{'author_name'} =$1;3163$tag{'author_email'} =$2;3164}else{3165$tag{'author_name'} =$tag{'author'};3166}3167}elsif($line=~m/--BEGIN/) {3168push@comment,$line;3169last;3170}elsif($lineeq"") {3171last;3172}3173}3174push@comment, <$fd>;3175$tag{'comment'} = \@comment;3176close$fdorreturn;3177if(!defined$tag{'name'}) {3178return3179};3180return%tag3181}31823183sub parse_commit_text {3184my($commit_text,$withparents) =@_;3185my@commit_lines=split'\n',$commit_text;3186my%co;31873188pop@commit_lines;# Remove '\0'31893190if(!@commit_lines) {3191return;3192}31933194my$header=shift@commit_lines;3195if($header!~m/^[0-9a-fA-F]{40}/) {3196return;3197}3198($co{'id'},my@parents) =split' ',$header;3199while(my$line=shift@commit_lines) {3200last if$lineeq"\n";3201if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3202$co{'tree'} =$1;3203}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3204push@parents,$1;3205}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3206$co{'author'} = to_utf8($1);3207$co{'author_epoch'} =$2;3208$co{'author_tz'} =$3;3209if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3210$co{'author_name'} =$1;3211$co{'author_email'} =$2;3212}else{3213$co{'author_name'} =$co{'author'};3214}3215}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3216$co{'committer'} = to_utf8($1);3217$co{'committer_epoch'} =$2;3218$co{'committer_tz'} =$3;3219if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3220$co{'committer_name'} =$1;3221$co{'committer_email'} =$2;3222}else{3223$co{'committer_name'} =$co{'committer'};3224}3225}3226}3227if(!defined$co{'tree'}) {3228return;3229};3230$co{'parents'} = \@parents;3231$co{'parent'} =$parents[0];32323233foreachmy$title(@commit_lines) {3234$title=~s/^ //;3235if($titlene"") {3236$co{'title'} = chop_str($title,80,5);3237# remove leading stuff of merges to make the interesting part visible3238if(length($title) >50) {3239$title=~s/^Automatic //;3240$title=~s/^merge (of|with) /Merge ... /i;3241if(length($title) >50) {3242$title=~s/(http|rsync):\/\///;3243}3244if(length($title) >50) {3245$title=~s/(master|www|rsync)\.//;3246}3247if(length($title) >50) {3248$title=~s/kernel.org:?//;3249}3250if(length($title) >50) {3251$title=~s/\/pub\/scm//;3252}3253}3254$co{'title_short'} = chop_str($title,50,5);3255last;3256}3257}3258if(!defined$co{'title'} ||$co{'title'}eq"") {3259$co{'title'} =$co{'title_short'} ='(no commit message)';3260}3261# remove added spaces3262foreachmy$line(@commit_lines) {3263$line=~s/^ //;3264}3265$co{'comment'} = \@commit_lines;32663267my$age=time-$co{'committer_epoch'};3268$co{'age'} =$age;3269$co{'age_string'} = age_string($age);3270my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3271if($age>60*60*24*7*2) {3272$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3273$co{'age_string_age'} =$co{'age_string'};3274}else{3275$co{'age_string_date'} =$co{'age_string'};3276$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3277}3278return%co;3279}32803281sub parse_commit {3282my($commit_id) =@_;3283my%co;32843285local$/="\0";32863287open my$fd,"-|", git_cmd(),"rev-list",3288"--parents",3289"--header",3290"--max-count=1",3291$commit_id,3292"--",3293or die_error(500,"Open git-rev-list failed");3294%co= parse_commit_text(<$fd>,1);3295close$fd;32963297return%co;3298}32993300sub parse_commits {3301my($commit_id,$maxcount,$skip,$filename,@args) =@_;3302my@cos;33033304$maxcount||=1;3305$skip||=0;33063307local$/="\0";33083309open my$fd,"-|", git_cmd(),"rev-list",3310"--header",3311@args,3312("--max-count=".$maxcount),3313("--skip=".$skip),3314@extra_options,3315$commit_id,3316"--",3317($filename? ($filename) : ())3318or die_error(500,"Open git-rev-list failed");3319while(my$line= <$fd>) {3320my%co= parse_commit_text($line);3321push@cos, \%co;3322}3323close$fd;33243325returnwantarray?@cos: \@cos;3326}33273328# parse line of git-diff-tree "raw" output3329sub parse_difftree_raw_line {3330my$line=shift;3331my%res;33323333# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3334# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3335if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3336$res{'from_mode'} =$1;3337$res{'to_mode'} =$2;3338$res{'from_id'} =$3;3339$res{'to_id'} =$4;3340$res{'status'} =$5;3341$res{'similarity'} =$6;3342if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3343($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3344}else{3345$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3346}3347}3348# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3349# combined diff (for merge commit)3350elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3351$res{'nparents'} =length($1);3352$res{'from_mode'} = [split(' ',$2) ];3353$res{'to_mode'} =pop@{$res{'from_mode'}};3354$res{'from_id'} = [split(' ',$3) ];3355$res{'to_id'} =pop@{$res{'from_id'}};3356$res{'status'} = [split('',$4) ];3357$res{'to_file'} = unquote($5);3358}3359# 'c512b523472485aef4fff9e57b229d9d243c967f'3360elsif($line=~m/^([0-9a-fA-F]{40})$/) {3361$res{'commit'} =$1;3362}33633364returnwantarray?%res: \%res;3365}33663367# wrapper: return parsed line of git-diff-tree "raw" output3368# (the argument might be raw line, or parsed info)3369sub parsed_difftree_line {3370my$line_or_ref=shift;33713372if(ref($line_or_ref)eq"HASH") {3373# pre-parsed (or generated by hand)3374return$line_or_ref;3375}else{3376return parse_difftree_raw_line($line_or_ref);3377}3378}33793380# parse line of git-ls-tree output3381sub parse_ls_tree_line {3382my$line=shift;3383my%opts=@_;3384my%res;33853386if($opts{'-l'}) {3387#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3388$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;33893390$res{'mode'} =$1;3391$res{'type'} =$2;3392$res{'hash'} =$3;3393$res{'size'} =$4;3394if($opts{'-z'}) {3395$res{'name'} =$5;3396}else{3397$res{'name'} = unquote($5);3398}3399}else{3400#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3401$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;34023403$res{'mode'} =$1;3404$res{'type'} =$2;3405$res{'hash'} =$3;3406if($opts{'-z'}) {3407$res{'name'} =$4;3408}else{3409$res{'name'} = unquote($4);3410}3411}34123413returnwantarray?%res: \%res;3414}34153416# generates _two_ hashes, references to which are passed as 2 and 3 argument3417sub parse_from_to_diffinfo {3418my($diffinfo,$from,$to,@parents) =@_;34193420if($diffinfo->{'nparents'}) {3421# combined diff3422$from->{'file'} = [];3423$from->{'href'} = [];3424 fill_from_file_info($diffinfo,@parents)3425unlessexists$diffinfo->{'from_file'};3426for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3427$from->{'file'}[$i] =3428defined$diffinfo->{'from_file'}[$i] ?3429$diffinfo->{'from_file'}[$i] :3430$diffinfo->{'to_file'};3431if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3432$from->{'href'}[$i] = href(action=>"blob",3433 hash_base=>$parents[$i],3434 hash=>$diffinfo->{'from_id'}[$i],3435 file_name=>$from->{'file'}[$i]);3436}else{3437$from->{'href'}[$i] =undef;3438}3439}3440}else{3441# ordinary (not combined) diff3442$from->{'file'} =$diffinfo->{'from_file'};3443if($diffinfo->{'status'}ne"A") {# not new (added) file3444$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3445 hash=>$diffinfo->{'from_id'},3446 file_name=>$from->{'file'});3447}else{3448delete$from->{'href'};3449}3450}34513452$to->{'file'} =$diffinfo->{'to_file'};3453if(!is_deleted($diffinfo)) {# file exists in result3454$to->{'href'} = href(action=>"blob", hash_base=>$hash,3455 hash=>$diffinfo->{'to_id'},3456 file_name=>$to->{'file'});3457}else{3458delete$to->{'href'};3459}3460}34613462## ......................................................................3463## parse to array of hashes functions34643465sub git_get_heads_list {3466my($limit,@classes) =@_;3467@classes= ('heads')unless@classes;3468my@patterns=map{"refs/$_"}@classes;3469my@headslist;34703471open my$fd,'-|', git_cmd(),'for-each-ref',3472($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3473'--format=%(objectname) %(refname) %(subject)%00%(committer)',3474@patterns3475orreturn;3476while(my$line= <$fd>) {3477my%ref_item;34783479chomp$line;3480my($refinfo,$committerinfo) =split(/\0/,$line);3481my($hash,$name,$title) =split(' ',$refinfo,3);3482my($committer,$epoch,$tz) =3483($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3484$ref_item{'fullname'} =$name;3485$name=~s!^refs/(?:head|remote)s/!!;34863487$ref_item{'name'} =$name;3488$ref_item{'id'} =$hash;3489$ref_item{'title'} =$title||'(no commit message)';3490$ref_item{'epoch'} =$epoch;3491if($epoch) {3492$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3493}else{3494$ref_item{'age'} ="unknown";3495}34963497push@headslist, \%ref_item;3498}3499close$fd;35003501returnwantarray?@headslist: \@headslist;3502}35033504sub git_get_tags_list {3505my$limit=shift;3506my@tagslist;35073508open my$fd,'-|', git_cmd(),'for-each-ref',3509($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3510'--format=%(objectname) %(objecttype) %(refname) '.3511'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3512'refs/tags'3513orreturn;3514while(my$line= <$fd>) {3515my%ref_item;35163517chomp$line;3518my($refinfo,$creatorinfo) =split(/\0/,$line);3519my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3520my($creator,$epoch,$tz) =3521($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3522$ref_item{'fullname'} =$name;3523$name=~s!^refs/tags/!!;35243525$ref_item{'type'} =$type;3526$ref_item{'id'} =$id;3527$ref_item{'name'} =$name;3528if($typeeq"tag") {3529$ref_item{'subject'} =$title;3530$ref_item{'reftype'} =$reftype;3531$ref_item{'refid'} =$refid;3532}else{3533$ref_item{'reftype'} =$type;3534$ref_item{'refid'} =$id;3535}35363537if($typeeq"tag"||$typeeq"commit") {3538$ref_item{'epoch'} =$epoch;3539if($epoch) {3540$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3541}else{3542$ref_item{'age'} ="unknown";3543}3544}35453546push@tagslist, \%ref_item;3547}3548close$fd;35493550returnwantarray?@tagslist: \@tagslist;3551}35523553## ----------------------------------------------------------------------3554## filesystem-related functions35553556sub get_file_owner {3557my$path=shift;35583559my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3560my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3561if(!defined$gcos) {3562returnundef;3563}3564my$owner=$gcos;3565$owner=~s/[,;].*$//;3566return to_utf8($owner);3567}35683569# assume that file exists3570sub insert_file {3571my$filename=shift;35723573open my$fd,'<',$filename;3574print map{ to_utf8($_) } <$fd>;3575close$fd;3576}35773578## ......................................................................3579## mimetype related functions35803581sub mimetype_guess_file {3582my$filename=shift;3583my$mimemap=shift;3584-r $mimemaporreturnundef;35853586my%mimemap;3587open(my$mh,'<',$mimemap)orreturnundef;3588while(<$mh>) {3589next ifm/^#/;# skip comments3590my($mimetype,@exts) =split(/\s+/);3591foreachmy$ext(@exts) {3592$mimemap{$ext} =$mimetype;3593}3594}3595close($mh);35963597$filename=~/\.([^.]*)$/;3598return$mimemap{$1};3599}36003601sub mimetype_guess {3602my$filename=shift;3603my$mime;3604$filename=~/\./orreturnundef;36053606if($mimetypes_file) {3607my$file=$mimetypes_file;3608if($file!~m!^/!) {# if it is relative path3609# it is relative to project3610$file="$projectroot/$project/$file";3611}3612$mime= mimetype_guess_file($filename,$file);3613}3614$mime||= mimetype_guess_file($filename,'/etc/mime.types');3615return$mime;3616}36173618sub blob_mimetype {3619my$fd=shift;3620my$filename=shift;36213622if($filename) {3623my$mime= mimetype_guess($filename);3624$mimeandreturn$mime;3625}36263627# just in case3628return$default_blob_plain_mimetypeunless$fd;36293630if(-T $fd) {3631return'text/plain';3632}elsif(!$filename) {3633return'application/octet-stream';3634}elsif($filename=~m/\.png$/i) {3635return'image/png';3636}elsif($filename=~m/\.gif$/i) {3637return'image/gif';3638}elsif($filename=~m/\.jpe?g$/i) {3639return'image/jpeg';3640}else{3641return'application/octet-stream';3642}3643}36443645sub blob_contenttype {3646my($fd,$file_name,$type) =@_;36473648$type||= blob_mimetype($fd,$file_name);3649if($typeeq'text/plain'&&defined$default_text_plain_charset) {3650$type.="; charset=$default_text_plain_charset";3651}36523653return$type;3654}36553656# guess file syntax for syntax highlighting; return undef if no highlighting3657# the name of syntax can (in the future) depend on syntax highlighter used3658sub guess_file_syntax {3659my($highlight,$mimetype,$file_name) =@_;3660returnundefunless($highlight&&defined$file_name);3661my$basename= basename($file_name,'.in');3662return$highlight_basename{$basename}3663ifexists$highlight_basename{$basename};36643665$basename=~/\.([^.]*)$/;3666my$ext=$1orreturnundef;3667return$highlight_ext{$ext}3668ifexists$highlight_ext{$ext};36693670returnundef;3671}36723673# run highlighter and return FD of its output,3674# or return original FD if no highlighting3675sub run_highlighter {3676my($fd,$highlight,$syntax) =@_;3677return$fdunless($highlight&&defined$syntax);36783679close$fd;3680open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3681 quote_command($highlight_bin).3682" --replace-tabs=8 --fragment --syntax$syntax|"3683or die_error(500,"Couldn't open file or run syntax highlighter");3684return$fd;3685}36863687## ======================================================================3688## functions printing HTML: header, footer, error page36893690sub get_page_title {3691my$title= to_utf8($site_name);36923693return$titleunless(defined$project);3694$title.=" - ". to_utf8($project);36953696return$titleunless(defined$action);3697$title.="/$action";# $action is US-ASCII (7bit ASCII)36983699return$titleunless(defined$file_name);3700$title.=" - ". esc_path($file_name);3701if($actioneq"tree"&&$file_name!~ m|/$|) {3702$title.="/";3703}37043705return$title;3706}37073708sub get_content_type_html {3709# require explicit support from the UA if we are to send the page as3710# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3711# we have to do this because MSIE sometimes globs '*/*', pretending to3712# support xhtml+xml but choking when it gets what it asked for.3713if(defined$cgi->http('HTTP_ACCEPT') &&3714$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3715$cgi->Accept('application/xhtml+xml') !=0) {3716return'application/xhtml+xml';3717}else{3718return'text/html';3719}3720}37213722sub print_feed_meta {3723if(defined$project) {3724my%href_params= get_feed_info();3725if(!exists$href_params{'-title'}) {3726$href_params{'-title'} ='log';3727}37283729foreachmy$format(qw(RSS Atom)) {3730my$type=lc($format);3731my%link_attr= (3732'-rel'=>'alternate',3733'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3734'-type'=>"application/$type+xml"3735);37363737$href_params{'action'} =$type;3738$link_attr{'-href'} = href(%href_params);3739print"<link ".3740"rel=\"$link_attr{'-rel'}\"".3741"title=\"$link_attr{'-title'}\"".3742"href=\"$link_attr{'-href'}\"".3743"type=\"$link_attr{'-type'}\"".3744"/>\n";37453746$href_params{'extra_options'} ='--no-merges';3747$link_attr{'-href'} = href(%href_params);3748$link_attr{'-title'} .=' (no merges)';3749print"<link ".3750"rel=\"$link_attr{'-rel'}\"".3751"title=\"$link_attr{'-title'}\"".3752"href=\"$link_attr{'-href'}\"".3753"type=\"$link_attr{'-type'}\"".3754"/>\n";3755}37563757}else{3758printf('<link rel="alternate" title="%sprojects list" '.3759'href="%s" type="text/plain; charset=utf-8" />'."\n",3760 esc_attr($site_name), href(project=>undef, action=>"project_index"));3761printf('<link rel="alternate" title="%sprojects feeds" '.3762'href="%s" type="text/x-opml" />'."\n",3763 esc_attr($site_name), href(project=>undef, action=>"opml"));3764}3765}37663767sub print_header_links {3768my$status=shift;37693770# print out each stylesheet that exist, providing backwards capability3771# for those people who defined $stylesheet in a config file3772if(defined$stylesheet) {3773print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3774}else{3775foreachmy$stylesheet(@stylesheets) {3776next unless$stylesheet;3777print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3778}3779}3780 print_feed_meta()3781if($statuseq'200 OK');3782if(defined$favicon) {3783printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);3784}3785}37863787sub print_nav_breadcrumbs {3788my%opts=@_;37893790print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3791if(defined$project) {3792print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3793if(defined$action) {3794my$action_print=$action;3795if(defined$opts{-action_extra}) {3796$action_print=$cgi->a({-href => href(action=>$action)},3797$action);3798}3799print" /$action_print";3800}3801if(defined$opts{-action_extra}) {3802print" /$opts{-action_extra}";3803}3804print"\n";3805}3806}38073808sub print_search_form {3809if(!defined$searchtext) {3810$searchtext="";3811}3812my$search_hash;3813if(defined$hash_base) {3814$search_hash=$hash_base;3815}elsif(defined$hash) {3816$search_hash=$hash;3817}else{3818$search_hash="HEAD";3819}3820my$action=$my_uri;3821my$use_pathinfo= gitweb_check_feature('pathinfo');3822if($use_pathinfo) {3823$action.="/".esc_url($project);3824}3825print$cgi->startform(-method=>"get", -action =>$action) .3826"<div class=\"search\">\n".3827(!$use_pathinfo&&3828$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3829$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3830$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3831$cgi->popup_menu(-name =>'st', -default=>'commit',3832-values=> ['commit','grep','author','committer','pickaxe']) .3833$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3834" search:\n",3835$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3836"<span title=\"Extended regular expression\">".3837$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3838-checked =>$search_use_regexp) .3839"</span>".3840"</div>".3841$cgi->end_form() ."\n";3842}38433844sub git_header_html {3845my$status=shift||"200 OK";3846my$expires=shift;3847my%opts=@_;38483849my$title= get_page_title();3850my$content_type= get_content_type_html();3851print$cgi->header(-type=>$content_type, -charset =>'utf-8',3852-status=>$status, -expires =>$expires)3853unless($opts{'-no_http_header'});3854my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3855print<<EOF;3856<?xml version="1.0" encoding="utf-8"?>3857<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3858<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3859<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3860<!-- git core binaries version$git_version-->3861<head>3862<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3863<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3864<meta name="robots" content="index, nofollow"/>3865<title>$title</title>3866EOF3867# the stylesheet, favicon etc urls won't work correctly with path_info3868# unless we set the appropriate base URL3869if($ENV{'PATH_INFO'}) {3870print"<base href=\"".esc_url($base_url)."\"/>\n";3871}3872 print_header_links($status);38733874if(defined$site_html_head_string) {3875print to_utf8($site_html_head_string);3876}38773878print"</head>\n".3879"<body>\n";38803881if(defined$site_header&& -f $site_header) {3882 insert_file($site_header);3883}38843885print"<div class=\"page_header\">\n";3886if(defined$logo) {3887print$cgi->a({-href => esc_url($logo_url),3888-title =>$logo_label},3889$cgi->img({-src => esc_url($logo),3890-width =>72, -height =>27,3891-alt =>"git",3892-class=>"logo"}));3893}3894 print_nav_breadcrumbs(%opts);3895print"</div>\n";38963897my$have_search= gitweb_check_feature('search');3898if(defined$project&&$have_search) {3899 print_search_form();3900}3901}39023903sub git_footer_html {3904my$feed_class='rss_logo';39053906print"<div class=\"page_footer\">\n";3907if(defined$project) {3908my$descr= git_get_project_description($project);3909if(defined$descr) {3910print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3911}39123913my%href_params= get_feed_info();3914if(!%href_params) {3915$feed_class.=' generic';3916}3917$href_params{'-title'} ||='log';39183919foreachmy$format(qw(RSS Atom)) {3920$href_params{'action'} =lc($format);3921print$cgi->a({-href => href(%href_params),3922-title =>"$href_params{'-title'}$formatfeed",3923-class=>$feed_class},$format)."\n";3924}39253926}else{3927print$cgi->a({-href => href(project=>undef, action=>"opml"),3928-class=>$feed_class},"OPML") ." ";3929print$cgi->a({-href => href(project=>undef, action=>"project_index"),3930-class=>$feed_class},"TXT") ."\n";3931}3932print"</div>\n";# class="page_footer"39333934if(defined$t0&& gitweb_check_feature('timed')) {3935print"<div id=\"generating_info\">\n";3936print'This page took '.3937'<span id="generating_time" class="time_span">'.3938 tv_interval($t0, [ gettimeofday() ]).3939' seconds </span>'.3940' and '.3941'<span id="generating_cmd">'.3942$number_of_git_cmds.3943'</span> git commands '.3944" to generate.\n";3945print"</div>\n";# class="page_footer"3946}39473948if(defined$site_footer&& -f $site_footer) {3949 insert_file($site_footer);3950}39513952print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;3953if(defined$action&&3954$actioneq'blame_incremental') {3955print qq!<script type="text/javascript">\n!.3956 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.3957 qq!"!. href() .qq!");\n!.3958 qq!</script>\n!;3959}else{3960my($jstimezone,$tz_cookie,$datetime_class) =3961 gitweb_get_feature('javascript-timezone');39623963print qq!<script type="text/javascript">\n!.3964 qq!window.onload = function () {\n!;3965if(gitweb_check_feature('javascript-actions')) {3966print qq! fixLinks();\n!;3967}3968if($jstimezone&&$tz_cookie&&$datetime_class) {3969print qq! var tz_cookie = { name:'$tz_cookie', expires:14, path:'/'};\n!.# in days3970 qq! onloadTZSetup('$jstimezone', tz_cookie,'$datetime_class');\n!;3971}3972print qq!};\n!.3973 qq!</script>\n!;3974}39753976print"</body>\n".3977"</html>";3978}39793980# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])3981# Example: die_error(404, 'Hash not found')3982# By convention, use the following status codes (as defined in RFC 2616):3983# 400: Invalid or missing CGI parameters, or3984# requested object exists but has wrong type.3985# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3986# this server or project.3987# 404: Requested object/revision/project doesn't exist.3988# 500: The server isn't configured properly, or3989# an internal error occurred (e.g. failed assertions caused by bugs), or3990# an unknown error occurred (e.g. the git binary died unexpectedly).3991# 503: The server is currently unavailable (because it is overloaded,3992# or down for maintenance). Generally, this is a temporary state.3993sub die_error {3994my$status=shift||500;3995my$error= esc_html(shift) ||"Internal Server Error";3996my$extra=shift;3997my%opts=@_;39983999my%http_responses= (4000400=>'400 Bad Request',4001403=>'403 Forbidden',4002404=>'404 Not Found',4003500=>'500 Internal Server Error',4004503=>'503 Service Unavailable',4005);4006 git_header_html($http_responses{$status},undef,%opts);4007print<<EOF;4008<div class="page_body">4009<br /><br />4010$status-$error4011<br />4012EOF4013if(defined$extra) {4014print"<hr />\n".4015"$extra\n";4016}4017print"</div>\n";40184019 git_footer_html();4020goto DONE_GITWEB4021unless($opts{'-error_handler'});4022}40234024## ----------------------------------------------------------------------4025## functions printing or outputting HTML: navigation40264027sub git_print_page_nav {4028my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;4029$extra=''if!defined$extra;# pager or formats40304031my@navs=qw(summary shortlog log commit commitdiff tree);4032if($suppress) {4033@navs=grep{$_ne$suppress}@navs;4034}40354036my%arg=map{$_=> {action=>$_} }@navs;4037if(defined$head) {4038for(qw(commit commitdiff)) {4039$arg{$_}{'hash'} =$head;4040}4041if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {4042for(qw(shortlog log)) {4043$arg{$_}{'hash'} =$head;4044}4045}4046}40474048$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;4049$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;40504051my@actions= gitweb_get_feature('actions');4052my%repl= (4053'%'=>'%',4054'n'=>$project,# project name4055'f'=>$git_dir,# project path within filesystem4056'h'=>$treehead||'',# current hash ('h' parameter)4057'b'=>$treebase||'',# hash base ('hb' parameter)4058);4059while(@actions) {4060my($label,$link,$pos) =splice(@actions,0,3);4061# insert4062@navs=map{$_eq$pos? ($_,$label) :$_}@navs;4063# munch munch4064$link=~s/%([%nfhb])/$repl{$1}/g;4065$arg{$label}{'_href'} =$link;4066}40674068print"<div class=\"page_nav\">\n".4069(join" | ",4070map{$_eq$current?4071$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4072}@navs);4073print"<br/>\n$extra<br/>\n".4074"</div>\n";4075}40764077# returns a submenu for the nagivation of the refs views (tags, heads,4078# remotes) with the current view disabled and the remotes view only4079# available if the feature is enabled4080sub format_ref_views {4081my($current) =@_;4082my@ref_views=qw{tags heads};4083push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4084returnjoin" | ",map{4085$_eq$current?$_:4086$cgi->a({-href => href(action=>$_)},$_)4087}@ref_views4088}40894090sub format_paging_nav {4091my($action,$page,$has_next_link) =@_;4092my$paging_nav;409340944095if($page>0) {4096$paging_nav.=4097$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4098" ⋅ ".4099$cgi->a({-href => href(-replay=>1, page=>$page-1),4100-accesskey =>"p", -title =>"Alt-p"},"prev");4101}else{4102$paging_nav.="first ⋅ prev";4103}41044105if($has_next_link) {4106$paging_nav.=" ⋅ ".4107$cgi->a({-href => href(-replay=>1, page=>$page+1),4108-accesskey =>"n", -title =>"Alt-n"},"next");4109}else{4110$paging_nav.=" ⋅ next";4111}41124113return$paging_nav;4114}41154116## ......................................................................4117## functions printing or outputting HTML: div41184119sub git_print_header_div {4120my($action,$title,$hash,$hash_base) =@_;4121my%args= ();41224123$args{'action'} =$action;4124$args{'hash'} =$hashif$hash;4125$args{'hash_base'} =$hash_baseif$hash_base;41264127print"<div class=\"header\">\n".4128$cgi->a({-href => href(%args), -class=>"title"},4129$title?$title:$action) .4130"\n</div>\n";4131}41324133sub format_repo_url {4134my($name,$url) =@_;4135return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4136}41374138# Group output by placing it in a DIV element and adding a header.4139# Options for start_div() can be provided by passing a hash reference as the4140# first parameter to the function.4141# Options to git_print_header_div() can be provided by passing an array4142# reference. This must follow the options to start_div if they are present.4143# The content can be a scalar, which is output as-is, a scalar reference, which4144# is output after html escaping, an IO handle passed either as *handle or4145# *handle{IO}, or a function reference. In the latter case all following4146# parameters will be taken as argument to the content function call.4147sub git_print_section {4148my($div_args,$header_args,$content);4149my$arg=shift;4150if(ref($arg)eq'HASH') {4151$div_args=$arg;4152$arg=shift;4153}4154if(ref($arg)eq'ARRAY') {4155$header_args=$arg;4156$arg=shift;4157}4158$content=$arg;41594160print$cgi->start_div($div_args);4161 git_print_header_div(@$header_args);41624163if(ref($content)eq'CODE') {4164$content->(@_);4165}elsif(ref($content)eq'SCALAR') {4166print esc_html($$content);4167}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4168print<$content>;4169}elsif(!ref($content) &&defined($content)) {4170print$content;4171}41724173print$cgi->end_div;4174}41754176sub format_timestamp_html {4177my$date=shift;4178my$strtime=$date->{'rfc2822'};41794180my(undef,undef,$datetime_class) =4181 gitweb_get_feature('javascript-timezone');4182if($datetime_class) {4183$strtime= qq!<span class="$datetime_class">$strtime</span>!;4184}41854186my$localtime_format='(%02d:%02d%s)';4187if($date->{'hour_local'} <6) {4188$localtime_format='(<span class="atnight">%02d:%02d</span>%s)';4189}4190$strtime.=' '.4191sprintf($localtime_format,4192$date->{'hour_local'},$date->{'minute_local'},$date->{'tz_local'});41934194return$strtime;4195}41964197# Outputs the author name and date in long form4198sub git_print_authorship {4199my$co=shift;4200my%opts=@_;4201my$tag=$opts{-tag} ||'div';4202my$author=$co->{'author_name'};42034204my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4205print"<$tagclass=\"author_date\">".4206 format_search_author($author,"author", esc_html($author)) .4207" [".format_timestamp_html(\%ad)."]".4208 git_get_avatar($co->{'author_email'}, -pad_before =>1) .4209"</$tag>\n";4210}42114212# Outputs table rows containing the full author or committer information,4213# in the format expected for 'commit' view (& similar).4214# Parameters are a commit hash reference, followed by the list of people4215# to output information for. If the list is empty it defaults to both4216# author and committer.4217sub git_print_authorship_rows {4218my$co=shift;4219# too bad we can't use @people = @_ || ('author', 'committer')4220my@people=@_;4221@people= ('author','committer')unless@people;4222foreachmy$who(@people) {4223my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4224print"<tr><td>$who</td><td>".4225 format_search_author($co->{"${who}_name"},$who,4226 esc_html($co->{"${who}_name"})) ." ".4227 format_search_author($co->{"${who}_email"},$who,4228 esc_html("<".$co->{"${who}_email"} .">")) .4229"</td><td rowspan=\"2\">".4230 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4231"</td></tr>\n".4232"<tr>".4233"<td></td><td>".4234 format_timestamp_html(\%wd) .4235"</td>".4236"</tr>\n";4237}4238}42394240sub git_print_page_path {4241my$name=shift;4242my$type=shift;4243my$hb=shift;424442454246print"<div class=\"page_path\">";4247print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4248-title =>'tree root'}, to_utf8("[$project]"));4249print" / ";4250if(defined$name) {4251my@dirname=split'/',$name;4252my$basename=pop@dirname;4253my$fullname='';42544255foreachmy$dir(@dirname) {4256$fullname.= ($fullname?'/':'') .$dir;4257print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4258 hash_base=>$hb),4259-title =>$fullname}, esc_path($dir));4260print" / ";4261}4262if(defined$type&&$typeeq'blob') {4263print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4264 hash_base=>$hb),4265-title =>$name}, esc_path($basename));4266}elsif(defined$type&&$typeeq'tree') {4267print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4268 hash_base=>$hb),4269-title =>$name}, esc_path($basename));4270print" / ";4271}else{4272print esc_path($basename);4273}4274}4275print"<br/></div>\n";4276}42774278sub git_print_log {4279my$log=shift;4280my%opts=@_;42814282if($opts{'-remove_title'}) {4283# remove title, i.e. first line of log4284shift@$log;4285}4286# remove leading empty lines4287while(defined$log->[0] &&$log->[0]eq"") {4288shift@$log;4289}42904291# print log4292my$signoff=0;4293my$empty=0;4294foreachmy$line(@$log) {4295if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {4296$signoff=1;4297$empty=0;4298if(!$opts{'-remove_signoff'}) {4299print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4300next;4301}else{4302# remove signoff lines4303next;4304}4305}else{4306$signoff=0;4307}43084309# print only one empty line4310# do not print empty line after signoff4311if($lineeq"") {4312next if($empty||$signoff);4313$empty=1;4314}else{4315$empty=0;4316}43174318print format_log_line_html($line) ."<br/>\n";4319}43204321if($opts{'-final_empty_line'}) {4322# end with single empty line4323print"<br/>\n"unless$empty;4324}4325}43264327# return link target (what link points to)4328sub git_get_link_target {4329my$hash=shift;4330my$link_target;43314332# read link4333open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4334orreturn;4335{4336local$/=undef;4337$link_target= <$fd>;4338}4339close$fd4340orreturn;43414342return$link_target;4343}43444345# given link target, and the directory (basedir) the link is in,4346# return target of link relative to top directory (top tree);4347# return undef if it is not possible (including absolute links).4348sub normalize_link_target {4349my($link_target,$basedir) =@_;43504351# absolute symlinks (beginning with '/') cannot be normalized4352return if(substr($link_target,0,1)eq'/');43534354# normalize link target to path from top (root) tree (dir)4355my$path;4356if($basedir) {4357$path=$basedir.'/'.$link_target;4358}else{4359# we are in top (root) tree (dir)4360$path=$link_target;4361}43624363# remove //, /./, and /../4364my@path_parts;4365foreachmy$part(split('/',$path)) {4366# discard '.' and ''4367next if(!$part||$parteq'.');4368# handle '..'4369if($parteq'..') {4370if(@path_parts) {4371pop@path_parts;4372}else{4373# link leads outside repository (outside top dir)4374return;4375}4376}else{4377push@path_parts,$part;4378}4379}4380$path=join('/',@path_parts);43814382return$path;4383}43844385# print tree entry (row of git_tree), but without encompassing <tr> element4386sub git_print_tree_entry {4387my($t,$basedir,$hash_base,$have_blame) =@_;43884389my%base_key= ();4390$base_key{'hash_base'} =$hash_baseifdefined$hash_base;43914392# The format of a table row is: mode list link. Where mode is4393# the mode of the entry, list is the name of the entry, an href,4394# and link is the action links of the entry.43954396print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4397if(exists$t->{'size'}) {4398print"<td class=\"size\">$t->{'size'}</td>\n";4399}4400if($t->{'type'}eq"blob") {4401print"<td class=\"list\">".4402$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4403 file_name=>"$basedir$t->{'name'}",%base_key),4404-class=>"list"}, esc_path($t->{'name'}));4405if(S_ISLNK(oct$t->{'mode'})) {4406my$link_target= git_get_link_target($t->{'hash'});4407if($link_target) {4408my$norm_target= normalize_link_target($link_target,$basedir);4409if(defined$norm_target) {4410print" -> ".4411$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4412 file_name=>$norm_target),4413-title =>$norm_target}, esc_path($link_target));4414}else{4415print" -> ". esc_path($link_target);4416}4417}4418}4419print"</td>\n";4420print"<td class=\"link\">";4421print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4422 file_name=>"$basedir$t->{'name'}",%base_key)},4423"blob");4424if($have_blame) {4425print" | ".4426$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4427 file_name=>"$basedir$t->{'name'}",%base_key)},4428"blame");4429}4430if(defined$hash_base) {4431print" | ".4432$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4433 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4434"history");4435}4436print" | ".4437$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4438 file_name=>"$basedir$t->{'name'}")},4439"raw");4440print"</td>\n";44414442}elsif($t->{'type'}eq"tree") {4443print"<td class=\"list\">";4444print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4445 file_name=>"$basedir$t->{'name'}",4446%base_key)},4447 esc_path($t->{'name'}));4448print"</td>\n";4449print"<td class=\"link\">";4450print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4451 file_name=>"$basedir$t->{'name'}",4452%base_key)},4453"tree");4454if(defined$hash_base) {4455print" | ".4456$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4457 file_name=>"$basedir$t->{'name'}")},4458"history");4459}4460print"</td>\n";4461}else{4462# unknown object: we can only present history for it4463# (this includes 'commit' object, i.e. submodule support)4464print"<td class=\"list\">".4465 esc_path($t->{'name'}) .4466"</td>\n";4467print"<td class=\"link\">";4468if(defined$hash_base) {4469print$cgi->a({-href => href(action=>"history",4470 hash_base=>$hash_base,4471 file_name=>"$basedir$t->{'name'}")},4472"history");4473}4474print"</td>\n";4475}4476}44774478## ......................................................................4479## functions printing large fragments of HTML44804481# get pre-image filenames for merge (combined) diff4482sub fill_from_file_info {4483my($diff,@parents) =@_;44844485$diff->{'from_file'} = [ ];4486$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4487for(my$i=0;$i<$diff->{'nparents'};$i++) {4488if($diff->{'status'}[$i]eq'R'||4489$diff->{'status'}[$i]eq'C') {4490$diff->{'from_file'}[$i] =4491 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4492}4493}44944495return$diff;4496}44974498# is current raw difftree line of file deletion4499sub is_deleted {4500my$diffinfo=shift;45014502return$diffinfo->{'to_id'}eq('0' x 40);4503}45044505# does patch correspond to [previous] difftree raw line4506# $diffinfo - hashref of parsed raw diff format4507# $patchinfo - hashref of parsed patch diff format4508# (the same keys as in $diffinfo)4509sub is_patch_split {4510my($diffinfo,$patchinfo) =@_;45114512returndefined$diffinfo&&defined$patchinfo4513&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4514}451545164517sub git_difftree_body {4518my($difftree,$hash,@parents) =@_;4519my($parent) =$parents[0];4520my$have_blame= gitweb_check_feature('blame');4521print"<div class=\"list_head\">\n";4522if($#{$difftree} >10) {4523print(($#{$difftree} +1) ." files changed:\n");4524}4525print"</div>\n";45264527print"<table class=\"".4528(@parents>1?"combined ":"") .4529"diff_tree\">\n";45304531# header only for combined diff in 'commitdiff' view4532my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4533if($has_header) {4534# table header4535print"<thead><tr>\n".4536"<th></th><th></th>\n";# filename, patchN link4537for(my$i=0;$i<@parents;$i++) {4538my$par=$parents[$i];4539print"<th>".4540$cgi->a({-href => href(action=>"commitdiff",4541 hash=>$hash, hash_parent=>$par),4542-title =>'commitdiff to parent number '.4543($i+1) .': '.substr($par,0,7)},4544$i+1) .4545" </th>\n";4546}4547print"</tr></thead>\n<tbody>\n";4548}45494550my$alternate=1;4551my$patchno=0;4552foreachmy$line(@{$difftree}) {4553my$diff= parsed_difftree_line($line);45544555if($alternate) {4556print"<tr class=\"dark\">\n";4557}else{4558print"<tr class=\"light\">\n";4559}4560$alternate^=1;45614562if(exists$diff->{'nparents'}) {# combined diff45634564 fill_from_file_info($diff,@parents)4565unlessexists$diff->{'from_file'};45664567if(!is_deleted($diff)) {4568# file exists in the result (child) commit4569print"<td>".4570$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4571 file_name=>$diff->{'to_file'},4572 hash_base=>$hash),4573-class=>"list"}, esc_path($diff->{'to_file'})) .4574"</td>\n";4575}else{4576print"<td>".4577 esc_path($diff->{'to_file'}) .4578"</td>\n";4579}45804581if($actioneq'commitdiff') {4582# link to patch4583$patchno++;4584print"<td class=\"link\">".4585$cgi->a({-href => href(-anchor=>"patch$patchno")},4586"patch") .4587" | ".4588"</td>\n";4589}45904591my$has_history=0;4592my$not_deleted=0;4593for(my$i=0;$i<$diff->{'nparents'};$i++) {4594my$hash_parent=$parents[$i];4595my$from_hash=$diff->{'from_id'}[$i];4596my$from_path=$diff->{'from_file'}[$i];4597my$status=$diff->{'status'}[$i];45984599$has_history||= ($statusne'A');4600$not_deleted||= ($statusne'D');46014602if($statuseq'A') {4603print"<td class=\"link\"align=\"right\"> | </td>\n";4604}elsif($statuseq'D') {4605print"<td class=\"link\">".4606$cgi->a({-href => href(action=>"blob",4607 hash_base=>$hash,4608 hash=>$from_hash,4609 file_name=>$from_path)},4610"blob". ($i+1)) .4611" | </td>\n";4612}else{4613if($diff->{'to_id'}eq$from_hash) {4614print"<td class=\"link nochange\">";4615}else{4616print"<td class=\"link\">";4617}4618print$cgi->a({-href => href(action=>"blobdiff",4619 hash=>$diff->{'to_id'},4620 hash_parent=>$from_hash,4621 hash_base=>$hash,4622 hash_parent_base=>$hash_parent,4623 file_name=>$diff->{'to_file'},4624 file_parent=>$from_path)},4625"diff". ($i+1)) .4626" | </td>\n";4627}4628}46294630print"<td class=\"link\">";4631if($not_deleted) {4632print$cgi->a({-href => href(action=>"blob",4633 hash=>$diff->{'to_id'},4634 file_name=>$diff->{'to_file'},4635 hash_base=>$hash)},4636"blob");4637print" | "if($has_history);4638}4639if($has_history) {4640print$cgi->a({-href => href(action=>"history",4641 file_name=>$diff->{'to_file'},4642 hash_base=>$hash)},4643"history");4644}4645print"</td>\n";46464647print"</tr>\n";4648next;# instead of 'else' clause, to avoid extra indent4649}4650# else ordinary diff46514652my($to_mode_oct,$to_mode_str,$to_file_type);4653my($from_mode_oct,$from_mode_str,$from_file_type);4654if($diff->{'to_mode'}ne('0' x 6)) {4655$to_mode_oct=oct$diff->{'to_mode'};4656if(S_ISREG($to_mode_oct)) {# only for regular file4657$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4658}4659$to_file_type= file_type($diff->{'to_mode'});4660}4661if($diff->{'from_mode'}ne('0' x 6)) {4662$from_mode_oct=oct$diff->{'from_mode'};4663if(S_ISREG($from_mode_oct)) {# only for regular file4664$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4665}4666$from_file_type= file_type($diff->{'from_mode'});4667}46684669if($diff->{'status'}eq"A") {# created4670my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4671$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4672$mode_chng.="]</span>";4673print"<td>";4674print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4675 hash_base=>$hash, file_name=>$diff->{'file'}),4676-class=>"list"}, esc_path($diff->{'file'}));4677print"</td>\n";4678print"<td>$mode_chng</td>\n";4679print"<td class=\"link\">";4680if($actioneq'commitdiff') {4681# link to patch4682$patchno++;4683print$cgi->a({-href => href(-anchor=>"patch$patchno")},4684"patch") .4685" | ";4686}4687print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4688 hash_base=>$hash, file_name=>$diff->{'file'})},4689"blob");4690print"</td>\n";46914692}elsif($diff->{'status'}eq"D") {# deleted4693my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4694print"<td>";4695print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4696 hash_base=>$parent, file_name=>$diff->{'file'}),4697-class=>"list"}, esc_path($diff->{'file'}));4698print"</td>\n";4699print"<td>$mode_chng</td>\n";4700print"<td class=\"link\">";4701if($actioneq'commitdiff') {4702# link to patch4703$patchno++;4704print$cgi->a({-href => href(-anchor=>"patch$patchno")},4705"patch") .4706" | ";4707}4708print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4709 hash_base=>$parent, file_name=>$diff->{'file'})},4710"blob") ." | ";4711if($have_blame) {4712print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4713 file_name=>$diff->{'file'})},4714"blame") ." | ";4715}4716print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4717 file_name=>$diff->{'file'})},4718"history");4719print"</td>\n";47204721}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4722my$mode_chnge="";4723if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4724$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4725if($from_file_typene$to_file_type) {4726$mode_chnge.=" from$from_file_typeto$to_file_type";4727}4728if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4729if($from_mode_str&&$to_mode_str) {4730$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4731}elsif($to_mode_str) {4732$mode_chnge.=" mode:$to_mode_str";4733}4734}4735$mode_chnge.="]</span>\n";4736}4737print"<td>";4738print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4739 hash_base=>$hash, file_name=>$diff->{'file'}),4740-class=>"list"}, esc_path($diff->{'file'}));4741print"</td>\n";4742print"<td>$mode_chnge</td>\n";4743print"<td class=\"link\">";4744if($actioneq'commitdiff') {4745# link to patch4746$patchno++;4747print$cgi->a({-href => href(-anchor=>"patch$patchno")},4748"patch") .4749" | ";4750}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4751# "commit" view and modified file (not onlu mode changed)4752print$cgi->a({-href => href(action=>"blobdiff",4753 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4754 hash_base=>$hash, hash_parent_base=>$parent,4755 file_name=>$diff->{'file'})},4756"diff") .4757" | ";4758}4759print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4760 hash_base=>$hash, file_name=>$diff->{'file'})},4761"blob") ." | ";4762if($have_blame) {4763print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4764 file_name=>$diff->{'file'})},4765"blame") ." | ";4766}4767print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4768 file_name=>$diff->{'file'})},4769"history");4770print"</td>\n";47714772}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4773my%status_name= ('R'=>'moved','C'=>'copied');4774my$nstatus=$status_name{$diff->{'status'}};4775my$mode_chng="";4776if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4777# mode also for directories, so we cannot use $to_mode_str4778$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4779}4780print"<td>".4781$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4782 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4783-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4784"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4785$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4786 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4787-class=>"list"}, esc_path($diff->{'from_file'})) .4788" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4789"<td class=\"link\">";4790if($actioneq'commitdiff') {4791# link to patch4792$patchno++;4793print$cgi->a({-href => href(-anchor=>"patch$patchno")},4794"patch") .4795" | ";4796}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4797# "commit" view and modified file (not only pure rename or copy)4798print$cgi->a({-href => href(action=>"blobdiff",4799 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4800 hash_base=>$hash, hash_parent_base=>$parent,4801 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4802"diff") .4803" | ";4804}4805print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4806 hash_base=>$parent, file_name=>$diff->{'to_file'})},4807"blob") ." | ";4808if($have_blame) {4809print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4810 file_name=>$diff->{'to_file'})},4811"blame") ." | ";4812}4813print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4814 file_name=>$diff->{'to_file'})},4815"history");4816print"</td>\n";48174818}# we should not encounter Unmerged (U) or Unknown (X) status4819print"</tr>\n";4820}4821print"</tbody>"if$has_header;4822print"</table>\n";4823}48244825sub git_patchset_body {4826my($fd,$difftree,$hash,@hash_parents) =@_;4827my($hash_parent) =$hash_parents[0];48284829my$is_combined= (@hash_parents>1);4830my$patch_idx=0;4831my$patch_number=0;4832my$patch_line;4833my$diffinfo;4834my$to_name;4835my(%from,%to);48364837print"<div class=\"patchset\">\n";48384839# skip to first patch4840while($patch_line= <$fd>) {4841chomp$patch_line;48424843last if($patch_line=~m/^diff /);4844}48454846 PATCH:4847while($patch_line) {48484849# parse "git diff" header line4850if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4851# $1 is from_name, which we do not use4852$to_name= unquote($2);4853$to_name=~s!^b/!!;4854}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4855# $1 is 'cc' or 'combined', which we do not use4856$to_name= unquote($2);4857}else{4858$to_name=undef;4859}48604861# check if current patch belong to current raw line4862# and parse raw git-diff line if needed4863if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4864# this is continuation of a split patch4865print"<div class=\"patch cont\">\n";4866}else{4867# advance raw git-diff output if needed4868$patch_idx++ifdefined$diffinfo;48694870# read and prepare patch information4871$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);48724873# compact combined diff output can have some patches skipped4874# find which patch (using pathname of result) we are at now;4875if($is_combined) {4876while($to_namene$diffinfo->{'to_file'}) {4877print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4878 format_diff_cc_simplified($diffinfo,@hash_parents) .4879"</div>\n";# class="patch"48804881$patch_idx++;4882$patch_number++;48834884last if$patch_idx>$#$difftree;4885$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4886}4887}48884889# modifies %from, %to hashes4890 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);48914892# this is first patch for raw difftree line with $patch_idx index4893# we index @$difftree array from 0, but number patches from 14894print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4895}48964897# git diff header4898#assert($patch_line =~ m/^diff /) if DEBUG;4899#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4900$patch_number++;4901# print "git diff" header4902print format_git_diff_header_line($patch_line,$diffinfo,4903 \%from, \%to);49044905# print extended diff header4906print"<div class=\"diff extended_header\">\n";4907 EXTENDED_HEADER:4908while($patch_line= <$fd>) {4909chomp$patch_line;49104911last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);49124913print format_extended_diff_header_line($patch_line,$diffinfo,4914 \%from, \%to);4915}4916print"</div>\n";# class="diff extended_header"49174918# from-file/to-file diff header4919if(!$patch_line) {4920print"</div>\n";# class="patch"4921last PATCH;4922}4923next PATCH if($patch_line=~m/^diff /);4924#assert($patch_line =~ m/^---/) if DEBUG;49254926my$last_patch_line=$patch_line;4927$patch_line= <$fd>;4928chomp$patch_line;4929#assert($patch_line =~ m/^\+\+\+/) if DEBUG;49304931print format_diff_from_to_header($last_patch_line,$patch_line,4932$diffinfo, \%from, \%to,4933@hash_parents);49344935# the patch itself4936 LINE:4937while($patch_line= <$fd>) {4938chomp$patch_line;49394940next PATCH if($patch_line=~m/^diff /);49414942print format_diff_line($patch_line, \%from, \%to);4943}49444945}continue{4946print"</div>\n";# class="patch"4947}49484949# for compact combined (--cc) format, with chunk and patch simplification4950# the patchset might be empty, but there might be unprocessed raw lines4951for(++$patch_idxif$patch_number>0;4952$patch_idx<@$difftree;4953++$patch_idx) {4954# read and prepare patch information4955$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);49564957# generate anchor for "patch" links in difftree / whatchanged part4958print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4959 format_diff_cc_simplified($diffinfo,@hash_parents) .4960"</div>\n";# class="patch"49614962$patch_number++;4963}49644965if($patch_number==0) {4966if(@hash_parents>1) {4967print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4968}else{4969print"<div class=\"diff nodifferences\">No differences found</div>\n";4970}4971}49724973print"</div>\n";# class="patchset"4974}49754976# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49774978# fills project list info (age, description, owner, category, forks)4979# for each project in the list, removing invalid projects from4980# returned list4981# NOTE: modifies $projlist, but does not remove entries from it4982sub fill_project_list_info {4983my$projlist=shift;4984my@projects;49854986my$show_ctags= gitweb_check_feature('ctags');4987 PROJECT:4988foreachmy$pr(@$projlist) {4989my(@activity) = git_get_last_activity($pr->{'path'});4990unless(@activity) {4991next PROJECT;4992}4993($pr->{'age'},$pr->{'age_string'}) =@activity;4994if(!defined$pr->{'descr'}) {4995my$descr= git_get_project_description($pr->{'path'}) ||"";4996$descr= to_utf8($descr);4997$pr->{'descr_long'} =$descr;4998$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);4999}5000if(!defined$pr->{'owner'}) {5001$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";5002}5003if($show_ctags) {5004$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});5005}5006if($projects_list_group_categories&& !defined$pr->{'category'}) {5007my$cat= git_get_project_category($pr->{'path'}) ||5008$project_list_default_category;5009$pr->{'category'} = to_utf8($cat);5010}50115012push@projects,$pr;5013}50145015return@projects;5016}50175018sub sort_projects_list {5019my($projlist,$order) =@_;5020my@projects;50215022my%order_info= (5023 project => { key =>'path', type =>'str'},5024 descr => { key =>'descr_long', type =>'str'},5025 owner => { key =>'owner', type =>'str'},5026 age => { key =>'age', type =>'num'}5027);5028my$oi=$order_info{$order};5029return@$projlistunlessdefined$oi;5030if($oi->{'type'}eq'str') {5031@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@$projlist;5032}else{5033@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@$projlist;5034}50355036return@projects;5037}50385039# returns a hash of categories, containing the list of project5040# belonging to each category5041sub build_projlist_by_category {5042my($projlist,$from,$to) =@_;5043my%categories;50445045$from=0unlessdefined$from;5046$to=$#$projlistif(!defined$to||$#$projlist<$to);50475048for(my$i=$from;$i<=$to;$i++) {5049my$pr=$projlist->[$i];5050push@{$categories{$pr->{'category'} }},$pr;5051}50525053returnwantarray?%categories: \%categories;5054}50555056# print 'sort by' <th> element, generating 'sort by $name' replay link5057# if that order is not selected5058sub print_sort_th {5059print format_sort_th(@_);5060}50615062sub format_sort_th {5063my($name,$order,$header) =@_;5064my$sort_th="";5065$header||=ucfirst($name);50665067if($ordereq$name) {5068$sort_th.="<th>$header</th>\n";5069}else{5070$sort_th.="<th>".5071$cgi->a({-href => href(-replay=>1, order=>$name),5072-class=>"header"},$header) .5073"</th>\n";5074}50755076return$sort_th;5077}50785079sub git_project_list_rows {5080my($projlist,$from,$to,$check_forks) =@_;50815082$from=0unlessdefined$from;5083$to=$#$projlistif(!defined$to||$#$projlist<$to);50845085my$alternate=1;5086for(my$i=$from;$i<=$to;$i++) {5087my$pr=$projlist->[$i];50885089if($alternate) {5090print"<tr class=\"dark\">\n";5091}else{5092print"<tr class=\"light\">\n";5093}5094$alternate^=1;50955096if($check_forks) {5097print"<td>";5098if($pr->{'forks'}) {5099my$nforks=scalar@{$pr->{'forks'}};5100if($nforks>0) {5101print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5102-title =>"$nforksforks"},"+");5103}else{5104print$cgi->span({-title =>"$nforksforks"},"+");5105}5106}5107print"</td>\n";5108}5109print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5110-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".5111"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5112-class=>"list", -title =>$pr->{'descr_long'}},5113 esc_html($pr->{'descr'})) ."</td>\n".5114"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5115print"<td class=\"". age_class($pr->{'age'}) ."\">".5116(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".5117"<td class=\"link\">".5118$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5119$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5120$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5121$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5122($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5123"</td>\n".5124"</tr>\n";5125}5126}51275128sub git_project_list_body {5129# actually uses global variable $project5130my($projlist,$order,$from,$to,$extra,$no_header) =@_;5131my@projects=@$projlist;51325133my$check_forks= gitweb_check_feature('forks');5134my$show_ctags= gitweb_check_feature('ctags');5135my$tagfilter=$show_ctags?$cgi->param('by_tag') :undef;5136$check_forks=undef5137if($tagfilter||$searchtext);51385139# filtering out forks before filling info allows to do less work5140@projects= filter_forks_from_projects_list(\@projects)5141if($check_forks);5142@projects= fill_project_list_info(\@projects);5143# searching projects require filling to be run before it5144@projects= search_projects_list(\@projects,5145'searchtext'=>$searchtext,5146'tagfilter'=>$tagfilter)5147if($tagfilter||$searchtext);51485149$order||=$default_projects_order;5150$from=0unlessdefined$from;5151$to=$#projectsif(!defined$to||$#projects<$to);51525153# short circuit5154if($from>$to) {5155print"<center>\n".5156"<b>No such projects found</b><br />\n".5157"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5158"</center>\n<br />\n";5159return;5160}51615162@projects= sort_projects_list(\@projects,$order);51635164if($show_ctags) {5165my$ctags= git_gather_all_ctags(\@projects);5166my$cloud= git_populate_project_tagcloud($ctags);5167print git_show_project_tagcloud($cloud,64);5168}51695170print"<table class=\"project_list\">\n";5171unless($no_header) {5172print"<tr>\n";5173if($check_forks) {5174print"<th></th>\n";5175}5176 print_sort_th('project',$order,'Project');5177 print_sort_th('descr',$order,'Description');5178 print_sort_th('owner',$order,'Owner');5179 print_sort_th('age',$order,'Last Change');5180print"<th></th>\n".# for links5181"</tr>\n";5182}51835184if($projects_list_group_categories) {5185# only display categories with projects in the $from-$to window5186@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5187my%categories= build_projlist_by_category(\@projects,$from,$to);5188foreachmy$cat(sort keys%categories) {5189unless($cateq"") {5190print"<tr>\n";5191if($check_forks) {5192print"<td></td>\n";5193}5194print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5195print"</tr>\n";5196}51975198 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5199}5200}else{5201 git_project_list_rows(\@projects,$from,$to,$check_forks);5202}52035204if(defined$extra) {5205print"<tr>\n";5206if($check_forks) {5207print"<td></td>\n";5208}5209print"<td colspan=\"5\">$extra</td>\n".5210"</tr>\n";5211}5212print"</table>\n";5213}52145215sub git_log_body {5216# uses global variable $project5217my($commitlist,$from,$to,$refs,$extra) =@_;52185219$from=0unlessdefined$from;5220$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);52215222for(my$i=0;$i<=$to;$i++) {5223my%co= %{$commitlist->[$i]};5224next if!%co;5225my$commit=$co{'id'};5226my$ref= format_ref_marker($refs,$commit);5227 git_print_header_div('commit',5228"<span class=\"age\">$co{'age_string'}</span>".5229 esc_html($co{'title'}) .$ref,5230$commit);5231print"<div class=\"title_text\">\n".5232"<div class=\"log_link\">\n".5233$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5234" | ".5235$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5236" | ".5237$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5238"<br/>\n".5239"</div>\n";5240 git_print_authorship(\%co, -tag =>'span');5241print"<br/>\n</div>\n";52425243print"<div class=\"log_body\">\n";5244 git_print_log($co{'comment'}, -final_empty_line=>1);5245print"</div>\n";5246}5247if($extra) {5248print"<div class=\"page_nav\">\n";5249print"$extra\n";5250print"</div>\n";5251}5252}52535254sub git_shortlog_body {5255# uses global variable $project5256my($commitlist,$from,$to,$refs,$extra) =@_;52575258$from=0unlessdefined$from;5259$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);52605261print"<table class=\"shortlog\">\n";5262my$alternate=1;5263for(my$i=$from;$i<=$to;$i++) {5264my%co= %{$commitlist->[$i]};5265my$commit=$co{'id'};5266my$ref= format_ref_marker($refs,$commit);5267if($alternate) {5268print"<tr class=\"dark\">\n";5269}else{5270print"<tr class=\"light\">\n";5271}5272$alternate^=1;5273# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5274print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5275 format_author_html('td', \%co,10) ."<td>";5276print format_subject_html($co{'title'},$co{'title_short'},5277 href(action=>"commit", hash=>$commit),$ref);5278print"</td>\n".5279"<td class=\"link\">".5280$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5281$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5282$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5283my$snapshot_links= format_snapshot_links($commit);5284if(defined$snapshot_links) {5285print" | ".$snapshot_links;5286}5287print"</td>\n".5288"</tr>\n";5289}5290if(defined$extra) {5291print"<tr>\n".5292"<td colspan=\"4\">$extra</td>\n".5293"</tr>\n";5294}5295print"</table>\n";5296}52975298sub git_history_body {5299# Warning: assumes constant type (blob or tree) during history5300my($commitlist,$from,$to,$refs,$extra,5301$file_name,$file_hash,$ftype) =@_;53025303$from=0unlessdefined$from;5304$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});53055306print"<table class=\"history\">\n";5307my$alternate=1;5308for(my$i=$from;$i<=$to;$i++) {5309my%co= %{$commitlist->[$i]};5310if(!%co) {5311next;5312}5313my$commit=$co{'id'};53145315my$ref= format_ref_marker($refs,$commit);53165317if($alternate) {5318print"<tr class=\"dark\">\n";5319}else{5320print"<tr class=\"light\">\n";5321}5322$alternate^=1;5323print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5324# shortlog: format_author_html('td', \%co, 10)5325 format_author_html('td', \%co,15,3) ."<td>";5326# originally git_history used chop_str($co{'title'}, 50)5327print format_subject_html($co{'title'},$co{'title_short'},5328 href(action=>"commit", hash=>$commit),$ref);5329print"</td>\n".5330"<td class=\"link\">".5331$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5332$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");53335334if($ftypeeq'blob') {5335my$blob_current=$file_hash;5336my$blob_parent= git_get_hash_by_path($commit,$file_name);5337if(defined$blob_current&&defined$blob_parent&&5338$blob_currentne$blob_parent) {5339print" | ".5340$cgi->a({-href => href(action=>"blobdiff",5341 hash=>$blob_current, hash_parent=>$blob_parent,5342 hash_base=>$hash_base, hash_parent_base=>$commit,5343 file_name=>$file_name)},5344"diff to current");5345}5346}5347print"</td>\n".5348"</tr>\n";5349}5350if(defined$extra) {5351print"<tr>\n".5352"<td colspan=\"4\">$extra</td>\n".5353"</tr>\n";5354}5355print"</table>\n";5356}53575358sub git_tags_body {5359# uses global variable $project5360my($taglist,$from,$to,$extra) =@_;5361$from=0unlessdefined$from;5362$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);53635364print"<table class=\"tags\">\n";5365my$alternate=1;5366for(my$i=$from;$i<=$to;$i++) {5367my$entry=$taglist->[$i];5368my%tag=%$entry;5369my$comment=$tag{'subject'};5370my$comment_short;5371if(defined$comment) {5372$comment_short= chop_str($comment,30,5);5373}5374if($alternate) {5375print"<tr class=\"dark\">\n";5376}else{5377print"<tr class=\"light\">\n";5378}5379$alternate^=1;5380if(defined$tag{'age'}) {5381print"<td><i>$tag{'age'}</i></td>\n";5382}else{5383print"<td></td>\n";5384}5385print"<td>".5386$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5387-class=>"list name"}, esc_html($tag{'name'})) .5388"</td>\n".5389"<td>";5390if(defined$comment) {5391print format_subject_html($comment,$comment_short,5392 href(action=>"tag", hash=>$tag{'id'}));5393}5394print"</td>\n".5395"<td class=\"selflink\">";5396if($tag{'type'}eq"tag") {5397print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");5398}else{5399print" ";5400}5401print"</td>\n".5402"<td class=\"link\">"." | ".5403$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});5404if($tag{'reftype'}eq"commit") {5405print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .5406" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");5407}elsif($tag{'reftype'}eq"blob") {5408print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");5409}5410print"</td>\n".5411"</tr>";5412}5413if(defined$extra) {5414print"<tr>\n".5415"<td colspan=\"5\">$extra</td>\n".5416"</tr>\n";5417}5418print"</table>\n";5419}54205421sub git_heads_body {5422# uses global variable $project5423my($headlist,$head,$from,$to,$extra) =@_;5424$from=0unlessdefined$from;5425$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);54265427print"<table class=\"heads\">\n";5428my$alternate=1;5429for(my$i=$from;$i<=$to;$i++) {5430my$entry=$headlist->[$i];5431my%ref=%$entry;5432my$curr=$ref{'id'}eq$head;5433if($alternate) {5434print"<tr class=\"dark\">\n";5435}else{5436print"<tr class=\"light\">\n";5437}5438$alternate^=1;5439print"<td><i>$ref{'age'}</i></td>\n".5440($curr?"<td class=\"current_head\">":"<td>") .5441$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),5442-class=>"list name"},esc_html($ref{'name'})) .5443"</td>\n".5444"<td class=\"link\">".5445$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".5446$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".5447$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .5448"</td>\n".5449"</tr>";5450}5451if(defined$extra) {5452print"<tr>\n".5453"<td colspan=\"3\">$extra</td>\n".5454"</tr>\n";5455}5456print"</table>\n";5457}54585459# Display a single remote block5460sub git_remote_block {5461my($remote,$rdata,$limit,$head) =@_;54625463my$heads=$rdata->{'heads'};5464my$fetch=$rdata->{'fetch'};5465my$push=$rdata->{'push'};54665467my$urls_table="<table class=\"projects_list\">\n";54685469if(defined$fetch) {5470if($fetcheq$push) {5471$urls_table.= format_repo_url("URL",$fetch);5472}else{5473$urls_table.= format_repo_url("Fetch URL",$fetch);5474$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;5475}5476}elsif(defined$push) {5477$urls_table.= format_repo_url("Push URL",$push);5478}else{5479$urls_table.= format_repo_url("","No remote URL");5480}54815482$urls_table.="</table>\n";54835484my$dots;5485if(defined$limit&&$limit<@$heads) {5486$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");5487}54885489print$urls_table;5490 git_heads_body($heads,$head,0,$limit,$dots);5491}54925493# Display a list of remote names with the respective fetch and push URLs5494sub git_remotes_list {5495my($remotedata,$limit) =@_;5496print"<table class=\"heads\">\n";5497my$alternate=1;5498my@remotes=sort keys%$remotedata;54995500my$limited=$limit&&$limit<@remotes;55015502$#remotes=$limit-1if$limited;55035504while(my$remote=shift@remotes) {5505my$rdata=$remotedata->{$remote};5506my$fetch=$rdata->{'fetch'};5507my$push=$rdata->{'push'};5508if($alternate) {5509print"<tr class=\"dark\">\n";5510}else{5511print"<tr class=\"light\">\n";5512}5513$alternate^=1;5514print"<td>".5515$cgi->a({-href=> href(action=>'remotes', hash=>$remote),5516-class=>"list name"},esc_html($remote)) .5517"</td>";5518print"<td class=\"link\">".5519(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .5520" | ".5521(defined$push?$cgi->a({-href=>$push},"push") :"push") .5522"</td>";55235524print"</tr>\n";5525}55265527if($limited) {5528print"<tr>\n".5529"<td colspan=\"3\">".5530$cgi->a({-href => href(action=>"remotes")},"...") .5531"</td>\n"."</tr>\n";5532}55335534print"</table>";5535}55365537# Display remote heads grouped by remote, unless there are too many5538# remotes, in which case we only display the remote names5539sub git_remotes_body {5540my($remotedata,$limit,$head) =@_;5541if($limitand$limit<keys%$remotedata) {5542 git_remotes_list($remotedata,$limit);5543}else{5544 fill_remote_heads($remotedata);5545while(my($remote,$rdata) =each%$remotedata) {5546 git_print_section({-class=>"remote", -id=>$remote},5547["remotes",$remote,$remote],sub{5548 git_remote_block($remote,$rdata,$limit,$head);5549});5550}5551}5552}55535554sub git_search_message {5555my%co=@_;55565557my$greptype;5558if($searchtypeeq'commit') {5559$greptype="--grep=";5560}elsif($searchtypeeq'author') {5561$greptype="--author=";5562}elsif($searchtypeeq'committer') {5563$greptype="--committer=";5564}5565$greptype.=$searchtext;5566my@commitlist= parse_commits($hash,101, (100*$page),undef,5567$greptype,'--regexp-ignore-case',5568$search_use_regexp?'--extended-regexp':'--fixed-strings');55695570my$paging_nav='';5571if($page>0) {5572$paging_nav.=5573$cgi->a({-href => href(-replay=>1, page=>undef)},5574"first") .5575" ⋅ ".5576$cgi->a({-href => href(-replay=>1, page=>$page-1),5577-accesskey =>"p", -title =>"Alt-p"},"prev");5578}else{5579$paging_nav.="first ⋅ prev";5580}5581my$next_link='';5582if($#commitlist>=100) {5583$next_link=5584$cgi->a({-href => href(-replay=>1, page=>$page+1),5585-accesskey =>"n", -title =>"Alt-n"},"next");5586$paging_nav.=" ⋅$next_link";5587}else{5588$paging_nav.=" ⋅ next";5589}55905591 git_header_html();55925593 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);5594 git_print_header_div('commit', esc_html($co{'title'}),$hash);5595if($page==0&& !@commitlist) {5596print"<p>No match.</p>\n";5597}else{5598 git_search_grep_body(\@commitlist,0,99,$next_link);5599}56005601 git_footer_html();5602}56035604sub git_search_changes {5605my%co=@_;56065607local$/="\n";5608open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,5609'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",5610($search_use_regexp?'--pickaxe-regex': ())5611or die_error(500,"Open git-log failed");56125613 git_header_html();56145615 git_print_page_nav('','',$hash,$co{'tree'},$hash);5616 git_print_header_div('commit', esc_html($co{'title'}),$hash);56175618print"<table class=\"pickaxe search\">\n";5619my$alternate=1;5620undef%co;5621my@files;5622while(my$line= <$fd>) {5623chomp$line;5624next unless$line;56255626my%set= parse_difftree_raw_line($line);5627if(defined$set{'commit'}) {5628# finish previous commit5629if(%co) {5630print"</td>\n".5631"<td class=\"link\">".5632$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},5633"commit") .5634" | ".5635$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},5636 hash_base=>$co{'id'})},5637"tree") .5638"</td>\n".5639"</tr>\n";5640}56415642if($alternate) {5643print"<tr class=\"dark\">\n";5644}else{5645print"<tr class=\"light\">\n";5646}5647$alternate^=1;5648%co= parse_commit($set{'commit'});5649my$author= chop_and_escape_str($co{'author_name'},15,5);5650print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5651"<td><i>$author</i></td>\n".5652"<td>".5653$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5654-class=>"list subject"},5655 chop_and_escape_str($co{'title'},50) ."<br/>");5656}elsif(defined$set{'to_id'}) {5657next if($set{'to_id'} =~m/^0{40}$/);56585659print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},5660 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),5661-class=>"list"},5662"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .5663"<br/>\n";5664}5665}5666close$fd;56675668# finish last commit (warning: repetition!)5669if(%co) {5670print"</td>\n".5671"<td class=\"link\">".5672$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},5673"commit") .5674" | ".5675$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},5676 hash_base=>$co{'id'})},5677"tree") .5678"</td>\n".5679"</tr>\n";5680}56815682print"</table>\n";56835684 git_footer_html();5685}56865687sub git_search_files {5688my%co=@_;56895690local$/="\n";5691open my$fd,"-|", git_cmd(),'grep','-n',5692$search_use_regexp? ('-E','-i') :'-F',5693$searchtext,$co{'tree'}5694or die_error(500,"Open git-grep failed");56955696 git_header_html();56975698 git_print_page_nav('','',$hash,$co{'tree'},$hash);5699 git_print_header_div('commit', esc_html($co{'title'}),$hash);57005701print"<table class=\"grep_search\">\n";5702my$alternate=1;5703my$matches=0;5704my$lastfile='';5705while(my$line= <$fd>) {5706chomp$line;5707my($file,$lno,$ltext,$binary);5708last if($matches++>1000);5709if($line=~/^Binary file (.+) matches$/) {5710$file=$1;5711$binary=1;5712}else{5713(undef,$file,$lno,$ltext) =split(/:/,$line,4);5714}5715if($filene$lastfile) {5716$lastfileand print"</td></tr>\n";5717if($alternate++) {5718print"<tr class=\"dark\">\n";5719}else{5720print"<tr class=\"light\">\n";5721}5722print"<td class=\"list\">".5723$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},5724 file_name=>"$file"),5725-class=>"list"}, esc_path($file));5726print"</td><td>\n";5727$lastfile=$file;5728}5729if($binary) {5730print"<div class=\"binary\">Binary file</div>\n";5731}else{5732$ltext= untabify($ltext);5733if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {5734$ltext= esc_html($1, -nbsp=>1);5735$ltext.='<span class="match">';5736$ltext.= esc_html($2, -nbsp=>1);5737$ltext.='</span>';5738$ltext.= esc_html($3, -nbsp=>1);5739}else{5740$ltext= esc_html($ltext, -nbsp=>1);5741}5742print"<div class=\"pre\">".5743$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},5744 file_name=>"$file").'#l'.$lno,5745-class=>"linenr"},sprintf('%4i',$lno))5746.' '.$ltext."</div>\n";5747}5748}5749if($lastfile) {5750print"</td></tr>\n";5751if($matches>1000) {5752print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";5753}5754}else{5755print"<div class=\"diff nodifferences\">No matches found</div>\n";5756}5757close$fd;57585759print"</table>\n";57605761 git_footer_html();5762}57635764sub git_search_grep_body {5765my($commitlist,$from,$to,$extra) =@_;5766$from=0unlessdefined$from;5767$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);57685769print"<table class=\"commit_search\">\n";5770my$alternate=1;5771for(my$i=$from;$i<=$to;$i++) {5772my%co= %{$commitlist->[$i]};5773if(!%co) {5774next;5775}5776my$commit=$co{'id'};5777if($alternate) {5778print"<tr class=\"dark\">\n";5779}else{5780print"<tr class=\"light\">\n";5781}5782$alternate^=1;5783print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5784 format_author_html('td', \%co,15,5) .5785"<td>".5786$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5787-class=>"list subject"},5788 chop_and_escape_str($co{'title'},50) ."<br/>");5789my$comment=$co{'comment'};5790foreachmy$line(@$comment) {5791if($line=~m/^(.*?)($search_regexp)(.*)$/i) {5792my($lead,$match,$trail) = ($1,$2,$3);5793$match= chop_str($match,70,5,'center');5794my$contextlen=int((80-length($match))/2);5795$contextlen=30if($contextlen>30);5796$lead= chop_str($lead,$contextlen,10,'left');5797$trail= chop_str($trail,$contextlen,10,'right');57985799$lead= esc_html($lead);5800$match= esc_html($match);5801$trail= esc_html($trail);58025803print"$lead<span class=\"match\">$match</span>$trail<br />";5804}5805}5806print"</td>\n".5807"<td class=\"link\">".5808$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .5809" | ".5810$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .5811" | ".5812$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");5813print"</td>\n".5814"</tr>\n";5815}5816if(defined$extra) {5817print"<tr>\n".5818"<td colspan=\"3\">$extra</td>\n".5819"</tr>\n";5820}5821print"</table>\n";5822}58235824## ======================================================================5825## ======================================================================5826## actions58275828sub git_project_list {5829my$order=$input_params{'order'};5830if(defined$order&&$order!~m/none|project|descr|owner|age/) {5831 die_error(400,"Unknown order parameter");5832}58335834my@list= git_get_projects_list();5835if(!@list) {5836 die_error(404,"No projects found");5837}58385839 git_header_html();5840if(defined$home_text&& -f $home_text) {5841print"<div class=\"index_include\">\n";5842 insert_file($home_text);5843print"</div>\n";5844}5845print$cgi->startform(-method=>"get") .5846"<p class=\"projsearch\">Search:\n".5847$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".5848"</p>".5849$cgi->end_form() ."\n";5850 git_project_list_body(\@list,$order);5851 git_footer_html();5852}58535854sub git_forks {5855my$order=$input_params{'order'};5856if(defined$order&&$order!~m/none|project|descr|owner|age/) {5857 die_error(400,"Unknown order parameter");5858}58595860my@list= git_get_projects_list($project);5861if(!@list) {5862 die_error(404,"No forks found");5863}58645865 git_header_html();5866 git_print_page_nav('','');5867 git_print_header_div('summary',"$projectforks");5868 git_project_list_body(\@list,$order);5869 git_footer_html();5870}58715872sub git_project_index {5873my@projects= git_get_projects_list();5874if(!@projects) {5875 die_error(404,"No projects found");5876}58775878print$cgi->header(5879-type =>'text/plain',5880-charset =>'utf-8',5881-content_disposition =>'inline; filename="index.aux"');58825883foreachmy$pr(@projects) {5884if(!exists$pr->{'owner'}) {5885$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");5886}58875888my($path,$owner) = ($pr->{'path'},$pr->{'owner'});5889# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '5890$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5891$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5892$path=~s/ /\+/g;5893$owner=~s/ /\+/g;58945895print"$path$owner\n";5896}5897}58985899sub git_summary {5900my$descr= git_get_project_description($project) ||"none";5901my%co= parse_commit("HEAD");5902my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();5903my$head=$co{'id'};5904my$remote_heads= gitweb_check_feature('remote_heads');59055906my$owner= git_get_project_owner($project);59075908my$refs= git_get_references();5909# These get_*_list functions return one more to allow us to see if5910# there are more ...5911my@taglist= git_get_tags_list(16);5912my@headlist= git_get_heads_list(16);5913my%remotedata=$remote_heads? git_get_remotes_list() : ();5914my@forklist;5915my$check_forks= gitweb_check_feature('forks');59165917if($check_forks) {5918# find forks of a project5919@forklist= git_get_projects_list($project);5920# filter out forks of forks5921@forklist= filter_forks_from_projects_list(\@forklist)5922if(@forklist);5923}59245925 git_header_html();5926 git_print_page_nav('summary','',$head);59275928print"<div class=\"title\"> </div>\n";5929print"<table class=\"projects_list\">\n".5930"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".5931"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";5932if(defined$cd{'rfc2822'}) {5933print"<tr id=\"metadata_lchange\"><td>last change</td>".5934"<td>".format_timestamp_html(\%cd)."</td></tr>\n";5935}59365937# use per project git URL list in $projectroot/$project/cloneurl5938# or make project git URL from git base URL and project name5939my$url_tag="URL";5940my@url_list= git_get_project_url_list($project);5941@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;5942foreachmy$git_url(@url_list) {5943next unless$git_url;5944print format_repo_url($url_tag,$git_url);5945$url_tag="";5946}59475948# Tag cloud5949my$show_ctags= gitweb_check_feature('ctags');5950if($show_ctags) {5951my$ctags= git_get_project_ctags($project);5952if(%$ctags) {5953# without ability to add tags, don't show if there are none5954my$cloud= git_populate_project_tagcloud($ctags);5955print"<tr id=\"metadata_ctags\">".5956"<td>content tags</td>".5957"<td>".git_show_project_tagcloud($cloud,48)."</td>".5958"</tr>\n";5959}5960}59615962print"</table>\n";59635964# If XSS prevention is on, we don't include README.html.5965# TODO: Allow a readme in some safe format.5966if(!$prevent_xss&& -s "$projectroot/$project/README.html") {5967print"<div class=\"title\">readme</div>\n".5968"<div class=\"readme\">\n";5969 insert_file("$projectroot/$project/README.html");5970print"\n</div>\n";# class="readme"5971}59725973# we need to request one more than 16 (0..15) to check if5974# those 16 are all5975my@commitlist=$head? parse_commits($head,17) : ();5976if(@commitlist) {5977 git_print_header_div('shortlog');5978 git_shortlog_body(\@commitlist,0,15,$refs,5979$#commitlist<=15?undef:5980$cgi->a({-href => href(action=>"shortlog")},"..."));5981}59825983if(@taglist) {5984 git_print_header_div('tags');5985 git_tags_body(\@taglist,0,15,5986$#taglist<=15?undef:5987$cgi->a({-href => href(action=>"tags")},"..."));5988}59895990if(@headlist) {5991 git_print_header_div('heads');5992 git_heads_body(\@headlist,$head,0,15,5993$#headlist<=15?undef:5994$cgi->a({-href => href(action=>"heads")},"..."));5995}59965997if(%remotedata) {5998 git_print_header_div('remotes');5999 git_remotes_body(\%remotedata,15,$head);6000}60016002if(@forklist) {6003 git_print_header_div('forks');6004 git_project_list_body(\@forklist,'age',0,15,6005$#forklist<=15?undef:6006$cgi->a({-href => href(action=>"forks")},"..."),6007'no_header');6008}60096010 git_footer_html();6011}60126013sub git_tag {6014my%tag= parse_tag($hash);60156016if(!%tag) {6017 die_error(404,"Unknown tag object");6018}60196020my$head= git_get_head_hash($project);6021 git_header_html();6022 git_print_page_nav('','',$head,undef,$head);6023 git_print_header_div('commit', esc_html($tag{'name'}),$hash);6024print"<div class=\"title_text\">\n".6025"<table class=\"object_header\">\n".6026"<tr>\n".6027"<td>object</td>\n".6028"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6029$tag{'object'}) ."</td>\n".6030"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6031$tag{'type'}) ."</td>\n".6032"</tr>\n";6033if(defined($tag{'author'})) {6034 git_print_authorship_rows(\%tag,'author');6035}6036print"</table>\n\n".6037"</div>\n";6038print"<div class=\"page_body\">";6039my$comment=$tag{'comment'};6040foreachmy$line(@$comment) {6041chomp$line;6042print esc_html($line, -nbsp=>1) ."<br/>\n";6043}6044print"</div>\n";6045 git_footer_html();6046}60476048sub git_blame_common {6049my$format=shift||'porcelain';6050if($formateq'porcelain'&&$cgi->param('js')) {6051$format='incremental';6052$action='blame_incremental';# for page title etc6053}60546055# permissions6056 gitweb_check_feature('blame')6057or die_error(403,"Blame view not allowed");60586059# error checking6060 die_error(400,"No file name given")unless$file_name;6061$hash_base||= git_get_head_hash($project);6062 die_error(404,"Couldn't find base commit")unless$hash_base;6063my%co= parse_commit($hash_base)6064or die_error(404,"Commit not found");6065my$ftype="blob";6066if(!defined$hash) {6067$hash= git_get_hash_by_path($hash_base,$file_name,"blob")6068or die_error(404,"Error looking up file");6069}else{6070$ftype= git_get_type($hash);6071if($ftype!~"blob") {6072 die_error(400,"Object is not a blob");6073}6074}60756076my$fd;6077if($formateq'incremental') {6078# get file contents (as base)6079open$fd,"-|", git_cmd(),'cat-file','blob',$hash6080or die_error(500,"Open git-cat-file failed");6081}elsif($formateq'data') {6082# run git-blame --incremental6083open$fd,"-|", git_cmd(),"blame","--incremental",6084$hash_base,"--",$file_name6085or die_error(500,"Open git-blame --incremental failed");6086}else{6087# run git-blame --porcelain6088open$fd,"-|", git_cmd(),"blame",'-p',6089$hash_base,'--',$file_name6090or die_error(500,"Open git-blame --porcelain failed");6091}60926093# incremental blame data returns early6094if($formateq'data') {6095print$cgi->header(6096-type=>"text/plain", -charset =>"utf-8",6097-status=>"200 OK");6098local$| =1;# output autoflush6099printwhile<$fd>;6100close$fd6101or print"ERROR$!\n";61026103print'END';6104if(defined$t0&& gitweb_check_feature('timed')) {6105print' '.6106 tv_interval($t0, [ gettimeofday() ]).6107' '.$number_of_git_cmds;6108}6109print"\n";61106111return;6112}61136114# page header6115 git_header_html();6116my$formats_nav=6117$cgi->a({-href => href(action=>"blob", -replay=>1)},6118"blob") .6119" | ";6120if($formateq'incremental') {6121$formats_nav.=6122$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},6123"blame") ." (non-incremental)";6124}else{6125$formats_nav.=6126$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},6127"blame") ." (incremental)";6128}6129$formats_nav.=6130" | ".6131$cgi->a({-href => href(action=>"history", -replay=>1)},6132"history") .6133" | ".6134$cgi->a({-href => href(action=>$action, file_name=>$file_name)},6135"HEAD");6136 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6137 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6138 git_print_page_path($file_name,$ftype,$hash_base);61396140# page body6141if($formateq'incremental') {6142print"<noscript>\n<div class=\"error\"><center><b>\n".6143"This page requires JavaScript to run.\nUse ".6144$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},6145'this page').6146" instead.\n".6147"</b></center></div>\n</noscript>\n";61486149print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;6150}61516152print qq!<div class="page_body">\n!;6153print qq!<div id="progress_info">.../ ...</div>\n!6154if($formateq'incremental');6155print qq!<table id="blame_table"class="blame" width="100%">\n!.6156#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.6157 qq!<thead>\n!.6158 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.6159 qq!</thead>\n!.6160 qq!<tbody>\n!;61616162my@rev_color=qw(light dark);6163my$num_colors=scalar(@rev_color);6164my$current_color=0;61656166if($formateq'incremental') {6167my$color_class=$rev_color[$current_color];61686169#contents of a file6170my$linenr=0;6171 LINE:6172while(my$line= <$fd>) {6173chomp$line;6174$linenr++;61756176print qq!<tr id="l$linenr"class="$color_class">!.6177 qq!<td class="sha1"><a href=""> </a></td>!.6178 qq!<td class="linenr">!.6179 qq!<a class="linenr" href="">$linenr</a></td>!;6180print qq!<td class="pre">! . esc_html($line) ."</td>\n";6181print qq!</tr>\n!;6182}61836184}else{# porcelain, i.e. ordinary blame6185my%metainfo= ();# saves information about commits61866187# blame data6188 LINE:6189while(my$line= <$fd>) {6190chomp$line;6191# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]6192# no <lines in group> for subsequent lines in group of lines6193my($full_rev,$orig_lineno,$lineno,$group_size) =6194($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);6195if(!exists$metainfo{$full_rev}) {6196$metainfo{$full_rev} = {'nprevious'=>0};6197}6198my$meta=$metainfo{$full_rev};6199my$data;6200while($data= <$fd>) {6201chomp$data;6202last if($data=~s/^\t//);# contents of line6203if($data=~/^(\S+)(?: (.*))?$/) {6204$meta->{$1} =$2unlessexists$meta->{$1};6205}6206if($data=~/^previous /) {6207$meta->{'nprevious'}++;6208}6209}6210my$short_rev=substr($full_rev,0,8);6211my$author=$meta->{'author'};6212my%date=6213 parse_date($meta->{'author-time'},$meta->{'author-tz'});6214my$date=$date{'iso-tz'};6215if($group_size) {6216$current_color= ($current_color+1) %$num_colors;6217}6218my$tr_class=$rev_color[$current_color];6219$tr_class.=' boundary'if(exists$meta->{'boundary'});6220$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);6221$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);6222print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";6223if($group_size) {6224print"<td class=\"sha1\"";6225print" title=\"". esc_html($author) .",$date\"";6226print" rowspan=\"$group_size\""if($group_size>1);6227print">";6228print$cgi->a({-href => href(action=>"commit",6229 hash=>$full_rev,6230 file_name=>$file_name)},6231 esc_html($short_rev));6232if($group_size>=2) {6233my@author_initials= ($author=~/\b([[:upper:]])\B/g);6234if(@author_initials) {6235print"<br />".6236 esc_html(join('',@author_initials));6237# or join('.', ...)6238}6239}6240print"</td>\n";6241}6242# 'previous' <sha1 of parent commit> <filename at commit>6243if(exists$meta->{'previous'} &&6244$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {6245$meta->{'parent'} =$1;6246$meta->{'file_parent'} = unquote($2);6247}6248my$linenr_commit=6249exists($meta->{'parent'}) ?6250$meta->{'parent'} :$full_rev;6251my$linenr_filename=6252exists($meta->{'file_parent'}) ?6253$meta->{'file_parent'} : unquote($meta->{'filename'});6254my$blamed= href(action =>'blame',6255 file_name =>$linenr_filename,6256 hash_base =>$linenr_commit);6257print"<td class=\"linenr\">";6258print$cgi->a({ -href =>"$blamed#l$orig_lineno",6259-class=>"linenr"},6260 esc_html($lineno));6261print"</td>";6262print"<td class=\"pre\">". esc_html($data) ."</td>\n";6263print"</tr>\n";6264}# end while62656266}62676268# footer6269print"</tbody>\n".6270"</table>\n";# class="blame"6271print"</div>\n";# class="blame_body"6272close$fd6273or print"Reading blob failed\n";62746275 git_footer_html();6276}62776278sub git_blame {6279 git_blame_common();6280}62816282sub git_blame_incremental {6283 git_blame_common('incremental');6284}62856286sub git_blame_data {6287 git_blame_common('data');6288}62896290sub git_tags {6291my$head= git_get_head_hash($project);6292 git_header_html();6293 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6294 git_print_header_div('summary',$project);62956296my@tagslist= git_get_tags_list();6297if(@tagslist) {6298 git_tags_body(\@tagslist);6299}6300 git_footer_html();6301}63026303sub git_heads {6304my$head= git_get_head_hash($project);6305 git_header_html();6306 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6307 git_print_header_div('summary',$project);63086309my@headslist= git_get_heads_list();6310if(@headslist) {6311 git_heads_body(\@headslist,$head);6312}6313 git_footer_html();6314}63156316# used both for single remote view and for list of all the remotes6317sub git_remotes {6318 gitweb_check_feature('remote_heads')6319or die_error(403,"Remote heads view is disabled");63206321my$head= git_get_head_hash($project);6322my$remote=$input_params{'hash'};63236324my$remotedata= git_get_remotes_list($remote);6325 die_error(500,"Unable to get remote information")unlessdefined$remotedata;63266327unless(%$remotedata) {6328 die_error(404,defined$remote?6329"Remote$remotenot found":6330"No remotes found");6331}63326333 git_header_html(undef,undef, -action_extra =>$remote);6334 git_print_page_nav('','',$head,undef,$head,6335 format_ref_views($remote?'':'remotes'));63366337 fill_remote_heads($remotedata);6338if(defined$remote) {6339 git_print_header_div('remotes',"$remoteremote for$project");6340 git_remote_block($remote,$remotedata->{$remote},undef,$head);6341}else{6342 git_print_header_div('summary',"$projectremotes");6343 git_remotes_body($remotedata,undef,$head);6344}63456346 git_footer_html();6347}63486349sub git_blob_plain {6350my$type=shift;6351my$expires;63526353if(!defined$hash) {6354if(defined$file_name) {6355my$base=$hash_base|| git_get_head_hash($project);6356$hash= git_get_hash_by_path($base,$file_name,"blob")6357or die_error(404,"Cannot find file");6358}else{6359 die_error(400,"No file name defined");6360}6361}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6362# blobs defined by non-textual hash id's can be cached6363$expires="+1d";6364}63656366open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6367or die_error(500,"Open git-cat-file blob '$hash' failed");63686369# content-type (can include charset)6370$type= blob_contenttype($fd,$file_name,$type);63716372# "save as" filename, even when no $file_name is given6373my$save_as="$hash";6374if(defined$file_name) {6375$save_as=$file_name;6376}elsif($type=~m/^text\//) {6377$save_as.='.txt';6378}63796380# With XSS prevention on, blobs of all types except a few known safe6381# ones are served with "Content-Disposition: attachment" to make sure6382# they don't run in our security domain. For certain image types,6383# blob view writes an <img> tag referring to blob_plain view, and we6384# want to be sure not to break that by serving the image as an6385# attachment (though Firefox 3 doesn't seem to care).6386my$sandbox=$prevent_xss&&6387$type!~m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;63886389# serve text/* as text/plain6390if($prevent_xss&&6391($type=~m!^text/[a-z]+\b(.*)$!||6392($type=~m!^[a-z]+/[a-z]\+xml\b(.*)$!&& -T $fd))) {6393my$rest=$1;6394$rest=defined$rest?$rest:'';6395$type="text/plain$rest";6396}63976398print$cgi->header(6399-type =>$type,6400-expires =>$expires,6401-content_disposition =>6402($sandbox?'attachment':'inline')6403.'; filename="'.$save_as.'"');6404local$/=undef;6405binmode STDOUT,':raw';6406print<$fd>;6407binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6408close$fd;6409}64106411sub git_blob {6412my$expires;64136414if(!defined$hash) {6415if(defined$file_name) {6416my$base=$hash_base|| git_get_head_hash($project);6417$hash= git_get_hash_by_path($base,$file_name,"blob")6418or die_error(404,"Cannot find file");6419}else{6420 die_error(400,"No file name defined");6421}6422}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6423# blobs defined by non-textual hash id's can be cached6424$expires="+1d";6425}64266427my$have_blame= gitweb_check_feature('blame');6428open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6429or die_error(500,"Couldn't cat$file_name,$hash");6430my$mimetype= blob_mimetype($fd,$file_name);6431# use 'blob_plain' (aka 'raw') view for files that cannot be displayed6432if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {6433close$fd;6434return git_blob_plain($mimetype);6435}6436# we can have blame only for text/* mimetype6437$have_blame&&= ($mimetype=~m!^text/!);64386439my$highlight= gitweb_check_feature('highlight');6440my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);6441$fd= run_highlighter($fd,$highlight,$syntax)6442if$syntax;64436444 git_header_html(undef,$expires);6445my$formats_nav='';6446if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6447if(defined$file_name) {6448if($have_blame) {6449$formats_nav.=6450$cgi->a({-href => href(action=>"blame", -replay=>1)},6451"blame") .6452" | ";6453}6454$formats_nav.=6455$cgi->a({-href => href(action=>"history", -replay=>1)},6456"history") .6457" | ".6458$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6459"raw") .6460" | ".6461$cgi->a({-href => href(action=>"blob",6462 hash_base=>"HEAD", file_name=>$file_name)},6463"HEAD");6464}else{6465$formats_nav.=6466$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6467"raw");6468}6469 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6470 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6471}else{6472print"<div class=\"page_nav\">\n".6473"<br/><br/></div>\n".6474"<div class=\"title\">".esc_html($hash)."</div>\n";6475}6476 git_print_page_path($file_name,"blob",$hash_base);6477print"<div class=\"page_body\">\n";6478if($mimetype=~m!^image/!) {6479print qq!<img type="!.esc_attr($mimetype).qq!"!;6480if($file_name) {6481print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;6482}6483print qq! src="! .6484 href(action=>"blob_plain", hash=>$hash,6485 hash_base=>$hash_base, file_name=>$file_name) .6486 qq!"/>\n!;6487}else{6488my$nr;6489while(my$line= <$fd>) {6490chomp$line;6491$nr++;6492$line= untabify($line);6493printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,6494$nr, esc_attr(href(-replay =>1)),$nr,$nr,$syntax? to_utf8($line) : esc_html($line, -nbsp=>1);6495}6496}6497close$fd6498or print"Reading blob failed.\n";6499print"</div>";6500 git_footer_html();6501}65026503sub git_tree {6504if(!defined$hash_base) {6505$hash_base="HEAD";6506}6507if(!defined$hash) {6508if(defined$file_name) {6509$hash= git_get_hash_by_path($hash_base,$file_name,"tree");6510}else{6511$hash=$hash_base;6512}6513}6514 die_error(404,"No such tree")unlessdefined($hash);65156516my$show_sizes= gitweb_check_feature('show-sizes');6517my$have_blame= gitweb_check_feature('blame');65186519my@entries= ();6520{6521local$/="\0";6522open my$fd,"-|", git_cmd(),"ls-tree",'-z',6523($show_sizes?'-l': ()),@extra_options,$hash6524or die_error(500,"Open git-ls-tree failed");6525@entries=map{chomp;$_} <$fd>;6526close$fd6527or die_error(404,"Reading tree failed");6528}65296530my$refs= git_get_references();6531my$ref= format_ref_marker($refs,$hash_base);6532 git_header_html();6533my$basedir='';6534if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6535my@views_nav= ();6536if(defined$file_name) {6537push@views_nav,6538$cgi->a({-href => href(action=>"history", -replay=>1)},6539"history"),6540$cgi->a({-href => href(action=>"tree",6541 hash_base=>"HEAD", file_name=>$file_name)},6542"HEAD"),6543}6544my$snapshot_links= format_snapshot_links($hash);6545if(defined$snapshot_links) {6546# FIXME: Should be available when we have no hash base as well.6547push@views_nav,$snapshot_links;6548}6549 git_print_page_nav('tree','',$hash_base,undef,undef,6550join(' | ',@views_nav));6551 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);6552}else{6553undef$hash_base;6554print"<div class=\"page_nav\">\n";6555print"<br/><br/></div>\n";6556print"<div class=\"title\">".esc_html($hash)."</div>\n";6557}6558if(defined$file_name) {6559$basedir=$file_name;6560if($basedirne''&&substr($basedir, -1)ne'/') {6561$basedir.='/';6562}6563 git_print_page_path($file_name,'tree',$hash_base);6564}6565print"<div class=\"page_body\">\n";6566print"<table class=\"tree\">\n";6567my$alternate=1;6568# '..' (top directory) link if possible6569if(defined$hash_base&&6570defined$file_name&&$file_name=~m![^/]+$!) {6571if($alternate) {6572print"<tr class=\"dark\">\n";6573}else{6574print"<tr class=\"light\">\n";6575}6576$alternate^=1;65776578my$up=$file_name;6579$up=~s!/?[^/]+$!!;6580undef$upunless$up;6581# based on git_print_tree_entry6582print'<td class="mode">'. mode_str('040000') ."</td>\n";6583print'<td class="size"> </td>'."\n"if$show_sizes;6584print'<td class="list">';6585print$cgi->a({-href => href(action=>"tree",6586 hash_base=>$hash_base,6587 file_name=>$up)},6588"..");6589print"</td>\n";6590print"<td class=\"link\"></td>\n";65916592print"</tr>\n";6593}6594foreachmy$line(@entries) {6595my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);65966597if($alternate) {6598print"<tr class=\"dark\">\n";6599}else{6600print"<tr class=\"light\">\n";6601}6602$alternate^=1;66036604 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);66056606print"</tr>\n";6607}6608print"</table>\n".6609"</div>";6610 git_footer_html();6611}66126613sub snapshot_name {6614my($project,$hash) =@_;66156616# path/to/project.git -> project6617# path/to/project/.git -> project6618my$name= to_utf8($project);6619$name=~ s,([^/])/*\.git$,$1,;6620$name= basename($name);6621# sanitize name6622$name=~s/[[:cntrl:]]/?/g;66236624my$ver=$hash;6625if($hash=~/^[0-9a-fA-F]+$/) {6626# shorten SHA-1 hash6627my$full_hash= git_get_full_hash($project,$hash);6628if($full_hash=~/^$hash/&&length($hash) >7) {6629$ver= git_get_short_hash($project,$hash);6630}6631}elsif($hash=~m!^refs/tags/(.*)$!) {6632# tags don't need shortened SHA-1 hash6633$ver=$1;6634}else{6635# branches and other need shortened SHA-1 hash6636if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {6637$ver=$1;6638}6639$ver.='-'. git_get_short_hash($project,$hash);6640}6641# in case of hierarchical branch names6642$ver=~s!/!.!g;66436644# name = project-version_string6645$name="$name-$ver";66466647returnwantarray? ($name,$name) :$name;6648}66496650sub git_snapshot {6651my$format=$input_params{'snapshot_format'};6652if(!@snapshot_fmts) {6653 die_error(403,"Snapshots not allowed");6654}6655# default to first supported snapshot format6656$format||=$snapshot_fmts[0];6657if($format!~m/^[a-z0-9]+$/) {6658 die_error(400,"Invalid snapshot format parameter");6659}elsif(!exists($known_snapshot_formats{$format})) {6660 die_error(400,"Unknown snapshot format");6661}elsif($known_snapshot_formats{$format}{'disabled'}) {6662 die_error(403,"Snapshot format not allowed");6663}elsif(!grep($_eq$format,@snapshot_fmts)) {6664 die_error(403,"Unsupported snapshot format");6665}66666667my$type= git_get_type("$hash^{}");6668if(!$type) {6669 die_error(404,'Object does not exist');6670}elsif($typeeq'blob') {6671 die_error(400,'Object is not a tree-ish');6672}66736674my($name,$prefix) = snapshot_name($project,$hash);6675my$filename="$name$known_snapshot_formats{$format}{'suffix'}";6676my$cmd= quote_command(6677 git_cmd(),'archive',6678"--format=$known_snapshot_formats{$format}{'format'}",6679"--prefix=$prefix/",$hash);6680if(exists$known_snapshot_formats{$format}{'compressor'}) {6681$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});6682}66836684$filename=~s/(["\\])/\\$1/g;6685print$cgi->header(6686-type =>$known_snapshot_formats{$format}{'type'},6687-content_disposition =>'inline; filename="'.$filename.'"',6688-status =>'200 OK');66896690open my$fd,"-|",$cmd6691or die_error(500,"Execute git-archive failed");6692binmode STDOUT,':raw';6693print<$fd>;6694binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6695close$fd;6696}66976698sub git_log_generic {6699my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;67006701my$head= git_get_head_hash($project);6702if(!defined$base) {6703$base=$head;6704}6705if(!defined$page) {6706$page=0;6707}6708my$refs= git_get_references();67096710my$commit_hash=$base;6711if(defined$parent) {6712$commit_hash="$parent..$base";6713}6714my@commitlist=6715 parse_commits($commit_hash,101, (100*$page),6716defined$file_name? ($file_name,"--full-history") : ());67176718my$ftype;6719if(!defined$file_hash&&defined$file_name) {6720# some commits could have deleted file in question,6721# and not have it in tree, but one of them has to have it6722for(my$i=0;$i<@commitlist;$i++) {6723$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);6724last ifdefined$file_hash;6725}6726}6727if(defined$file_hash) {6728$ftype= git_get_type($file_hash);6729}6730if(defined$file_name&& !defined$ftype) {6731 die_error(500,"Unknown type of object");6732}6733my%co;6734if(defined$file_name) {6735%co= parse_commit($base)6736or die_error(404,"Unknown commit object");6737}673867396740my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);6741my$next_link='';6742if($#commitlist>=100) {6743$next_link=6744$cgi->a({-href => href(-replay=>1, page=>$page+1),6745-accesskey =>"n", -title =>"Alt-n"},"next");6746}6747my$patch_max= gitweb_get_feature('patches');6748if($patch_max&& !defined$file_name) {6749if($patch_max<0||@commitlist<=$patch_max) {6750$paging_nav.=" ⋅ ".6751$cgi->a({-href => href(action=>"patches", -replay=>1)},6752"patches");6753}6754}67556756 git_header_html();6757 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);6758if(defined$file_name) {6759 git_print_header_div('commit', esc_html($co{'title'}),$base);6760}else{6761 git_print_header_div('summary',$project)6762}6763 git_print_page_path($file_name,$ftype,$hash_base)6764if(defined$file_name);67656766$body_subr->(\@commitlist,0,99,$refs,$next_link,6767$file_name,$file_hash,$ftype);67686769 git_footer_html();6770}67716772sub git_log {6773 git_log_generic('log', \&git_log_body,6774$hash,$hash_parent);6775}67766777sub git_commit {6778$hash||=$hash_base||"HEAD";6779my%co= parse_commit($hash)6780or die_error(404,"Unknown commit object");67816782my$parent=$co{'parent'};6783my$parents=$co{'parents'};# listref67846785# we need to prepare $formats_nav before any parameter munging6786my$formats_nav;6787if(!defined$parent) {6788# --root commitdiff6789$formats_nav.='(initial)';6790}elsif(@$parents==1) {6791# single parent commit6792$formats_nav.=6793'(parent: '.6794$cgi->a({-href => href(action=>"commit",6795 hash=>$parent)},6796 esc_html(substr($parent,0,7))) .6797')';6798}else{6799# merge commit6800$formats_nav.=6801'(merge: '.6802join(' ',map{6803$cgi->a({-href => href(action=>"commit",6804 hash=>$_)},6805 esc_html(substr($_,0,7)));6806}@$parents) .6807')';6808}6809if(gitweb_check_feature('patches') &&@$parents<=1) {6810$formats_nav.=" | ".6811$cgi->a({-href => href(action=>"patch", -replay=>1)},6812"patch");6813}68146815if(!defined$parent) {6816$parent="--root";6817}6818my@difftree;6819open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",6820@diff_opts,6821(@$parents<=1?$parent:'-c'),6822$hash,"--"6823or die_error(500,"Open git-diff-tree failed");6824@difftree=map{chomp;$_} <$fd>;6825close$fdor die_error(404,"Reading git-diff-tree failed");68266827# non-textual hash id's can be cached6828my$expires;6829if($hash=~m/^[0-9a-fA-F]{40}$/) {6830$expires="+1d";6831}6832my$refs= git_get_references();6833my$ref= format_ref_marker($refs,$co{'id'});68346835 git_header_html(undef,$expires);6836 git_print_page_nav('commit','',6837$hash,$co{'tree'},$hash,6838$formats_nav);68396840if(defined$co{'parent'}) {6841 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);6842}else{6843 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);6844}6845print"<div class=\"title_text\">\n".6846"<table class=\"object_header\">\n";6847 git_print_authorship_rows(\%co);6848print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";6849print"<tr>".6850"<td>tree</td>".6851"<td class=\"sha1\">".6852$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),6853class=>"list"},$co{'tree'}) .6854"</td>".6855"<td class=\"link\">".6856$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},6857"tree");6858my$snapshot_links= format_snapshot_links($hash);6859if(defined$snapshot_links) {6860print" | ".$snapshot_links;6861}6862print"</td>".6863"</tr>\n";68646865foreachmy$par(@$parents) {6866print"<tr>".6867"<td>parent</td>".6868"<td class=\"sha1\">".6869$cgi->a({-href => href(action=>"commit", hash=>$par),6870class=>"list"},$par) .6871"</td>".6872"<td class=\"link\">".6873$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .6874" | ".6875$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .6876"</td>".6877"</tr>\n";6878}6879print"</table>".6880"</div>\n";68816882print"<div class=\"page_body\">\n";6883 git_print_log($co{'comment'});6884print"</div>\n";68856886 git_difftree_body(\@difftree,$hash,@$parents);68876888 git_footer_html();6889}68906891sub git_object {6892# object is defined by:6893# - hash or hash_base alone6894# - hash_base and file_name6895my$type;68966897# - hash or hash_base alone6898if($hash|| ($hash_base&& !defined$file_name)) {6899my$object_id=$hash||$hash_base;69006901open my$fd,"-|", quote_command(6902 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'6903or die_error(404,"Object does not exist");6904$type= <$fd>;6905chomp$type;6906close$fd6907or die_error(404,"Object does not exist");69086909# - hash_base and file_name6910}elsif($hash_base&&defined$file_name) {6911$file_name=~ s,/+$,,;69126913system(git_cmd(),"cat-file",'-e',$hash_base) ==06914or die_error(404,"Base object does not exist");69156916# here errors should not hapen6917open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name6918or die_error(500,"Open git-ls-tree failed");6919my$line= <$fd>;6920close$fd;69216922#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'6923unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {6924 die_error(404,"File or directory for given base does not exist");6925}6926$type=$2;6927$hash=$3;6928}else{6929 die_error(400,"Not enough information to find object");6930}69316932print$cgi->redirect(-uri => href(action=>$type, -full=>1,6933 hash=>$hash, hash_base=>$hash_base,6934 file_name=>$file_name),6935-status =>'302 Found');6936}69376938sub git_blobdiff {6939my$format=shift||'html';69406941my$fd;6942my@difftree;6943my%diffinfo;6944my$expires;69456946# preparing $fd and %diffinfo for git_patchset_body6947# new style URI6948if(defined$hash_base&&defined$hash_parent_base) {6949if(defined$file_name) {6950# read raw output6951open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6952$hash_parent_base,$hash_base,6953"--", (defined$file_parent?$file_parent: ()),$file_name6954or die_error(500,"Open git-diff-tree failed");6955@difftree=map{chomp;$_} <$fd>;6956close$fd6957or die_error(404,"Reading git-diff-tree failed");6958@difftree6959or die_error(404,"Blob diff not found");69606961}elsif(defined$hash&&6962$hash=~/[0-9a-fA-F]{40}/) {6963# try to find filename from $hash69646965# read filtered raw output6966open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6967$hash_parent_base,$hash_base,"--"6968or die_error(500,"Open git-diff-tree failed");6969@difftree=6970# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'6971# $hash == to_id6972grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}6973map{chomp;$_} <$fd>;6974close$fd6975or die_error(404,"Reading git-diff-tree failed");6976@difftree6977or die_error(404,"Blob diff not found");69786979}else{6980 die_error(400,"Missing one of the blob diff parameters");6981}69826983if(@difftree>1) {6984 die_error(400,"Ambiguous blob diff specification");6985}69866987%diffinfo= parse_difftree_raw_line($difftree[0]);6988$file_parent||=$diffinfo{'from_file'} ||$file_name;6989$file_name||=$diffinfo{'to_file'};69906991$hash_parent||=$diffinfo{'from_id'};6992$hash||=$diffinfo{'to_id'};69936994# non-textual hash id's can be cached6995if($hash_base=~m/^[0-9a-fA-F]{40}$/&&6996$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {6997$expires='+1d';6998}69997000# open patch output7001open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7002'-p', ($formateq'html'?"--full-index": ()),7003$hash_parent_base,$hash_base,7004"--", (defined$file_parent?$file_parent: ()),$file_name7005or die_error(500,"Open git-diff-tree failed");7006}70077008# old/legacy style URI -- not generated anymore since 1.4.3.7009if(!%diffinfo) {7010 die_error('404 Not Found',"Missing one of the blob diff parameters")7011}70127013# header7014if($formateq'html') {7015my$formats_nav=7016$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},7017"raw");7018 git_header_html(undef,$expires);7019if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7020 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7021 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7022}else{7023print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";7024print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";7025}7026if(defined$file_name) {7027 git_print_page_path($file_name,"blob",$hash_base);7028}else{7029print"<div class=\"page_path\"></div>\n";7030}70317032}elsif($formateq'plain') {7033print$cgi->header(7034-type =>'text/plain',7035-charset =>'utf-8',7036-expires =>$expires,7037-content_disposition =>'inline; filename="'."$file_name".'.patch"');70387039print"X-Git-Url: ".$cgi->self_url() ."\n\n";70407041}else{7042 die_error(400,"Unknown blobdiff format");7043}70447045# patch7046if($formateq'html') {7047print"<div class=\"page_body\">\n";70487049 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);7050close$fd;70517052print"</div>\n";# class="page_body"7053 git_footer_html();70547055}else{7056while(my$line= <$fd>) {7057$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;7058$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;70597060print$line;70617062last if$line=~m!^\+\+\+!;7063}7064local$/=undef;7065print<$fd>;7066close$fd;7067}7068}70697070sub git_blobdiff_plain {7071 git_blobdiff('plain');7072}70737074sub git_commitdiff {7075my%params=@_;7076my$format=$params{-format} ||'html';70777078my($patch_max) = gitweb_get_feature('patches');7079if($formateq'patch') {7080 die_error(403,"Patch view not allowed")unless$patch_max;7081}70827083$hash||=$hash_base||"HEAD";7084my%co= parse_commit($hash)7085or die_error(404,"Unknown commit object");70867087# choose format for commitdiff for merge7088if(!defined$hash_parent&& @{$co{'parents'}} >1) {7089$hash_parent='--cc';7090}7091# we need to prepare $formats_nav before almost any parameter munging7092my$formats_nav;7093if($formateq'html') {7094$formats_nav=7095$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},7096"raw");7097if($patch_max&& @{$co{'parents'}} <=1) {7098$formats_nav.=" | ".7099$cgi->a({-href => href(action=>"patch", -replay=>1)},7100"patch");7101}71027103if(defined$hash_parent&&7104$hash_parentne'-c'&&$hash_parentne'--cc') {7105# commitdiff with two commits given7106my$hash_parent_short=$hash_parent;7107if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {7108$hash_parent_short=substr($hash_parent,0,7);7109}7110$formats_nav.=7111' (from';7112for(my$i=0;$i< @{$co{'parents'}};$i++) {7113if($co{'parents'}[$i]eq$hash_parent) {7114$formats_nav.=' parent '. ($i+1);7115last;7116}7117}7118$formats_nav.=': '.7119$cgi->a({-href => href(action=>"commitdiff",7120 hash=>$hash_parent)},7121 esc_html($hash_parent_short)) .7122')';7123}elsif(!$co{'parent'}) {7124# --root commitdiff7125$formats_nav.=' (initial)';7126}elsif(scalar@{$co{'parents'}} ==1) {7127# single parent commit7128$formats_nav.=7129' (parent: '.7130$cgi->a({-href => href(action=>"commitdiff",7131 hash=>$co{'parent'})},7132 esc_html(substr($co{'parent'},0,7))) .7133')';7134}else{7135# merge commit7136if($hash_parenteq'--cc') {7137$formats_nav.=' | '.7138$cgi->a({-href => href(action=>"commitdiff",7139 hash=>$hash, hash_parent=>'-c')},7140'combined');7141}else{# $hash_parent eq '-c'7142$formats_nav.=' | '.7143$cgi->a({-href => href(action=>"commitdiff",7144 hash=>$hash, hash_parent=>'--cc')},7145'compact');7146}7147$formats_nav.=7148' (merge: '.7149join(' ',map{7150$cgi->a({-href => href(action=>"commitdiff",7151 hash=>$_)},7152 esc_html(substr($_,0,7)));7153} @{$co{'parents'}} ) .7154')';7155}7156}71577158my$hash_parent_param=$hash_parent;7159if(!defined$hash_parent_param) {7160# --cc for multiple parents, --root for parentless7161$hash_parent_param=7162@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';7163}71647165# read commitdiff7166my$fd;7167my@difftree;7168if($formateq'html') {7169open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7170"--no-commit-id","--patch-with-raw","--full-index",7171$hash_parent_param,$hash,"--"7172or die_error(500,"Open git-diff-tree failed");71737174while(my$line= <$fd>) {7175chomp$line;7176# empty line ends raw part of diff-tree output7177last unless$line;7178push@difftree,scalar parse_difftree_raw_line($line);7179}71807181}elsif($formateq'plain') {7182open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7183'-p',$hash_parent_param,$hash,"--"7184or die_error(500,"Open git-diff-tree failed");7185}elsif($formateq'patch') {7186# For commit ranges, we limit the output to the number of7187# patches specified in the 'patches' feature.7188# For single commits, we limit the output to a single patch,7189# diverging from the git-format-patch default.7190my@commit_spec= ();7191if($hash_parent) {7192if($patch_max>0) {7193push@commit_spec,"-$patch_max";7194}7195push@commit_spec,'-n',"$hash_parent..$hash";7196}else{7197if($params{-single}) {7198push@commit_spec,'-1';7199}else{7200if($patch_max>0) {7201push@commit_spec,"-$patch_max";7202}7203push@commit_spec,"-n";7204}7205push@commit_spec,'--root',$hash;7206}7207open$fd,"-|", git_cmd(),"format-patch",@diff_opts,7208'--encoding=utf8','--stdout',@commit_spec7209or die_error(500,"Open git-format-patch failed");7210}else{7211 die_error(400,"Unknown commitdiff format");7212}72137214# non-textual hash id's can be cached7215my$expires;7216if($hash=~m/^[0-9a-fA-F]{40}$/) {7217$expires="+1d";7218}72197220# write commit message7221if($formateq'html') {7222my$refs= git_get_references();7223my$ref= format_ref_marker($refs,$co{'id'});72247225 git_header_html(undef,$expires);7226 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);7227 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);7228print"<div class=\"title_text\">\n".7229"<table class=\"object_header\">\n";7230 git_print_authorship_rows(\%co);7231print"</table>".7232"</div>\n";7233print"<div class=\"page_body\">\n";7234if(@{$co{'comment'}} >1) {7235print"<div class=\"log\">\n";7236 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);7237print"</div>\n";# class="log"7238}72397240}elsif($formateq'plain') {7241my$refs= git_get_references("tags");7242my$tagname= git_get_rev_name_tags($hash);7243my$filename= basename($project) ."-$hash.patch";72447245print$cgi->header(7246-type =>'text/plain',7247-charset =>'utf-8',7248-expires =>$expires,7249-content_disposition =>'inline; filename="'."$filename".'"');7250my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});7251print"From: ". to_utf8($co{'author'}) ."\n";7252print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";7253print"Subject: ". to_utf8($co{'title'}) ."\n";72547255print"X-Git-Tag:$tagname\n"if$tagname;7256print"X-Git-Url: ".$cgi->self_url() ."\n\n";72577258foreachmy$line(@{$co{'comment'}}) {7259print to_utf8($line) ."\n";7260}7261print"---\n\n";7262}elsif($formateq'patch') {7263my$filename= basename($project) ."-$hash.patch";72647265print$cgi->header(7266-type =>'text/plain',7267-charset =>'utf-8',7268-expires =>$expires,7269-content_disposition =>'inline; filename="'."$filename".'"');7270}72717272# write patch7273if($formateq'html') {7274my$use_parents= !defined$hash_parent||7275$hash_parenteq'-c'||$hash_parenteq'--cc';7276 git_difftree_body(\@difftree,$hash,7277$use_parents? @{$co{'parents'}} :$hash_parent);7278print"<br/>\n";72797280 git_patchset_body($fd, \@difftree,$hash,7281$use_parents? @{$co{'parents'}} :$hash_parent);7282close$fd;7283print"</div>\n";# class="page_body"7284 git_footer_html();72857286}elsif($formateq'plain') {7287local$/=undef;7288print<$fd>;7289close$fd7290or print"Reading git-diff-tree failed\n";7291}elsif($formateq'patch') {7292local$/=undef;7293print<$fd>;7294close$fd7295or print"Reading git-format-patch failed\n";7296}7297}72987299sub git_commitdiff_plain {7300 git_commitdiff(-format =>'plain');7301}73027303# format-patch-style patches7304sub git_patch {7305 git_commitdiff(-format =>'patch', -single =>1);7306}73077308sub git_patches {7309 git_commitdiff(-format =>'patch');7310}73117312sub git_history {7313 git_log_generic('history', \&git_history_body,7314$hash_base,$hash_parent_base,7315$file_name,$hash);7316}73177318sub git_search {7319$searchtype||='commit';73207321# check if appropriate features are enabled7322 gitweb_check_feature('search')7323or die_error(403,"Search is disabled");7324if($searchtypeeq'pickaxe') {7325# pickaxe may take all resources of your box and run for several minutes7326# with every query - so decide by yourself how public you make this feature7327 gitweb_check_feature('pickaxe')7328or die_error(403,"Pickaxe search is disabled");7329}7330if($searchtypeeq'grep') {7331# grep search might be potentially CPU-intensive, too7332 gitweb_check_feature('grep')7333or die_error(403,"Grep search is disabled");7334}73357336if(!defined$searchtext) {7337 die_error(400,"Text field is empty");7338}7339if(!defined$hash) {7340$hash= git_get_head_hash($project);7341}7342my%co= parse_commit($hash);7343if(!%co) {7344 die_error(404,"Unknown commit object");7345}7346if(!defined$page) {7347$page=0;7348}73497350if($searchtypeeq'commit'||7351$searchtypeeq'author'||7352$searchtypeeq'committer') {7353 git_search_message(%co);7354}elsif($searchtypeeq'pickaxe') {7355 git_search_changes(%co);7356}elsif($searchtypeeq'grep') {7357 git_search_files(%co);7358}else{7359 die_error(400,"Unknown search type");7360}7361}73627363sub git_search_help {7364 git_header_html();7365 git_print_page_nav('','',$hash,$hash,$hash);7366print<<EOT;7367<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without7368regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,7369the pattern entered is recognized as the POSIX extended7370<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case7371insensitive).</p>7372<dl>7373<dt><b>commit</b></dt>7374<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>7375EOT7376my$have_grep= gitweb_check_feature('grep');7377if($have_grep) {7378print<<EOT;7379<dt><b>grep</b></dt>7380<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing7381 a different one) are searched for the given pattern. On large trees, this search can take7382a while and put some strain on the server, so please use it with some consideration. Note that7383due to git-grep peculiarity, currently if regexp mode is turned off, the matches are7384case-sensitive.</dd>7385EOT7386}7387print<<EOT;7388<dt><b>author</b></dt>7389<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>7390<dt><b>committer</b></dt>7391<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>7392EOT7393my$have_pickaxe= gitweb_check_feature('pickaxe');7394if($have_pickaxe) {7395print<<EOT;7396<dt><b>pickaxe</b></dt>7397<dd>All commits that caused the string to appear or disappear from any file (changes that7398added, removed or "modified" the string) will be listed. This search can take a while and7399takes a lot of strain on the server, so please use it wisely. Note that since you may be7400interested even in changes just changing the case as well, this search is case sensitive.</dd>7401EOT7402}7403print"</dl>\n";7404 git_footer_html();7405}74067407sub git_shortlog {7408 git_log_generic('shortlog', \&git_shortlog_body,7409$hash,$hash_parent);7410}74117412## ......................................................................7413## feeds (RSS, Atom; OPML)74147415sub git_feed {7416my$format=shift||'atom';7417my$have_blame= gitweb_check_feature('blame');74187419# Atom: http://www.atomenabled.org/developers/syndication/7420# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ7421if($formatne'rss'&&$formatne'atom') {7422 die_error(400,"Unknown web feed format");7423}74247425# log/feed of current (HEAD) branch, log of given branch, history of file/directory7426my$head=$hash||'HEAD';7427my@commitlist= parse_commits($head,150,0,$file_name);74287429my%latest_commit;7430my%latest_date;7431my$content_type="application/$format+xml";7432if(defined$cgi->http('HTTP_ACCEPT') &&7433$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {7434# browser (feed reader) prefers text/xml7435$content_type='text/xml';7436}7437if(defined($commitlist[0])) {7438%latest_commit= %{$commitlist[0]};7439my$latest_epoch=$latest_commit{'committer_epoch'};7440%latest_date= parse_date($latest_epoch,$latest_commit{'comitter_tz'});7441my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7442if(defined$if_modified) {7443my$since;7444if(eval{require HTTP::Date;1; }) {7445$since= HTTP::Date::str2time($if_modified);7446}elsif(eval{require Time::ParseDate;1; }) {7447$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7448}7449if(defined$since&&$latest_epoch<=$since) {7450print$cgi->header(7451-type =>$content_type,7452-charset =>'utf-8',7453-last_modified =>$latest_date{'rfc2822'},7454-status =>'304 Not Modified');7455return;7456}7457}7458print$cgi->header(7459-type =>$content_type,7460-charset =>'utf-8',7461-last_modified =>$latest_date{'rfc2822'});7462}else{7463print$cgi->header(7464-type =>$content_type,7465-charset =>'utf-8');7466}74677468# Optimization: skip generating the body if client asks only7469# for Last-Modified date.7470return if($cgi->request_method()eq'HEAD');74717472# header variables7473my$title="$site_name-$project/$action";7474my$feed_type='log';7475if(defined$hash) {7476$title.=" - '$hash'";7477$feed_type='branch log';7478if(defined$file_name) {7479$title.=" ::$file_name";7480$feed_type='history';7481}7482}elsif(defined$file_name) {7483$title.=" -$file_name";7484$feed_type='history';7485}7486$title.="$feed_type";7487my$descr= git_get_project_description($project);7488if(defined$descr) {7489$descr= esc_html($descr);7490}else{7491$descr="$project".7492($formateq'rss'?'RSS':'Atom') .7493" feed";7494}7495my$owner= git_get_project_owner($project);7496$owner= esc_html($owner);74977498#header7499my$alt_url;7500if(defined$file_name) {7501$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);7502}elsif(defined$hash) {7503$alt_url= href(-full=>1, action=>"log", hash=>$hash);7504}else{7505$alt_url= href(-full=>1, action=>"summary");7506}7507print qq!<?xml version="1.0" encoding="utf-8"?>\n!;7508if($formateq'rss') {7509print<<XML;7510<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">7511<channel>7512XML7513print"<title>$title</title>\n".7514"<link>$alt_url</link>\n".7515"<description>$descr</description>\n".7516"<language>en</language>\n".7517# project owner is responsible for 'editorial' content7518"<managingEditor>$owner</managingEditor>\n";7519if(defined$logo||defined$favicon) {7520# prefer the logo to the favicon, since RSS7521# doesn't allow both7522my$img= esc_url($logo||$favicon);7523print"<image>\n".7524"<url>$img</url>\n".7525"<title>$title</title>\n".7526"<link>$alt_url</link>\n".7527"</image>\n";7528}7529if(%latest_date) {7530print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";7531print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";7532}7533print"<generator>gitweb v.$version/$git_version</generator>\n";7534}elsif($formateq'atom') {7535print<<XML;7536<feed xmlns="http://www.w3.org/2005/Atom">7537XML7538print"<title>$title</title>\n".7539"<subtitle>$descr</subtitle>\n".7540'<link rel="alternate" type="text/html" href="'.7541$alt_url.'" />'."\n".7542'<link rel="self" type="'.$content_type.'" href="'.7543$cgi->self_url() .'" />'."\n".7544"<id>". href(-full=>1) ."</id>\n".7545# use project owner for feed author7546"<author><name>$owner</name></author>\n";7547if(defined$favicon) {7548print"<icon>". esc_url($favicon) ."</icon>\n";7549}7550if(defined$logo) {7551# not twice as wide as tall: 72 x 27 pixels7552print"<logo>". esc_url($logo) ."</logo>\n";7553}7554if(!%latest_date) {7555# dummy date to keep the feed valid until commits trickle in:7556print"<updated>1970-01-01T00:00:00Z</updated>\n";7557}else{7558print"<updated>$latest_date{'iso-8601'}</updated>\n";7559}7560print"<generator version='$version/$git_version'>gitweb</generator>\n";7561}75627563# contents7564for(my$i=0;$i<=$#commitlist;$i++) {7565my%co= %{$commitlist[$i]};7566my$commit=$co{'id'};7567# we read 150, we always show 30 and the ones more recent than 48 hours7568if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {7569last;7570}7571my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});75727573# get list of changed files7574open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7575$co{'parent'} ||"--root",7576$co{'id'},"--", (defined$file_name?$file_name: ())7577ornext;7578my@difftree=map{chomp;$_} <$fd>;7579close$fd7580ornext;75817582# print element (entry, item)7583my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);7584if($formateq'rss') {7585print"<item>\n".7586"<title>". esc_html($co{'title'}) ."</title>\n".7587"<author>". esc_html($co{'author'}) ."</author>\n".7588"<pubDate>$cd{'rfc2822'}</pubDate>\n".7589"<guid isPermaLink=\"true\">$co_url</guid>\n".7590"<link>$co_url</link>\n".7591"<description>". esc_html($co{'title'}) ."</description>\n".7592"<content:encoded>".7593"<![CDATA[\n";7594}elsif($formateq'atom') {7595print"<entry>\n".7596"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".7597"<updated>$cd{'iso-8601'}</updated>\n".7598"<author>\n".7599" <name>". esc_html($co{'author_name'}) ."</name>\n";7600if($co{'author_email'}) {7601print" <email>". esc_html($co{'author_email'}) ."</email>\n";7602}7603print"</author>\n".7604# use committer for contributor7605"<contributor>\n".7606" <name>". esc_html($co{'committer_name'}) ."</name>\n";7607if($co{'committer_email'}) {7608print" <email>". esc_html($co{'committer_email'}) ."</email>\n";7609}7610print"</contributor>\n".7611"<published>$cd{'iso-8601'}</published>\n".7612"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".7613"<id>$co_url</id>\n".7614"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".7615"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";7616}7617my$comment=$co{'comment'};7618print"<pre>\n";7619foreachmy$line(@$comment) {7620$line= esc_html($line);7621print"$line\n";7622}7623print"</pre><ul>\n";7624foreachmy$difftree_line(@difftree) {7625my%difftree= parse_difftree_raw_line($difftree_line);7626next if!$difftree{'from_id'};76277628my$file=$difftree{'file'} ||$difftree{'to_file'};76297630print"<li>".7631"[".7632$cgi->a({-href => href(-full=>1, action=>"blobdiff",7633 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},7634 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},7635 file_name=>$file, file_parent=>$difftree{'from_file'}),7636-title =>"diff"},'D');7637if($have_blame) {7638print$cgi->a({-href => href(-full=>1, action=>"blame",7639 file_name=>$file, hash_base=>$commit),7640-title =>"blame"},'B');7641}7642# if this is not a feed of a file history7643if(!defined$file_name||$file_namene$file) {7644print$cgi->a({-href => href(-full=>1, action=>"history",7645 file_name=>$file, hash=>$commit),7646-title =>"history"},'H');7647}7648$file= esc_path($file);7649print"] ".7650"$file</li>\n";7651}7652if($formateq'rss') {7653print"</ul>]]>\n".7654"</content:encoded>\n".7655"</item>\n";7656}elsif($formateq'atom') {7657print"</ul>\n</div>\n".7658"</content>\n".7659"</entry>\n";7660}7661}76627663# end of feed7664if($formateq'rss') {7665print"</channel>\n</rss>\n";7666}elsif($formateq'atom') {7667print"</feed>\n";7668}7669}76707671sub git_rss {7672 git_feed('rss');7673}76747675sub git_atom {7676 git_feed('atom');7677}76787679sub git_opml {7680my@list= git_get_projects_list();7681if(!@list) {7682 die_error(404,"No projects found");7683}76847685print$cgi->header(7686-type =>'text/xml',7687-charset =>'utf-8',7688-content_disposition =>'inline; filename="opml.xml"');76897690print<<XML;7691<?xml version="1.0" encoding="utf-8"?>7692<opml version="1.0">7693<head>7694 <title>$site_nameOPML Export</title>7695</head>7696<body>7697<outline text="git RSS feeds">7698XML76997700foreachmy$pr(@list) {7701my%proj=%$pr;7702my$head= git_get_head_hash($proj{'path'});7703if(!defined$head) {7704next;7705}7706$git_dir="$projectroot/$proj{'path'}";7707my%co= parse_commit($head);7708if(!%co) {7709next;7710}77117712my$path= esc_html(chop_str($proj{'path'},25,5));7713my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);7714my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);7715print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";7716}7717print<<XML;7718</outline>7719</body>7720</opml>7721XML7722}