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# filename of html text to include at top of each page 89our$site_header="++GITWEB_SITE_HEADER++"; 90# html text to include at home page 91our$home_text="++GITWEB_HOMETEXT++"; 92# filename of html text to include at bottom of each page 93our$site_footer="++GITWEB_SITE_FOOTER++"; 94 95# URI of stylesheets 96our@stylesheets= ("++GITWEB_CSS++"); 97# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG. 98our$stylesheet=undef; 99# URI of GIT logo (72x27 size) 100our$logo="++GITWEB_LOGO++"; 101# URI of GIT favicon, assumed to be image/png type 102our$favicon="++GITWEB_FAVICON++"; 103# URI of gitweb.js (JavaScript code for gitweb) 104our$javascript="++GITWEB_JS++"; 105 106# URI and label (title) of GIT logo link 107#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/"; 108#our $logo_label = "git documentation"; 109our$logo_url="http://git-scm.com/"; 110our$logo_label="git homepage"; 111 112# source of projects list 113our$projects_list="++GITWEB_LIST++"; 114 115# the width (in characters) of the projects list "Description" column 116our$projects_list_description_width=25; 117 118# group projects by category on the projects list 119# (enabled if this variable evaluates to true) 120our$projects_list_group_categories=0; 121 122# default category if none specified 123# (leave the empty string for no category) 124our$project_list_default_category=""; 125 126# default order of projects list 127# valid values are none, project, descr, owner, and age 128our$default_projects_order="project"; 129 130# show repository only if this file exists 131# (only effective if this variable evaluates to true) 132our$export_ok="++GITWEB_EXPORT_OK++"; 133 134# show repository only if this subroutine returns true 135# when given the path to the project, for example: 136# sub { return -e "$_[0]/git-daemon-export-ok"; } 137our$export_auth_hook=undef; 138 139# only allow viewing of repositories also shown on the overview page 140our$strict_export="++GITWEB_STRICT_EXPORT++"; 141 142# list of git base URLs used for URL to where fetch project from, 143# i.e. full URL is "$git_base_url/$project" 144our@git_base_url_list=grep{$_ne''} ("++GITWEB_BASE_URL++"); 145 146# default blob_plain mimetype and default charset for text/plain blob 147our$default_blob_plain_mimetype='text/plain'; 148our$default_text_plain_charset=undef; 149 150# file to use for guessing MIME types before trying /etc/mime.types 151# (relative to the current git repository) 152our$mimetypes_file=undef; 153 154# assume this charset if line contains non-UTF-8 characters; 155# it should be valid encoding (see Encoding::Supported(3pm) for list), 156# for which encoding all byte sequences are valid, for example 157# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it 158# could be even 'utf-8' for the old behavior) 159our$fallback_encoding='latin1'; 160 161# rename detection options for git-diff and git-diff-tree 162# - default is '-M', with the cost proportional to 163# (number of removed files) * (number of new files). 164# - more costly is '-C' (which implies '-M'), with the cost proportional to 165# (number of changed files + number of removed files) * (number of new files) 166# - even more costly is '-C', '--find-copies-harder' with cost 167# (number of files in the original tree) * (number of new files) 168# - one might want to include '-B' option, e.g. '-B', '-M' 169our@diff_opts= ('-M');# taken from git_commit 170 171# Disables features that would allow repository owners to inject script into 172# the gitweb domain. 173our$prevent_xss=0; 174 175# Path to the highlight executable to use (must be the one from 176# http://www.andre-simon.de due to assumptions about parameters and output). 177# Useful if highlight is not installed on your webserver's PATH. 178# [Default: highlight] 179our$highlight_bin="++HIGHLIGHT_BIN++"; 180 181# information about snapshot formats that gitweb is capable of serving 182our%known_snapshot_formats= ( 183# name => { 184# 'display' => display name, 185# 'type' => mime type, 186# 'suffix' => filename suffix, 187# 'format' => --format for git-archive, 188# 'compressor' => [compressor command and arguments] 189# (array reference, optional) 190# 'disabled' => boolean (optional)} 191# 192'tgz'=> { 193'display'=>'tar.gz', 194'type'=>'application/x-gzip', 195'suffix'=>'.tar.gz', 196'format'=>'tar', 197'compressor'=> ['gzip','-n']}, 198 199'tbz2'=> { 200'display'=>'tar.bz2', 201'type'=>'application/x-bzip2', 202'suffix'=>'.tar.bz2', 203'format'=>'tar', 204'compressor'=> ['bzip2']}, 205 206'txz'=> { 207'display'=>'tar.xz', 208'type'=>'application/x-xz', 209'suffix'=>'.tar.xz', 210'format'=>'tar', 211'compressor'=> ['xz'], 212'disabled'=>1}, 213 214'zip'=> { 215'display'=>'zip', 216'type'=>'application/x-zip', 217'suffix'=>'.zip', 218'format'=>'zip'}, 219); 220 221# Aliases so we understand old gitweb.snapshot values in repository 222# configuration. 223our%known_snapshot_format_aliases= ( 224'gzip'=>'tgz', 225'bzip2'=>'tbz2', 226'xz'=>'txz', 227 228# backward compatibility: legacy gitweb config support 229'x-gzip'=>undef,'gz'=>undef, 230'x-bzip2'=>undef,'bz2'=>undef, 231'x-zip'=>undef,''=>undef, 232); 233 234# Pixel sizes for icons and avatars. If the default font sizes or lineheights 235# are changed, it may be appropriate to change these values too via 236# $GITWEB_CONFIG. 237our%avatar_size= ( 238'default'=>16, 239'double'=>32 240); 241 242# Used to set the maximum load that we will still respond to gitweb queries. 243# If server load exceed this value then return "503 server busy" error. 244# If gitweb cannot determined server load, it is taken to be 0. 245# Leave it undefined (or set to 'undef') to turn off load checking. 246our$maxload=300; 247 248# configuration for 'highlight' (http://www.andre-simon.de/) 249# match by basename 250our%highlight_basename= ( 251#'Program' => 'py', 252#'Library' => 'py', 253'SConstruct'=>'py',# SCons equivalent of Makefile 254'Makefile'=>'make', 255); 256# match by extension 257our%highlight_ext= ( 258# main extensions, defining name of syntax; 259# see files in /usr/share/highlight/langDefs/ directory 260map{$_=>$_} 261qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl sql make), 262# alternate extensions, see /etc/highlight/filetypes.conf 263'h'=>'c', 264map{$_=>'sh'}qw(bash zsh ksh), 265map{$_=>'cpp'}qw(cxx c++ cc), 266map{$_=>'php'}qw(php3 php4 php5 phps), 267map{$_=>'pl'}qw(perl pm),# perhaps also 'cgi' 268map{$_=>'make'}qw(mak mk), 269map{$_=>'xml'}qw(xhtml html htm), 270); 271 272# You define site-wide feature defaults here; override them with 273# $GITWEB_CONFIG as necessary. 274our%feature= ( 275# feature => { 276# 'sub' => feature-sub (subroutine), 277# 'override' => allow-override (boolean), 278# 'default' => [ default options...] (array reference)} 279# 280# if feature is overridable (it means that allow-override has true value), 281# then feature-sub will be called with default options as parameters; 282# return value of feature-sub indicates if to enable specified feature 283# 284# if there is no 'sub' key (no feature-sub), then feature cannot be 285# overridden 286# 287# use gitweb_get_feature(<feature>) to retrieve the <feature> value 288# (an array) or gitweb_check_feature(<feature>) to check if <feature> 289# is enabled 290 291# Enable the 'blame' blob view, showing the last commit that modified 292# each line in the file. This can be very CPU-intensive. 293 294# To enable system wide have in $GITWEB_CONFIG 295# $feature{'blame'}{'default'} = [1]; 296# To have project specific config enable override in $GITWEB_CONFIG 297# $feature{'blame'}{'override'} = 1; 298# and in project config gitweb.blame = 0|1; 299'blame'=> { 300'sub'=>sub{ feature_bool('blame',@_) }, 301'override'=>0, 302'default'=> [0]}, 303 304# Enable the 'snapshot' link, providing a compressed archive of any 305# tree. This can potentially generate high traffic if you have large 306# project. 307 308# Value is a list of formats defined in %known_snapshot_formats that 309# you wish to offer. 310# To disable system wide have in $GITWEB_CONFIG 311# $feature{'snapshot'}{'default'} = []; 312# To have project specific config enable override in $GITWEB_CONFIG 313# $feature{'snapshot'}{'override'} = 1; 314# and in project config, a comma-separated list of formats or "none" 315# to disable. Example: gitweb.snapshot = tbz2,zip; 316'snapshot'=> { 317'sub'=> \&feature_snapshot, 318'override'=>0, 319'default'=> ['tgz']}, 320 321# Enable text search, which will list the commits which match author, 322# committer or commit text to a given string. Enabled by default. 323# Project specific override is not supported. 324'search'=> { 325'override'=>0, 326'default'=> [1]}, 327 328# Enable grep search, which will list the files in currently selected 329# tree containing the given string. Enabled by default. This can be 330# potentially CPU-intensive, of course. 331 332# To enable system wide have in $GITWEB_CONFIG 333# $feature{'grep'}{'default'} = [1]; 334# To have project specific config enable override in $GITWEB_CONFIG 335# $feature{'grep'}{'override'} = 1; 336# and in project config gitweb.grep = 0|1; 337'grep'=> { 338'sub'=>sub{ feature_bool('grep',@_) }, 339'override'=>0, 340'default'=> [1]}, 341 342# Enable the pickaxe search, which will list the commits that modified 343# a given string in a file. This can be practical and quite faster 344# alternative to 'blame', but still potentially CPU-intensive. 345 346# To enable system wide have in $GITWEB_CONFIG 347# $feature{'pickaxe'}{'default'} = [1]; 348# To have project specific config enable override in $GITWEB_CONFIG 349# $feature{'pickaxe'}{'override'} = 1; 350# and in project config gitweb.pickaxe = 0|1; 351'pickaxe'=> { 352'sub'=>sub{ feature_bool('pickaxe',@_) }, 353'override'=>0, 354'default'=> [1]}, 355 356# Enable showing size of blobs in a 'tree' view, in a separate 357# column, similar to what 'ls -l' does. This cost a bit of IO. 358 359# To disable system wide have in $GITWEB_CONFIG 360# $feature{'show-sizes'}{'default'} = [0]; 361# To have project specific config enable override in $GITWEB_CONFIG 362# $feature{'show-sizes'}{'override'} = 1; 363# and in project config gitweb.showsizes = 0|1; 364'show-sizes'=> { 365'sub'=>sub{ feature_bool('showsizes',@_) }, 366'override'=>0, 367'default'=> [1]}, 368 369# Make gitweb use an alternative format of the URLs which can be 370# more readable and natural-looking: project name is embedded 371# directly in the path and the query string contains other 372# auxiliary information. All gitweb installations recognize 373# URL in either format; this configures in which formats gitweb 374# generates links. 375 376# To enable system wide have in $GITWEB_CONFIG 377# $feature{'pathinfo'}{'default'} = [1]; 378# Project specific override is not supported. 379 380# Note that you will need to change the default location of CSS, 381# favicon, logo and possibly other files to an absolute URL. Also, 382# if gitweb.cgi serves as your indexfile, you will need to force 383# $my_uri to contain the script name in your $GITWEB_CONFIG. 384'pathinfo'=> { 385'override'=>0, 386'default'=> [0]}, 387 388# Make gitweb consider projects in project root subdirectories 389# to be forks of existing projects. Given project $projname.git, 390# projects matching $projname/*.git will not be shown in the main 391# projects list, instead a '+' mark will be added to $projname 392# there and a 'forks' view will be enabled for the project, listing 393# all the forks. If project list is taken from a file, forks have 394# to be listed after the main project. 395 396# To enable system wide have in $GITWEB_CONFIG 397# $feature{'forks'}{'default'} = [1]; 398# Project specific override is not supported. 399'forks'=> { 400'override'=>0, 401'default'=> [0]}, 402 403# Insert custom links to the action bar of all project pages. 404# This enables you mainly to link to third-party scripts integrating 405# into gitweb; e.g. git-browser for graphical history representation 406# or custom web-based repository administration interface. 407 408# The 'default' value consists of a list of triplets in the form 409# (label, link, position) where position is the label after which 410# to insert the link and link is a format string where %n expands 411# to the project name, %f to the project path within the filesystem, 412# %h to the current hash (h gitweb parameter) and %b to the current 413# hash base (hb gitweb parameter); %% expands to %. 414 415# To enable system wide have in $GITWEB_CONFIG e.g. 416# $feature{'actions'}{'default'} = [('graphiclog', 417# '/git-browser/by-commit.html?r=%n', 'summary')]; 418# Project specific override is not supported. 419'actions'=> { 420'override'=>0, 421'default'=> []}, 422 423# Allow gitweb scan project content tags of project repository, 424# and display the popular Web 2.0-ish "tag cloud" near the projects 425# list. Note that this is something COMPLETELY different from the 426# normal Git tags. 427 428# gitweb by itself can show existing tags, but it does not handle 429# tagging itself; you need to do it externally, outside gitweb. 430# The format is described in git_get_project_ctags() subroutine. 431# You may want to install the HTML::TagCloud Perl module to get 432# a pretty tag cloud instead of just a list of tags. 433 434# To enable system wide have in $GITWEB_CONFIG 435# $feature{'ctags'}{'default'} = [1]; 436# Project specific override is not supported. 437 438# In the future whether ctags editing is enabled might depend 439# on the value, but using 1 should always mean no editing of ctags. 440'ctags'=> { 441'override'=>0, 442'default'=> [0]}, 443 444# The maximum number of patches in a patchset generated in patch 445# view. Set this to 0 or undef to disable patch view, or to a 446# negative number to remove any limit. 447 448# To disable system wide have in $GITWEB_CONFIG 449# $feature{'patches'}{'default'} = [0]; 450# To have project specific config enable override in $GITWEB_CONFIG 451# $feature{'patches'}{'override'} = 1; 452# and in project config gitweb.patches = 0|n; 453# where n is the maximum number of patches allowed in a patchset. 454'patches'=> { 455'sub'=> \&feature_patches, 456'override'=>0, 457'default'=> [16]}, 458 459# Avatar support. When this feature is enabled, views such as 460# shortlog or commit will display an avatar associated with 461# the email of the committer(s) and/or author(s). 462 463# Currently available providers are gravatar and picon. 464# If an unknown provider is specified, the feature is disabled. 465 466# Gravatar depends on Digest::MD5. 467# Picon currently relies on the indiana.edu database. 468 469# To enable system wide have in $GITWEB_CONFIG 470# $feature{'avatar'}{'default'} = ['<provider>']; 471# where <provider> is either gravatar or picon. 472# To have project specific config enable override in $GITWEB_CONFIG 473# $feature{'avatar'}{'override'} = 1; 474# and in project config gitweb.avatar = <provider>; 475'avatar'=> { 476'sub'=> \&feature_avatar, 477'override'=>0, 478'default'=> ['']}, 479 480# Enable displaying how much time and how many git commands 481# it took to generate and display page. Disabled by default. 482# Project specific override is not supported. 483'timed'=> { 484'override'=>0, 485'default'=> [0]}, 486 487# Enable turning some links into links to actions which require 488# JavaScript to run (like 'blame_incremental'). Not enabled by 489# default. Project specific override is currently not supported. 490'javascript-actions'=> { 491'override'=>0, 492'default'=> [0]}, 493 494# Enable and configure ability to change common timezone for dates 495# in gitweb output via JavaScript. Enabled by default. 496# Project specific override is not supported. 497'javascript-timezone'=> { 498'override'=>0, 499'default'=> [ 500'local',# default timezone: 'utc', 'local', or '(-|+)HHMM' format, 501# or undef to turn off this feature 502'gitweb_tz',# name of cookie where to store selected timezone 503'datetime',# CSS class used to mark up dates for manipulation 504]}, 505 506# Syntax highlighting support. This is based on Daniel Svensson's 507# and Sham Chukoury's work in gitweb-xmms2.git. 508# It requires the 'highlight' program present in $PATH, 509# and therefore is disabled by default. 510 511# To enable system wide have in $GITWEB_CONFIG 512# $feature{'highlight'}{'default'} = [1]; 513 514'highlight'=> { 515'sub'=>sub{ feature_bool('highlight',@_) }, 516'override'=>0, 517'default'=> [0]}, 518 519# Enable displaying of remote heads in the heads list 520 521# To enable system wide have in $GITWEB_CONFIG 522# $feature{'remote_heads'}{'default'} = [1]; 523# To have project specific config enable override in $GITWEB_CONFIG 524# $feature{'remote_heads'}{'override'} = 1; 525# and in project config gitweb.remote_heads = 0|1; 526'remote_heads'=> { 527'sub'=>sub{ feature_bool('remote_heads',@_) }, 528'override'=>0, 529'default'=> [0]}, 530); 531 532sub gitweb_get_feature { 533my($name) =@_; 534return unlessexists$feature{$name}; 535my($sub,$override,@defaults) = ( 536$feature{$name}{'sub'}, 537$feature{$name}{'override'}, 538@{$feature{$name}{'default'}}); 539# project specific override is possible only if we have project 540our$git_dir;# global variable, declared later 541if(!$override|| !defined$git_dir) { 542return@defaults; 543} 544if(!defined$sub) { 545warn"feature$nameis not overridable"; 546return@defaults; 547} 548return$sub->(@defaults); 549} 550 551# A wrapper to check if a given feature is enabled. 552# With this, you can say 553# 554# my $bool_feat = gitweb_check_feature('bool_feat'); 555# gitweb_check_feature('bool_feat') or somecode; 556# 557# instead of 558# 559# my ($bool_feat) = gitweb_get_feature('bool_feat'); 560# (gitweb_get_feature('bool_feat'))[0] or somecode; 561# 562sub gitweb_check_feature { 563return(gitweb_get_feature(@_))[0]; 564} 565 566 567sub feature_bool { 568my$key=shift; 569my($val) = git_get_project_config($key,'--bool'); 570 571if(!defined$val) { 572return($_[0]); 573}elsif($valeq'true') { 574return(1); 575}elsif($valeq'false') { 576return(0); 577} 578} 579 580sub feature_snapshot { 581my(@fmts) =@_; 582 583my($val) = git_get_project_config('snapshot'); 584 585if($val) { 586@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 587} 588 589return@fmts; 590} 591 592sub feature_patches { 593my@val= (git_get_project_config('patches','--int')); 594 595if(@val) { 596return@val; 597} 598 599return($_[0]); 600} 601 602sub feature_avatar { 603my@val= (git_get_project_config('avatar')); 604 605return@val?@val:@_; 606} 607 608# checking HEAD file with -e is fragile if the repository was 609# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 610# and then pruned. 611sub check_head_link { 612my($dir) =@_; 613my$headfile="$dir/HEAD"; 614return((-e $headfile) || 615(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 616} 617 618sub check_export_ok { 619my($dir) =@_; 620return(check_head_link($dir) && 621(!$export_ok|| -e "$dir/$export_ok") && 622(!$export_auth_hook||$export_auth_hook->($dir))); 623} 624 625# process alternate names for backward compatibility 626# filter out unsupported (unknown) snapshot formats 627sub filter_snapshot_fmts { 628my@fmts=@_; 629 630@fmts=map{ 631exists$known_snapshot_format_aliases{$_} ? 632$known_snapshot_format_aliases{$_} :$_}@fmts; 633@fmts=grep{ 634exists$known_snapshot_formats{$_} && 635!$known_snapshot_formats{$_}{'disabled'}}@fmts; 636} 637 638# If it is set to code reference, it is code that it is to be run once per 639# request, allowing updating configurations that change with each request, 640# while running other code in config file only once. 641# 642# Otherwise, if it is false then gitweb would process config file only once; 643# if it is true then gitweb config would be run for each request. 644our$per_request_config=1; 645 646# read and parse gitweb config file given by its parameter. 647# returns true on success, false on recoverable error, allowing 648# to chain this subroutine, using first file that exists. 649# dies on errors during parsing config file, as it is unrecoverable. 650sub read_config_file { 651my$filename=shift; 652return unlessdefined$filename; 653# die if there are errors parsing config file 654if(-e $filename) { 655do$filename; 656die$@if$@; 657return1; 658} 659return; 660} 661 662our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM); 663sub evaluate_gitweb_config { 664our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 665our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 666 667# use first config file that exists 668 read_config_file($GITWEB_CONFIG)or 669 read_config_file($GITWEB_CONFIG_SYSTEM); 670} 671 672# Get loadavg of system, to compare against $maxload. 673# Currently it requires '/proc/loadavg' present to get loadavg; 674# if it is not present it returns 0, which means no load checking. 675sub get_loadavg { 676if( -e '/proc/loadavg'){ 677open my$fd,'<','/proc/loadavg' 678orreturn0; 679my@load=split(/\s+/,scalar<$fd>); 680close$fd; 681 682# The first three columns measure CPU and IO utilization of the last one, 683# five, and 10 minute periods. The fourth column shows the number of 684# currently running processes and the total number of processes in the m/n 685# format. The last column displays the last process ID used. 686return$load[0] ||0; 687} 688# additional checks for load average should go here for things that don't export 689# /proc/loadavg 690 691return0; 692} 693 694# version of the core git binary 695our$git_version; 696sub evaluate_git_version { 697our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 698$number_of_git_cmds++; 699} 700 701sub check_loadavg { 702if(defined$maxload&& get_loadavg() >$maxload) { 703 die_error(503,"The load average on the server is too high"); 704} 705} 706 707# ====================================================================== 708# input validation and dispatch 709 710# input parameters can be collected from a variety of sources (presently, CGI 711# and PATH_INFO), so we define an %input_params hash that collects them all 712# together during validation: this allows subsequent uses (e.g. href()) to be 713# agnostic of the parameter origin 714 715our%input_params= (); 716 717# input parameters are stored with the long parameter name as key. This will 718# also be used in the href subroutine to convert parameters to their CGI 719# equivalent, and since the href() usage is the most frequent one, we store 720# the name -> CGI key mapping here, instead of the reverse. 721# 722# XXX: Warning: If you touch this, check the search form for updating, 723# too. 724 725our@cgi_param_mapping= ( 726 project =>"p", 727 action =>"a", 728 file_name =>"f", 729 file_parent =>"fp", 730 hash =>"h", 731 hash_parent =>"hp", 732 hash_base =>"hb", 733 hash_parent_base =>"hpb", 734 page =>"pg", 735 order =>"o", 736 searchtext =>"s", 737 searchtype =>"st", 738 snapshot_format =>"sf", 739 extra_options =>"opt", 740 search_use_regexp =>"sr", 741 ctag =>"by_tag", 742# this must be last entry (for manipulation from JavaScript) 743 javascript =>"js" 744); 745our%cgi_param_mapping=@cgi_param_mapping; 746 747# we will also need to know the possible actions, for validation 748our%actions= ( 749"blame"=> \&git_blame, 750"blame_incremental"=> \&git_blame_incremental, 751"blame_data"=> \&git_blame_data, 752"blobdiff"=> \&git_blobdiff, 753"blobdiff_plain"=> \&git_blobdiff_plain, 754"blob"=> \&git_blob, 755"blob_plain"=> \&git_blob_plain, 756"commitdiff"=> \&git_commitdiff, 757"commitdiff_plain"=> \&git_commitdiff_plain, 758"commit"=> \&git_commit, 759"forks"=> \&git_forks, 760"heads"=> \&git_heads, 761"history"=> \&git_history, 762"log"=> \&git_log, 763"patch"=> \&git_patch, 764"patches"=> \&git_patches, 765"remotes"=> \&git_remotes, 766"rss"=> \&git_rss, 767"atom"=> \&git_atom, 768"search"=> \&git_search, 769"search_help"=> \&git_search_help, 770"shortlog"=> \&git_shortlog, 771"summary"=> \&git_summary, 772"tag"=> \&git_tag, 773"tags"=> \&git_tags, 774"tree"=> \&git_tree, 775"snapshot"=> \&git_snapshot, 776"object"=> \&git_object, 777# those below don't need $project 778"opml"=> \&git_opml, 779"project_list"=> \&git_project_list, 780"project_index"=> \&git_project_index, 781); 782 783# finally, we have the hash of allowed extra_options for the commands that 784# allow them 785our%allowed_options= ( 786"--no-merges"=> [qw(rss atom log shortlog history)], 787); 788 789# fill %input_params with the CGI parameters. All values except for 'opt' 790# should be single values, but opt can be an array. We should probably 791# build an array of parameters that can be multi-valued, but since for the time 792# being it's only this one, we just single it out 793sub evaluate_query_params { 794our$cgi; 795 796while(my($name,$symbol) =each%cgi_param_mapping) { 797if($symboleq'opt') { 798$input_params{$name} = [$cgi->param($symbol) ]; 799}else{ 800$input_params{$name} =$cgi->param($symbol); 801} 802} 803} 804 805# now read PATH_INFO and update the parameter list for missing parameters 806sub evaluate_path_info { 807return ifdefined$input_params{'project'}; 808return if!$path_info; 809$path_info=~ s,^/+,,; 810return if!$path_info; 811 812# find which part of PATH_INFO is project 813my$project=$path_info; 814$project=~ s,/+$,,; 815while($project&& !check_head_link("$projectroot/$project")) { 816$project=~ s,/*[^/]*$,,; 817} 818return unless$project; 819$input_params{'project'} =$project; 820 821# do not change any parameters if an action is given using the query string 822return if$input_params{'action'}; 823$path_info=~ s,^\Q$project\E/*,,; 824 825# next, check if we have an action 826my$action=$path_info; 827$action=~ s,/.*$,,; 828if(exists$actions{$action}) { 829$path_info=~ s,^$action/*,,; 830$input_params{'action'} =$action; 831} 832 833# list of actions that want hash_base instead of hash, but can have no 834# pathname (f) parameter 835my@wants_base= ( 836'tree', 837'history', 838); 839 840# we want to catch, among others 841# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 842my($parentrefname,$parentpathname,$refname,$pathname) = 843($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/); 844 845# first, analyze the 'current' part 846if(defined$pathname) { 847# we got "branch:filename" or "branch:dir/" 848# we could use git_get_type(branch:pathname), but: 849# - it needs $git_dir 850# - it does a git() call 851# - the convention of terminating directories with a slash 852# makes it superfluous 853# - embedding the action in the PATH_INFO would make it even 854# more superfluous 855$pathname=~ s,^/+,,; 856if(!$pathname||substr($pathname, -1)eq"/") { 857$input_params{'action'} ||="tree"; 858$pathname=~ s,/$,,; 859}else{ 860# the default action depends on whether we had parent info 861# or not 862if($parentrefname) { 863$input_params{'action'} ||="blobdiff_plain"; 864}else{ 865$input_params{'action'} ||="blob_plain"; 866} 867} 868$input_params{'hash_base'} ||=$refname; 869$input_params{'file_name'} ||=$pathname; 870}elsif(defined$refname) { 871# we got "branch". In this case we have to choose if we have to 872# set hash or hash_base. 873# 874# Most of the actions without a pathname only want hash to be 875# set, except for the ones specified in @wants_base that want 876# hash_base instead. It should also be noted that hand-crafted 877# links having 'history' as an action and no pathname or hash 878# set will fail, but that happens regardless of PATH_INFO. 879if(defined$parentrefname) { 880# if there is parent let the default be 'shortlog' action 881# (for http://git.example.com/repo.git/A..B links); if there 882# is no parent, dispatch will detect type of object and set 883# action appropriately if required (if action is not set) 884$input_params{'action'} ||="shortlog"; 885} 886if($input_params{'action'} && 887grep{$_eq$input_params{'action'} }@wants_base) { 888$input_params{'hash_base'} ||=$refname; 889}else{ 890$input_params{'hash'} ||=$refname; 891} 892} 893 894# next, handle the 'parent' part, if present 895if(defined$parentrefname) { 896# a missing pathspec defaults to the 'current' filename, allowing e.g. 897# someproject/blobdiff/oldrev..newrev:/filename 898if($parentpathname) { 899$parentpathname=~ s,^/+,,; 900$parentpathname=~ s,/$,,; 901$input_params{'file_parent'} ||=$parentpathname; 902}else{ 903$input_params{'file_parent'} ||=$input_params{'file_name'}; 904} 905# we assume that hash_parent_base is wanted if a path was specified, 906# or if the action wants hash_base instead of hash 907if(defined$input_params{'file_parent'} || 908grep{$_eq$input_params{'action'} }@wants_base) { 909$input_params{'hash_parent_base'} ||=$parentrefname; 910}else{ 911$input_params{'hash_parent'} ||=$parentrefname; 912} 913} 914 915# for the snapshot action, we allow URLs in the form 916# $project/snapshot/$hash.ext 917# where .ext determines the snapshot and gets removed from the 918# passed $refname to provide the $hash. 919# 920# To be able to tell that $refname includes the format extension, we 921# require the following two conditions to be satisfied: 922# - the hash input parameter MUST have been set from the $refname part 923# of the URL (i.e. they must be equal) 924# - the snapshot format MUST NOT have been defined already (e.g. from 925# CGI parameter sf) 926# It's also useless to try any matching unless $refname has a dot, 927# so we check for that too 928if(defined$input_params{'action'} && 929$input_params{'action'}eq'snapshot'&& 930defined$refname&&index($refname,'.') != -1&& 931$refnameeq$input_params{'hash'} && 932!defined$input_params{'snapshot_format'}) { 933# We loop over the known snapshot formats, checking for 934# extensions. Allowed extensions are both the defined suffix 935# (which includes the initial dot already) and the snapshot 936# format key itself, with a prepended dot 937while(my($fmt,$opt) =each%known_snapshot_formats) { 938my$hash=$refname; 939unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 940next; 941} 942my$sfx=$1; 943# a valid suffix was found, so set the snapshot format 944# and reset the hash parameter 945$input_params{'snapshot_format'} =$fmt; 946$input_params{'hash'} =$hash; 947# we also set the format suffix to the one requested 948# in the URL: this way a request for e.g. .tgz returns 949# a .tgz instead of a .tar.gz 950$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 951last; 952} 953} 954} 955 956our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 957$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 958$searchtext,$search_regexp); 959sub evaluate_and_validate_params { 960our$action=$input_params{'action'}; 961if(defined$action) { 962if(!validate_action($action)) { 963 die_error(400,"Invalid action parameter"); 964} 965} 966 967# parameters which are pathnames 968our$project=$input_params{'project'}; 969if(defined$project) { 970if(!validate_project($project)) { 971undef$project; 972 die_error(404,"No such project"); 973} 974} 975 976our$file_name=$input_params{'file_name'}; 977if(defined$file_name) { 978if(!validate_pathname($file_name)) { 979 die_error(400,"Invalid file parameter"); 980} 981} 982 983our$file_parent=$input_params{'file_parent'}; 984if(defined$file_parent) { 985if(!validate_pathname($file_parent)) { 986 die_error(400,"Invalid file parent parameter"); 987} 988} 989 990# parameters which are refnames 991our$hash=$input_params{'hash'}; 992if(defined$hash) { 993if(!validate_refname($hash)) { 994 die_error(400,"Invalid hash parameter"); 995} 996} 997 998our$hash_parent=$input_params{'hash_parent'}; 999if(defined$hash_parent) {1000if(!validate_refname($hash_parent)) {1001 die_error(400,"Invalid hash parent parameter");1002}1003}10041005our$hash_base=$input_params{'hash_base'};1006if(defined$hash_base) {1007if(!validate_refname($hash_base)) {1008 die_error(400,"Invalid hash base parameter");1009}1010}10111012our@extra_options= @{$input_params{'extra_options'}};1013# @extra_options is always defined, since it can only be (currently) set from1014# CGI, and $cgi->param() returns the empty array in array context if the param1015# is not set1016foreachmy$opt(@extra_options) {1017if(not exists$allowed_options{$opt}) {1018 die_error(400,"Invalid option parameter");1019}1020if(not grep(/^$action$/, @{$allowed_options{$opt}})) {1021 die_error(400,"Invalid option parameter for this action");1022}1023}10241025our$hash_parent_base=$input_params{'hash_parent_base'};1026if(defined$hash_parent_base) {1027if(!validate_refname($hash_parent_base)) {1028 die_error(400,"Invalid hash parent base parameter");1029}1030}10311032# other parameters1033our$page=$input_params{'page'};1034if(defined$page) {1035if($page=~m/[^0-9]/) {1036 die_error(400,"Invalid page parameter");1037}1038}10391040our$searchtype=$input_params{'searchtype'};1041if(defined$searchtype) {1042if($searchtype=~m/[^a-z]/) {1043 die_error(400,"Invalid searchtype parameter");1044}1045}10461047our$search_use_regexp=$input_params{'search_use_regexp'};10481049our$searchtext=$input_params{'searchtext'};1050our$search_regexp;1051if(defined$searchtext) {1052if(length($searchtext) <2) {1053 die_error(403,"At least two characters are required for search parameter");1054}1055$search_regexp=$search_use_regexp?$searchtext:quotemeta$searchtext;1056}1057}10581059# path to the current git repository1060our$git_dir;1061sub evaluate_git_dir {1062our$git_dir="$projectroot/$project"if$project;1063}10641065our(@snapshot_fmts,$git_avatar);1066sub configure_gitweb_features {1067# list of supported snapshot formats1068our@snapshot_fmts= gitweb_get_feature('snapshot');1069@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);10701071# check that the avatar feature is set to a known provider name,1072# and for each provider check if the dependencies are satisfied.1073# if the provider name is invalid or the dependencies are not met,1074# reset $git_avatar to the empty string.1075our($git_avatar) = gitweb_get_feature('avatar');1076if($git_avatareq'gravatar') {1077$git_avatar=''unless(eval{require Digest::MD5;1; });1078}elsif($git_avatareq'picon') {1079# no dependencies1080}else{1081$git_avatar='';1082}1083}10841085# custom error handler: 'die <message>' is Internal Server Error1086sub handle_errors_html {1087my$msg=shift;# it is already HTML escaped10881089# to avoid infinite loop where error occurs in die_error,1090# change handler to default handler, disabling handle_errors_html1091 set_message("Error occured when inside die_error:\n$msg");10921093# you cannot jump out of die_error when called as error handler;1094# the subroutine set via CGI::Carp::set_message is called _after_1095# HTTP headers are already written, so it cannot write them itself1096 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1097}1098set_message(\&handle_errors_html);10991100# dispatch1101sub dispatch {1102if(!defined$action) {1103if(defined$hash) {1104$action= git_get_type($hash);1105}elsif(defined$hash_base&&defined$file_name) {1106$action= git_get_type("$hash_base:$file_name");1107}elsif(defined$project) {1108$action='summary';1109}else{1110$action='project_list';1111}1112}1113if(!defined($actions{$action})) {1114 die_error(400,"Unknown action");1115}1116if($action!~m/^(?:opml|project_list|project_index)$/&&1117!$project) {1118 die_error(400,"Project needed");1119}1120$actions{$action}->();1121}11221123sub reset_timer {1124our$t0= [ gettimeofday() ]1125ifdefined$t0;1126our$number_of_git_cmds=0;1127}11281129our$first_request=1;1130sub run_request {1131 reset_timer();11321133 evaluate_uri();1134if($first_request) {1135 evaluate_gitweb_config();1136 evaluate_git_version();1137}1138if($per_request_config) {1139if(ref($per_request_config)eq'CODE') {1140$per_request_config->();1141}elsif(!$first_request) {1142 evaluate_gitweb_config();1143}1144}1145 check_loadavg();11461147# $projectroot and $projects_list might be set in gitweb config file1148$projects_list||=$projectroot;11491150 evaluate_query_params();1151 evaluate_path_info();1152 evaluate_and_validate_params();1153 evaluate_git_dir();11541155 configure_gitweb_features();11561157 dispatch();1158}11591160our$is_last_request=sub{1};1161our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1162our$CGI='CGI';1163our$cgi;1164sub configure_as_fcgi {1165require CGI::Fast;1166our$CGI='CGI::Fast';11671168my$request_number=0;1169# let each child service 100 requests1170our$is_last_request=sub{ ++$request_number>100};1171}1172sub evaluate_argv {1173my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1174 configure_as_fcgi()1175if$script_name=~/\.fcgi$/;11761177return unless(@ARGV);11781179require Getopt::Long;1180 Getopt::Long::GetOptions(1181'fastcgi|fcgi|f'=> \&configure_as_fcgi,1182'nproc|n=i'=>sub{1183my($arg,$val) =@_;1184return unlesseval{require FCGI::ProcManager;1; };1185my$proc_manager= FCGI::ProcManager->new({1186 n_processes =>$val,1187});1188our$pre_listen_hook=sub{$proc_manager->pm_manage() };1189our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1190our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1191},1192);1193}11941195sub run {1196 evaluate_argv();11971198$first_request=1;1199$pre_listen_hook->()1200if$pre_listen_hook;12011202 REQUEST:1203while($cgi=$CGI->new()) {1204$pre_dispatch_hook->()1205if$pre_dispatch_hook;12061207 run_request();12081209$post_dispatch_hook->()1210if$post_dispatch_hook;1211$first_request=0;12121213last REQUEST if($is_last_request->());1214}12151216 DONE_GITWEB:12171;1218}12191220run();12211222if(defined caller) {1223# wrapped in a subroutine processing requests,1224# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1225return;1226}else{1227# pure CGI script, serving single request1228exit;1229}12301231## ======================================================================1232## action links12331234# possible values of extra options1235# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1236# -replay => 1 - start from a current view (replay with modifications)1237# -path_info => 0|1 - don't use/use path_info URL (if possible)1238# -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone1239sub href {1240my%params=@_;1241# default is to use -absolute url() i.e. $my_uri1242my$href=$params{-full} ?$my_url:$my_uri;12431244# implicit -replay, must be first of implicit params1245$params{-replay} =1if(keys%params==1&&$params{-anchor});12461247$params{'project'} =$projectunlessexists$params{'project'};12481249if($params{-replay}) {1250while(my($name,$symbol) =each%cgi_param_mapping) {1251if(!exists$params{$name}) {1252$params{$name} =$input_params{$name};1253}1254}1255}12561257my$use_pathinfo= gitweb_check_feature('pathinfo');1258if(defined$params{'project'} &&1259(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1260# try to put as many parameters as possible in PATH_INFO:1261# - project name1262# - action1263# - hash_parent or hash_parent_base:/file_parent1264# - hash or hash_base:/filename1265# - the snapshot_format as an appropriate suffix12661267# When the script is the root DirectoryIndex for the domain,1268# $href here would be something like http://gitweb.example.com/1269# Thus, we strip any trailing / from $href, to spare us double1270# slashes in the final URL1271$href=~ s,/$,,;12721273# Then add the project name, if present1274$href.="/".esc_path_info($params{'project'});1275delete$params{'project'};12761277# since we destructively absorb parameters, we keep this1278# boolean that remembers if we're handling a snapshot1279my$is_snapshot=$params{'action'}eq'snapshot';12801281# Summary just uses the project path URL, any other action is1282# added to the URL1283if(defined$params{'action'}) {1284$href.="/".esc_path_info($params{'action'})1285unless$params{'action'}eq'summary';1286delete$params{'action'};1287}12881289# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1290# stripping nonexistent or useless pieces1291$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1292||$params{'hash_parent'} ||$params{'hash'});1293if(defined$params{'hash_base'}) {1294if(defined$params{'hash_parent_base'}) {1295$href.= esc_path_info($params{'hash_parent_base'});1296# skip the file_parent if it's the same as the file_name1297if(defined$params{'file_parent'}) {1298if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1299delete$params{'file_parent'};1300}elsif($params{'file_parent'} !~/\.\./) {1301$href.=":/".esc_path_info($params{'file_parent'});1302delete$params{'file_parent'};1303}1304}1305$href.="..";1306delete$params{'hash_parent'};1307delete$params{'hash_parent_base'};1308}elsif(defined$params{'hash_parent'}) {1309$href.= esc_path_info($params{'hash_parent'})."..";1310delete$params{'hash_parent'};1311}13121313$href.= esc_path_info($params{'hash_base'});1314if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1315$href.=":/".esc_path_info($params{'file_name'});1316delete$params{'file_name'};1317}1318delete$params{'hash'};1319delete$params{'hash_base'};1320}elsif(defined$params{'hash'}) {1321$href.= esc_path_info($params{'hash'});1322delete$params{'hash'};1323}13241325# If the action was a snapshot, we can absorb the1326# snapshot_format parameter too1327if($is_snapshot) {1328my$fmt=$params{'snapshot_format'};1329# snapshot_format should always be defined when href()1330# is called, but just in case some code forgets, we1331# fall back to the default1332$fmt||=$snapshot_fmts[0];1333$href.=$known_snapshot_formats{$fmt}{'suffix'};1334delete$params{'snapshot_format'};1335}1336}13371338# now encode the parameters explicitly1339my@result= ();1340for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1341my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1342if(defined$params{$name}) {1343if(ref($params{$name})eq"ARRAY") {1344foreachmy$par(@{$params{$name}}) {1345push@result,$symbol."=". esc_param($par);1346}1347}else{1348push@result,$symbol."=". esc_param($params{$name});1349}1350}1351}1352$href.="?".join(';',@result)ifscalar@result;13531354# final transformation: trailing spaces must be escaped (URI-encoded)1355$href=~s/(\s+)$/CGI::escape($1)/e;13561357if($params{-anchor}) {1358$href.="#".esc_param($params{-anchor});1359}13601361return$href;1362}136313641365## ======================================================================1366## validation, quoting/unquoting and escaping13671368sub validate_action {1369my$input=shift||returnundef;1370returnundefunlessexists$actions{$input};1371return$input;1372}13731374sub validate_project {1375my$input=shift||returnundef;1376if(!validate_pathname($input) ||1377!(-d "$projectroot/$input") ||1378!check_export_ok("$projectroot/$input") ||1379($strict_export&& !project_in_list($input))) {1380returnundef;1381}else{1382return$input;1383}1384}13851386sub validate_pathname {1387my$input=shift||returnundef;13881389# no '.' or '..' as elements of path, i.e. no '.' nor '..'1390# at the beginning, at the end, and between slashes.1391# also this catches doubled slashes1392if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1393returnundef;1394}1395# no null characters1396if($input=~m!\0!) {1397returnundef;1398}1399return$input;1400}14011402sub validate_refname {1403my$input=shift||returnundef;14041405# textual hashes are O.K.1406if($input=~m/^[0-9a-fA-F]{40}$/) {1407return$input;1408}1409# it must be correct pathname1410$input= validate_pathname($input)1411orreturnundef;1412# restrictions on ref name according to git-check-ref-format1413if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1414returnundef;1415}1416return$input;1417}14181419# decode sequences of octets in utf8 into Perl's internal form,1420# which is utf-8 with utf8 flag set if needed. gitweb writes out1421# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1422sub to_utf8 {1423my$str=shift;1424returnundefunlessdefined$str;1425if(utf8::valid($str)) {1426 utf8::decode($str);1427return$str;1428}else{1429return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1430}1431}14321433# quote unsafe chars, but keep the slash, even when it's not1434# correct, but quoted slashes look too horrible in bookmarks1435sub esc_param {1436my$str=shift;1437returnundefunlessdefined$str;1438$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1439$str=~s/ /\+/g;1440return$str;1441}14421443# the quoting rules for path_info fragment are slightly different1444sub esc_path_info {1445my$str=shift;1446returnundefunlessdefined$str;14471448# path_info doesn't treat '+' as space (specially), but '?' must be escaped1449$str=~s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;14501451return$str;1452}14531454# quote unsafe chars in whole URL, so some characters cannot be quoted1455sub esc_url {1456my$str=shift;1457returnundefunlessdefined$str;1458$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1459$str=~s/ /\+/g;1460return$str;1461}14621463# quote unsafe characters in HTML attributes1464sub esc_attr {14651466# for XHTML conformance escaping '"' to '"' is not enough1467return esc_html(@_);1468}14691470# replace invalid utf8 character with SUBSTITUTION sequence1471sub esc_html {1472my$str=shift;1473my%opts=@_;14741475returnundefunlessdefined$str;14761477$str= to_utf8($str);1478$str=$cgi->escapeHTML($str);1479if($opts{'-nbsp'}) {1480$str=~s/ / /g;1481}1482$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1483return$str;1484}14851486# quote control characters and escape filename to HTML1487sub esc_path {1488my$str=shift;1489my%opts=@_;14901491returnundefunlessdefined$str;14921493$str= to_utf8($str);1494$str=$cgi->escapeHTML($str);1495if($opts{'-nbsp'}) {1496$str=~s/ / /g;1497}1498$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1499return$str;1500}15011502# Make control characters "printable", using character escape codes (CEC)1503sub quot_cec {1504my$cntrl=shift;1505my%opts=@_;1506my%es= (# character escape codes, aka escape sequences1507"\t"=>'\t',# tab (HT)1508"\n"=>'\n',# line feed (LF)1509"\r"=>'\r',# carrige return (CR)1510"\f"=>'\f',# form feed (FF)1511"\b"=>'\b',# backspace (BS)1512"\a"=>'\a',# alarm (bell) (BEL)1513"\e"=>'\e',# escape (ESC)1514"\013"=>'\v',# vertical tab (VT)1515"\000"=>'\0',# nul character (NUL)1516);1517my$chr= ( (exists$es{$cntrl})1518?$es{$cntrl}1519:sprintf('\%2x',ord($cntrl)) );1520if($opts{-nohtml}) {1521return$chr;1522}else{1523return"<span class=\"cntrl\">$chr</span>";1524}1525}15261527# Alternatively use unicode control pictures codepoints,1528# Unicode "printable representation" (PR)1529sub quot_upr {1530my$cntrl=shift;1531my%opts=@_;15321533my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1534if($opts{-nohtml}) {1535return$chr;1536}else{1537return"<span class=\"cntrl\">$chr</span>";1538}1539}15401541# git may return quoted and escaped filenames1542sub unquote {1543my$str=shift;15441545sub unq {1546my$seq=shift;1547my%es= (# character escape codes, aka escape sequences1548't'=>"\t",# tab (HT, TAB)1549'n'=>"\n",# newline (NL)1550'r'=>"\r",# return (CR)1551'f'=>"\f",# form feed (FF)1552'b'=>"\b",# backspace (BS)1553'a'=>"\a",# alarm (bell) (BEL)1554'e'=>"\e",# escape (ESC)1555'v'=>"\013",# vertical tab (VT)1556);15571558if($seq=~m/^[0-7]{1,3}$/) {1559# octal char sequence1560returnchr(oct($seq));1561}elsif(exists$es{$seq}) {1562# C escape sequence, aka character escape code1563return$es{$seq};1564}1565# quoted ordinary character1566return$seq;1567}15681569if($str=~m/^"(.*)"$/) {1570# needs unquoting1571$str=$1;1572$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1573}1574return$str;1575}15761577# escape tabs (convert tabs to spaces)1578sub untabify {1579my$line=shift;15801581while((my$pos=index($line,"\t")) != -1) {1582if(my$count= (8- ($pos%8))) {1583my$spaces=' ' x $count;1584$line=~s/\t/$spaces/;1585}1586}15871588return$line;1589}15901591sub project_in_list {1592my$project=shift;1593my@list= git_get_projects_list();1594return@list&&scalar(grep{$_->{'path'}eq$project}@list);1595}15961597## ----------------------------------------------------------------------1598## HTML aware string manipulation15991600# Try to chop given string on a word boundary between position1601# $len and $len+$add_len. If there is no word boundary there,1602# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1603# (marking chopped part) would be longer than given string.1604sub chop_str {1605my$str=shift;1606my$len=shift;1607my$add_len=shift||10;1608my$where=shift||'right';# 'left' | 'center' | 'right'16091610# Make sure perl knows it is utf8 encoded so we don't1611# cut in the middle of a utf8 multibyte char.1612$str= to_utf8($str);16131614# allow only $len chars, but don't cut a word if it would fit in $add_len1615# if it doesn't fit, cut it if it's still longer than the dots we would add1616# remove chopped character entities entirely16171618# when chopping in the middle, distribute $len into left and right part1619# return early if chopping wouldn't make string shorter1620if($whereeq'center') {1621return$strif($len+5>=length($str));# filler is length 51622$len=int($len/2);1623}else{1624return$strif($len+4>=length($str));# filler is length 41625}16261627# regexps: ending and beginning with word part up to $add_len1628my$endre=qr/.{$len}\w{0,$add_len}/;1629my$begre=qr/\w{0,$add_len}.{$len}/;16301631if($whereeq'left') {1632$str=~m/^(.*?)($begre)$/;1633my($lead,$body) = ($1,$2);1634if(length($lead) >4) {1635$lead=" ...";1636}1637return"$lead$body";16381639}elsif($whereeq'center') {1640$str=~m/^($endre)(.*)$/;1641my($left,$str) = ($1,$2);1642$str=~m/^(.*?)($begre)$/;1643my($mid,$right) = ($1,$2);1644if(length($mid) >5) {1645$mid=" ... ";1646}1647return"$left$mid$right";16481649}else{1650$str=~m/^($endre)(.*)$/;1651my$body=$1;1652my$tail=$2;1653if(length($tail) >4) {1654$tail="... ";1655}1656return"$body$tail";1657}1658}16591660# takes the same arguments as chop_str, but also wraps a <span> around the1661# result with a title attribute if it does get chopped. Additionally, the1662# string is HTML-escaped.1663sub chop_and_escape_str {1664my($str) =@_;16651666my$chopped= chop_str(@_);1667if($choppedeq$str) {1668return esc_html($chopped);1669}else{1670$str=~s/[[:cntrl:]]/?/g;1671return$cgi->span({-title=>$str}, esc_html($chopped));1672}1673}16741675## ----------------------------------------------------------------------1676## functions returning short strings16771678# CSS class for given age value (in seconds)1679sub age_class {1680my$age=shift;16811682if(!defined$age) {1683return"noage";1684}elsif($age<60*60*2) {1685return"age0";1686}elsif($age<60*60*24*2) {1687return"age1";1688}else{1689return"age2";1690}1691}16921693# convert age in seconds to "nn units ago" string1694sub age_string {1695my$age=shift;1696my$age_str;16971698if($age>60*60*24*365*2) {1699$age_str= (int$age/60/60/24/365);1700$age_str.=" years ago";1701}elsif($age>60*60*24*(365/12)*2) {1702$age_str=int$age/60/60/24/(365/12);1703$age_str.=" months ago";1704}elsif($age>60*60*24*7*2) {1705$age_str=int$age/60/60/24/7;1706$age_str.=" weeks ago";1707}elsif($age>60*60*24*2) {1708$age_str=int$age/60/60/24;1709$age_str.=" days ago";1710}elsif($age>60*60*2) {1711$age_str=int$age/60/60;1712$age_str.=" hours ago";1713}elsif($age>60*2) {1714$age_str=int$age/60;1715$age_str.=" min ago";1716}elsif($age>2) {1717$age_str=int$age;1718$age_str.=" sec ago";1719}else{1720$age_str.=" right now";1721}1722return$age_str;1723}17241725useconstant{1726 S_IFINVALID =>0030000,1727 S_IFGITLINK =>0160000,1728};17291730# submodule/subproject, a commit object reference1731sub S_ISGITLINK {1732my$mode=shift;17331734return(($mode& S_IFMT) == S_IFGITLINK)1735}17361737# convert file mode in octal to symbolic file mode string1738sub mode_str {1739my$mode=oct shift;17401741if(S_ISGITLINK($mode)) {1742return'm---------';1743}elsif(S_ISDIR($mode& S_IFMT)) {1744return'drwxr-xr-x';1745}elsif(S_ISLNK($mode)) {1746return'lrwxrwxrwx';1747}elsif(S_ISREG($mode)) {1748# git cares only about the executable bit1749if($mode& S_IXUSR) {1750return'-rwxr-xr-x';1751}else{1752return'-rw-r--r--';1753};1754}else{1755return'----------';1756}1757}17581759# convert file mode in octal to file type string1760sub file_type {1761my$mode=shift;17621763if($mode!~m/^[0-7]+$/) {1764return$mode;1765}else{1766$mode=oct$mode;1767}17681769if(S_ISGITLINK($mode)) {1770return"submodule";1771}elsif(S_ISDIR($mode& S_IFMT)) {1772return"directory";1773}elsif(S_ISLNK($mode)) {1774return"symlink";1775}elsif(S_ISREG($mode)) {1776return"file";1777}else{1778return"unknown";1779}1780}17811782# convert file mode in octal to file type description string1783sub file_type_long {1784my$mode=shift;17851786if($mode!~m/^[0-7]+$/) {1787return$mode;1788}else{1789$mode=oct$mode;1790}17911792if(S_ISGITLINK($mode)) {1793return"submodule";1794}elsif(S_ISDIR($mode& S_IFMT)) {1795return"directory";1796}elsif(S_ISLNK($mode)) {1797return"symlink";1798}elsif(S_ISREG($mode)) {1799if($mode& S_IXUSR) {1800return"executable";1801}else{1802return"file";1803};1804}else{1805return"unknown";1806}1807}180818091810## ----------------------------------------------------------------------1811## functions returning short HTML fragments, or transforming HTML fragments1812## which don't belong to other sections18131814# format line of commit message.1815sub format_log_line_html {1816my$line=shift;18171818$line= esc_html($line, -nbsp=>1);1819$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1820$cgi->a({-href => href(action=>"object", hash=>$1),1821-class=>"text"},$1);1822}eg;18231824return$line;1825}18261827# format marker of refs pointing to given object18281829# the destination action is chosen based on object type and current context:1830# - for annotated tags, we choose the tag view unless it's the current view1831# already, in which case we go to shortlog view1832# - for other refs, we keep the current view if we're in history, shortlog or1833# log view, and select shortlog otherwise1834sub format_ref_marker {1835my($refs,$id) =@_;1836my$markers='';18371838if(defined$refs->{$id}) {1839foreachmy$ref(@{$refs->{$id}}) {1840# this code exploits the fact that non-lightweight tags are the1841# only indirect objects, and that they are the only objects for which1842# we want to use tag instead of shortlog as action1843my($type,$name) =qw();1844my$indirect= ($ref=~s/\^\{\}$//);1845# e.g. tags/v2.6.11 or heads/next1846if($ref=~m!^(.*?)s?/(.*)$!) {1847$type=$1;1848$name=$2;1849}else{1850$type="ref";1851$name=$ref;1852}18531854my$class=$type;1855$class.=" indirect"if$indirect;18561857my$dest_action="shortlog";18581859if($indirect) {1860$dest_action="tag"unless$actioneq"tag";1861}elsif($action=~/^(history|(short)?log)$/) {1862$dest_action=$action;1863}18641865my$dest="";1866$dest.="refs/"unless$ref=~ m!^refs/!;1867$dest.=$ref;18681869my$link=$cgi->a({1870-href => href(1871 action=>$dest_action,1872 hash=>$dest1873)},$name);18741875$markers.=" <span class=\"".esc_attr($class)."\"title=\"".esc_attr($ref)."\">".1876$link."</span>";1877}1878}18791880if($markers) {1881return' <span class="refs">'.$markers.'</span>';1882}else{1883return"";1884}1885}18861887# format, perhaps shortened and with markers, title line1888sub format_subject_html {1889my($long,$short,$href,$extra) =@_;1890$extra=''unlessdefined($extra);18911892if(length($short) <length($long)) {1893$long=~s/[[:cntrl:]]/?/g;1894return$cgi->a({-href =>$href, -class=>"list subject",1895-title => to_utf8($long)},1896 esc_html($short)) .$extra;1897}else{1898return$cgi->a({-href =>$href, -class=>"list subject"},1899 esc_html($long)) .$extra;1900}1901}19021903# Rather than recomputing the url for an email multiple times, we cache it1904# after the first hit. This gives a visible benefit in views where the avatar1905# for the same email is used repeatedly (e.g. shortlog).1906# The cache is shared by all avatar engines (currently gravatar only), which1907# are free to use it as preferred. Since only one avatar engine is used for any1908# given page, there's no risk for cache conflicts.1909our%avatar_cache= ();19101911# Compute the picon url for a given email, by using the picon search service over at1912# http://www.cs.indiana.edu/picons/search.html1913sub picon_url {1914my$email=lc shift;1915if(!$avatar_cache{$email}) {1916my($user,$domain) =split('@',$email);1917$avatar_cache{$email} =1918"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1919"$domain/$user/".1920"users+domains+unknown/up/single";1921}1922return$avatar_cache{$email};1923}19241925# Compute the gravatar url for a given email, if it's not in the cache already.1926# Gravatar stores only the part of the URL before the size, since that's the1927# one computationally more expensive. This also allows reuse of the cache for1928# different sizes (for this particular engine).1929sub gravatar_url {1930my$email=lc shift;1931my$size=shift;1932$avatar_cache{$email} ||=1933"http://www.gravatar.com/avatar/".1934 Digest::MD5::md5_hex($email) ."?s=";1935return$avatar_cache{$email} .$size;1936}19371938# Insert an avatar for the given $email at the given $size if the feature1939# is enabled.1940sub git_get_avatar {1941my($email,%opts) =@_;1942my$pre_white= ($opts{-pad_before} ?" ":"");1943my$post_white= ($opts{-pad_after} ?" ":"");1944$opts{-size} ||='default';1945my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1946my$url="";1947if($git_avatareq'gravatar') {1948$url= gravatar_url($email,$size);1949}elsif($git_avatareq'picon') {1950$url= picon_url($email);1951}1952# Other providers can be added by extending the if chain, defining $url1953# as needed. If no variant puts something in $url, we assume avatars1954# are completely disabled/unavailable.1955if($url) {1956return$pre_white.1957"<img width=\"$size\"".1958"class=\"avatar\"".1959"src=\"".esc_url($url)."\"".1960"alt=\"\"".1961"/>".$post_white;1962}else{1963return"";1964}1965}19661967sub format_search_author {1968my($author,$searchtype,$displaytext) =@_;1969my$have_search= gitweb_check_feature('search');19701971if($have_search) {1972my$performed="";1973if($searchtypeeq'author') {1974$performed="authored";1975}elsif($searchtypeeq'committer') {1976$performed="committed";1977}19781979return$cgi->a({-href => href(action=>"search", hash=>$hash,1980 searchtext=>$author,1981 searchtype=>$searchtype),class=>"list",1982 title=>"Search for commits$performedby$author"},1983$displaytext);19841985}else{1986return$displaytext;1987}1988}19891990# format the author name of the given commit with the given tag1991# the author name is chopped and escaped according to the other1992# optional parameters (see chop_str).1993sub format_author_html {1994my$tag=shift;1995my$co=shift;1996my$author= chop_and_escape_str($co->{'author_name'},@_);1997return"<$tagclass=\"author\">".1998 format_search_author($co->{'author_name'},"author",1999 git_get_avatar($co->{'author_email'}, -pad_after =>1) .2000$author) .2001"</$tag>";2002}20032004# format git diff header line, i.e. "diff --(git|combined|cc) ..."2005sub format_git_diff_header_line {2006my$line=shift;2007my$diffinfo=shift;2008my($from,$to) =@_;20092010if($diffinfo->{'nparents'}) {2011# combined diff2012$line=~s!^(diff (.*?) )"?.*$!$1!;2013if($to->{'href'}) {2014$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2015 esc_path($to->{'file'}));2016}else{# file was deleted (no href)2017$line.= esc_path($to->{'file'});2018}2019}else{2020# "ordinary" diff2021$line=~s!^(diff (.*?) )"?a/.*$!$1!;2022if($from->{'href'}) {2023$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},2024'a/'. esc_path($from->{'file'}));2025}else{# file was added (no href)2026$line.='a/'. esc_path($from->{'file'});2027}2028$line.=' ';2029if($to->{'href'}) {2030$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2031'b/'. esc_path($to->{'file'}));2032}else{# file was deleted2033$line.='b/'. esc_path($to->{'file'});2034}2035}20362037return"<div class=\"diff header\">$line</div>\n";2038}20392040# format extended diff header line, before patch itself2041sub format_extended_diff_header_line {2042my$line=shift;2043my$diffinfo=shift;2044my($from,$to) =@_;20452046# match <path>2047if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {2048$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},2049 esc_path($from->{'file'}));2050}2051if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {2052$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},2053 esc_path($to->{'file'}));2054}2055# match single <mode>2056if($line=~m/\s(\d{6})$/) {2057$line.='<span class="info"> ('.2058 file_type_long($1) .2059')</span>';2060}2061# match <hash>2062if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {2063# can match only for combined diff2064$line='index ';2065for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2066if($from->{'href'}[$i]) {2067$line.=$cgi->a({-href=>$from->{'href'}[$i],2068-class=>"hash"},2069substr($diffinfo->{'from_id'}[$i],0,7));2070}else{2071$line.='0' x 7;2072}2073# separator2074$line.=','if($i<$diffinfo->{'nparents'} -1);2075}2076$line.='..';2077if($to->{'href'}) {2078$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2079substr($diffinfo->{'to_id'},0,7));2080}else{2081$line.='0' x 7;2082}20832084}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {2085# can match only for ordinary diff2086my($from_link,$to_link);2087if($from->{'href'}) {2088$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},2089substr($diffinfo->{'from_id'},0,7));2090}else{2091$from_link='0' x 7;2092}2093if($to->{'href'}) {2094$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2095substr($diffinfo->{'to_id'},0,7));2096}else{2097$to_link='0' x 7;2098}2099my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});2100$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;2101}21022103return$line."<br/>\n";2104}21052106# format from-file/to-file diff header2107sub format_diff_from_to_header {2108my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2109my$line;2110my$result='';21112112$line=$from_line;2113#assert($line =~ m/^---/) if DEBUG;2114# no extra formatting for "^--- /dev/null"2115if(!$diffinfo->{'nparents'}) {2116# ordinary (single parent) diff2117if($line=~m!^--- "?a/!) {2118if($from->{'href'}) {2119$line='--- a/'.2120$cgi->a({-href=>$from->{'href'}, -class=>"path"},2121 esc_path($from->{'file'}));2122}else{2123$line='--- a/'.2124 esc_path($from->{'file'});2125}2126}2127$result.= qq!<div class="diff from_file">$line</div>\n!;21282129}else{2130# combined diff (merge commit)2131for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2132if($from->{'href'}[$i]) {2133$line='--- '.2134$cgi->a({-href=>href(action=>"blobdiff",2135 hash_parent=>$diffinfo->{'from_id'}[$i],2136 hash_parent_base=>$parents[$i],2137 file_parent=>$from->{'file'}[$i],2138 hash=>$diffinfo->{'to_id'},2139 hash_base=>$hash,2140 file_name=>$to->{'file'}),2141-class=>"path",2142-title=>"diff". ($i+1)},2143$i+1) .2144'/'.2145$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2146 esc_path($from->{'file'}[$i]));2147}else{2148$line='--- /dev/null';2149}2150$result.= qq!<div class="diff from_file">$line</div>\n!;2151}2152}21532154$line=$to_line;2155#assert($line =~ m/^\+\+\+/) if DEBUG;2156# no extra formatting for "^+++ /dev/null"2157if($line=~m!^\+\+\+ "?b/!) {2158if($to->{'href'}) {2159$line='+++ b/'.2160$cgi->a({-href=>$to->{'href'}, -class=>"path"},2161 esc_path($to->{'file'}));2162}else{2163$line='+++ b/'.2164 esc_path($to->{'file'});2165}2166}2167$result.= qq!<div class="diff to_file">$line</div>\n!;21682169return$result;2170}21712172# create note for patch simplified by combined diff2173sub format_diff_cc_simplified {2174my($diffinfo,@parents) =@_;2175my$result='';21762177$result.="<div class=\"diff header\">".2178"diff --cc ";2179if(!is_deleted($diffinfo)) {2180$result.=$cgi->a({-href => href(action=>"blob",2181 hash_base=>$hash,2182 hash=>$diffinfo->{'to_id'},2183 file_name=>$diffinfo->{'to_file'}),2184-class=>"path"},2185 esc_path($diffinfo->{'to_file'}));2186}else{2187$result.= esc_path($diffinfo->{'to_file'});2188}2189$result.="</div>\n".# class="diff header"2190"<div class=\"diff nodifferences\">".2191"Simple merge".2192"</div>\n";# class="diff nodifferences"21932194return$result;2195}21962197# format patch (diff) line (not to be used for diff headers)2198sub format_diff_line {2199my$line=shift;2200my($from,$to) =@_;2201my$diff_class="";22022203chomp$line;22042205if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2206# combined diff2207my$prefix=substr($line,0,scalar@{$from->{'href'}});2208if($line=~m/^\@{3}/) {2209$diff_class=" chunk_header";2210}elsif($line=~m/^\\/) {2211$diff_class=" incomplete";2212}elsif($prefix=~tr/+/+/) {2213$diff_class=" add";2214}elsif($prefix=~tr/-/-/) {2215$diff_class=" rem";2216}2217}else{2218# assume ordinary diff2219my$char=substr($line,0,1);2220if($chareq'+') {2221$diff_class=" add";2222}elsif($chareq'-') {2223$diff_class=" rem";2224}elsif($chareq'@') {2225$diff_class=" chunk_header";2226}elsif($chareq"\\") {2227$diff_class=" incomplete";2228}2229}2230$line= untabify($line);2231if($from&&$to&&$line=~m/^\@{2} /) {2232my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2233$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;22342235$from_lines=0unlessdefined$from_lines;2236$to_lines=0unlessdefined$to_lines;22372238if($from->{'href'}) {2239$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2240-class=>"list"},$from_text);2241}2242if($to->{'href'}) {2243$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2244-class=>"list"},$to_text);2245}2246$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2247"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2248return"<div class=\"diff$diff_class\">$line</div>\n";2249}elsif($from&&$to&&$line=~m/^\@{3}/) {2250my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2251my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);22522253@from_text=split(' ',$ranges);2254for(my$i=0;$i<@from_text; ++$i) {2255($from_start[$i],$from_nlines[$i]) =2256(split(',',substr($from_text[$i],1)),0);2257}22582259$to_text=pop@from_text;2260$to_start=pop@from_start;2261$to_nlines=pop@from_nlines;22622263$line="<span class=\"chunk_info\">$prefix";2264for(my$i=0;$i<@from_text; ++$i) {2265if($from->{'href'}[$i]) {2266$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2267-class=>"list"},$from_text[$i]);2268}else{2269$line.=$from_text[$i];2270}2271$line.=" ";2272}2273if($to->{'href'}) {2274$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2275-class=>"list"},$to_text);2276}else{2277$line.=$to_text;2278}2279$line.="$prefix</span>".2280"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2281return"<div class=\"diff$diff_class\">$line</div>\n";2282}2283return"<div class=\"diff$diff_class\">". esc_html($line, -nbsp=>1) ."</div>\n";2284}22852286# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2287# linked. Pass the hash of the tree/commit to snapshot.2288sub format_snapshot_links {2289my($hash) =@_;2290my$num_fmts=@snapshot_fmts;2291if($num_fmts>1) {2292# A parenthesized list of links bearing format names.2293# e.g. "snapshot (_tar.gz_ _zip_)"2294return"snapshot (".join(' ',map2295$cgi->a({2296-href => href(2297 action=>"snapshot",2298 hash=>$hash,2299 snapshot_format=>$_2300)2301},$known_snapshot_formats{$_}{'display'})2302,@snapshot_fmts) .")";2303}elsif($num_fmts==1) {2304# A single "snapshot" link whose tooltip bears the format name.2305# i.e. "_snapshot_"2306my($fmt) =@snapshot_fmts;2307return2308$cgi->a({2309-href => href(2310 action=>"snapshot",2311 hash=>$hash,2312 snapshot_format=>$fmt2313),2314-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2315},"snapshot");2316}else{# $num_fmts == 02317returnundef;2318}2319}23202321## ......................................................................2322## functions returning values to be passed, perhaps after some2323## transformation, to other functions; e.g. returning arguments to href()23242325# returns hash to be passed to href to generate gitweb URL2326# in -title key it returns description of link2327sub get_feed_info {2328my$format=shift||'Atom';2329my%res= (action =>lc($format));23302331# feed links are possible only for project views2332return unless(defined$project);2333# some views should link to OPML, or to generic project feed,2334# or don't have specific feed yet (so they should use generic)2335return if($action=~/^(?:tags|heads|forks|tag|search)$/x);23362337my$branch;2338# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2339# from tag links; this also makes possible to detect branch links2340if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2341(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2342$branch=$1;2343}2344# find log type for feed description (title)2345my$type='log';2346if(defined$file_name) {2347$type="history of$file_name";2348$type.="/"if($actioneq'tree');2349$type.=" on '$branch'"if(defined$branch);2350}else{2351$type="log of$branch"if(defined$branch);2352}23532354$res{-title} =$type;2355$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2356$res{'file_name'} =$file_name;23572358return%res;2359}23602361## ----------------------------------------------------------------------2362## git utility subroutines, invoking git commands23632364# returns path to the core git executable and the --git-dir parameter as list2365sub git_cmd {2366$number_of_git_cmds++;2367return$GIT,'--git-dir='.$git_dir;2368}23692370# quote the given arguments for passing them to the shell2371# quote_command("command", "arg 1", "arg with ' and ! characters")2372# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2373# Try to avoid using this function wherever possible.2374sub quote_command {2375returnjoin(' ',2376map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2377}23782379# get HEAD ref of given project as hash2380sub git_get_head_hash {2381return git_get_full_hash(shift,'HEAD');2382}23832384sub git_get_full_hash {2385return git_get_hash(@_);2386}23872388sub git_get_short_hash {2389return git_get_hash(@_,'--short=7');2390}23912392sub git_get_hash {2393my($project,$hash,@options) =@_;2394my$o_git_dir=$git_dir;2395my$retval=undef;2396$git_dir="$projectroot/$project";2397if(open my$fd,'-|', git_cmd(),'rev-parse',2398'--verify','-q',@options,$hash) {2399$retval= <$fd>;2400chomp$retvalifdefined$retval;2401close$fd;2402}2403if(defined$o_git_dir) {2404$git_dir=$o_git_dir;2405}2406return$retval;2407}24082409# get type of given object2410sub git_get_type {2411my$hash=shift;24122413open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2414my$type= <$fd>;2415close$fdorreturn;2416chomp$type;2417return$type;2418}24192420# repository configuration2421our$config_file='';2422our%config;24232424# store multiple values for single key as anonymous array reference2425# single values stored directly in the hash, not as [ <value> ]2426sub hash_set_multi {2427my($hash,$key,$value) =@_;24282429if(!exists$hash->{$key}) {2430$hash->{$key} =$value;2431}elsif(!ref$hash->{$key}) {2432$hash->{$key} = [$hash->{$key},$value];2433}else{2434push@{$hash->{$key}},$value;2435}2436}24372438# return hash of git project configuration2439# optionally limited to some section, e.g. 'gitweb'2440sub git_parse_project_config {2441my$section_regexp=shift;2442my%config;24432444local$/="\0";24452446open my$fh,"-|", git_cmd(),"config",'-z','-l',2447orreturn;24482449while(my$keyval= <$fh>) {2450chomp$keyval;2451my($key,$value) =split(/\n/,$keyval,2);24522453 hash_set_multi(\%config,$key,$value)2454if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2455}2456close$fh;24572458return%config;2459}24602461# convert config value to boolean: 'true' or 'false'2462# no value, number > 0, 'true' and 'yes' values are true2463# rest of values are treated as false (never as error)2464sub config_to_bool {2465my$val=shift;24662467return1if!defined$val;# section.key24682469# strip leading and trailing whitespace2470$val=~s/^\s+//;2471$val=~s/\s+$//;24722473return(($val=~/^\d+$/&&$val) ||# section.key = 12474($val=~/^(?:true|yes)$/i));# section.key = true2475}24762477# convert config value to simple decimal number2478# an optional value suffix of 'k', 'm', or 'g' will cause the value2479# to be multiplied by 1024, 1048576, or 10737418242480sub config_to_int {2481my$val=shift;24822483# strip leading and trailing whitespace2484$val=~s/^\s+//;2485$val=~s/\s+$//;24862487if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2488$unit=lc($unit);2489# unknown unit is treated as 12490return$num* ($uniteq'g'?1073741824:2491$uniteq'm'?1048576:2492$uniteq'k'?1024:1);2493}2494return$val;2495}24962497# convert config value to array reference, if needed2498sub config_to_multi {2499my$val=shift;25002501returnref($val) ?$val: (defined($val) ? [$val] : []);2502}25032504sub git_get_project_config {2505my($key,$type) =@_;25062507return unlessdefined$git_dir;25082509# key sanity check2510return unless($key);2511$key=~s/^gitweb\.//;2512return if($key=~m/\W/);25132514# type sanity check2515if(defined$type) {2516$type=~s/^--//;2517$type=undef2518unless($typeeq'bool'||$typeeq'int');2519}25202521# get config2522if(!defined$config_file||2523$config_filene"$git_dir/config") {2524%config= git_parse_project_config('gitweb');2525$config_file="$git_dir/config";2526}25272528# check if config variable (key) exists2529return unlessexists$config{"gitweb.$key"};25302531# ensure given type2532if(!defined$type) {2533return$config{"gitweb.$key"};2534}elsif($typeeq'bool') {2535# backward compatibility: 'git config --bool' returns true/false2536return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2537}elsif($typeeq'int') {2538return config_to_int($config{"gitweb.$key"});2539}2540return$config{"gitweb.$key"};2541}25422543# get hash of given path at given ref2544sub git_get_hash_by_path {2545my$base=shift;2546my$path=shift||returnundef;2547my$type=shift;25482549$path=~ s,/+$,,;25502551open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2552or die_error(500,"Open git-ls-tree failed");2553my$line= <$fd>;2554close$fdorreturnundef;25552556if(!defined$line) {2557# there is no tree or hash given by $path at $base2558returnundef;2559}25602561#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2562$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2563if(defined$type&&$typene$2) {2564# type doesn't match2565returnundef;2566}2567return$3;2568}25692570# get path of entry with given hash at given tree-ish (ref)2571# used to get 'from' filename for combined diff (merge commit) for renames2572sub git_get_path_by_hash {2573my$base=shift||return;2574my$hash=shift||return;25752576local$/="\0";25772578open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2579orreturnundef;2580while(my$line= <$fd>) {2581chomp$line;25822583#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2584#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2585if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2586close$fd;2587return$1;2588}2589}2590close$fd;2591returnundef;2592}25932594## ......................................................................2595## git utility functions, directly accessing git repository25962597# get the value of config variable either from file named as the variable2598# itself in the repository ($GIT_DIR/$name file), or from gitweb.$name2599# configuration variable in the repository config file.2600sub git_get_file_or_project_config {2601my($path,$name) =@_;26022603$git_dir="$projectroot/$path";2604open my$fd,'<',"$git_dir/$name"2605orreturn git_get_project_config($name);2606my$conf= <$fd>;2607close$fd;2608if(defined$conf) {2609chomp$conf;2610}2611return$conf;2612}26132614sub git_get_project_description {2615my$path=shift;2616return git_get_file_or_project_config($path,'description');2617}26182619sub git_get_project_category {2620my$path=shift;2621return git_get_file_or_project_config($path,'category');2622}262326242625# supported formats:2626# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2627# - if its contents is a number, use it as tag weight,2628# - otherwise add a tag with weight 12629# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2630# the same value multiple times increases tag weight2631# * `gitweb.ctag' multi-valued repo config variable2632sub git_get_project_ctags {2633my$project=shift;2634my$ctags= {};26352636$git_dir="$projectroot/$project";2637if(opendir my$dh,"$git_dir/ctags") {2638my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2639foreachmy$tagfile(@files) {2640open my$ct,'<',$tagfile2641ornext;2642my$val= <$ct>;2643chomp$valif$val;2644close$ct;26452646(my$ctag=$tagfile) =~ s#.*/##;2647if($val=~/\d+/) {2648$ctags->{$ctag} =$val;2649}else{2650$ctags->{$ctag} =1;2651}2652}2653closedir$dh;26542655}elsif(open my$fh,'<',"$git_dir/ctags") {2656while(my$line= <$fh>) {2657chomp$line;2658$ctags->{$line}++if$line;2659}2660close$fh;26612662}else{2663my$taglist= config_to_multi(git_get_project_config('ctag'));2664foreachmy$tag(@$taglist) {2665$ctags->{$tag}++;2666}2667}26682669return$ctags;2670}26712672# return hash, where keys are content tags ('ctags'),2673# and values are sum of weights of given tag in every project2674sub git_gather_all_ctags {2675my$projects=shift;2676my$ctags= {};26772678foreachmy$p(@$projects) {2679foreachmy$ct(keys%{$p->{'ctags'}}) {2680$ctags->{$ct} +=$p->{'ctags'}->{$ct};2681}2682}26832684return$ctags;2685}26862687sub git_populate_project_tagcloud {2688my$ctags=shift;26892690# First, merge different-cased tags; tags vote on casing2691my%ctags_lc;2692foreach(keys%$ctags) {2693$ctags_lc{lc$_}->{count} +=$ctags->{$_};2694if(not$ctags_lc{lc$_}->{topcount}2695or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2696$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2697$ctags_lc{lc$_}->{topname} =$_;2698}2699}27002701my$cloud;2702my$matched=$cgi->param('by_tag');2703if(eval{require HTML::TagCloud;1; }) {2704$cloud= HTML::TagCloud->new;2705foreachmy$ctag(sort keys%ctags_lc) {2706# Pad the title with spaces so that the cloud looks2707# less crammed.2708my$title= esc_html($ctags_lc{$ctag}->{topname});2709$title=~s/ / /g;2710$title=~s/^/ /g;2711$title=~s/$/ /g;2712if(defined$matched&&$matchedeq$ctag) {2713$title=qq(<span class="match">$title</span>);2714}2715$cloud->add($title, href(project=>undef, ctag=>$ctag),2716$ctags_lc{$ctag}->{count});2717}2718}else{2719$cloud= {};2720foreachmy$ctag(keys%ctags_lc) {2721my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2722if(defined$matched&&$matchedeq$ctag) {2723$title=qq(<span class="match">$title</span>);2724}2725$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};2726$cloud->{$ctag}{ctag} =2727$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);2728}2729}2730return$cloud;2731}27322733sub git_show_project_tagcloud {2734my($cloud,$count) =@_;2735if(ref$cloudeq'HTML::TagCloud') {2736return$cloud->html_and_css($count);2737}else{2738my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;2739return2740'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.2741join(', ',map{2742$cloud->{$_}->{'ctag'}2743}splice(@tags,0,$count)) .2744'</div>';2745}2746}27472748sub git_get_project_url_list {2749my$path=shift;27502751$git_dir="$projectroot/$path";2752open my$fd,'<',"$git_dir/cloneurl"2753orreturnwantarray?2754@{ config_to_multi(git_get_project_config('url')) } :2755 config_to_multi(git_get_project_config('url'));2756my@git_project_url_list=map{chomp;$_} <$fd>;2757close$fd;27582759returnwantarray?@git_project_url_list: \@git_project_url_list;2760}27612762sub git_get_projects_list {2763my$filter=shift||'';2764my@list;27652766$filter=~s/\.git$//;27672768if(-d $projects_list) {2769# search in directory2770my$dir=$projects_list;2771# remove the trailing "/"2772$dir=~s!/+$!!;2773my$pfxlen=length("$projects_list");2774my$pfxdepth= ($projects_list=~tr!/!!);2775# when filtering, search only given subdirectory2776if($filter) {2777$dir.="/$filter";2778$dir=~s!/+$!!;2779}27802781 File::Find::find({2782 follow_fast =>1,# follow symbolic links2783 follow_skip =>2,# ignore duplicates2784 dangling_symlinks =>0,# ignore dangling symlinks, silently2785 wanted =>sub{2786# global variables2787our$project_maxdepth;2788our$projectroot;2789# skip project-list toplevel, if we get it.2790return if(m!^[/.]$!);2791# only directories can be git repositories2792return unless(-d $_);2793# don't traverse too deep (Find is super slow on os x)2794# $project_maxdepth excludes depth of $projectroot2795if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2796$File::Find::prune =1;2797return;2798}27992800my$path=substr($File::Find::name,$pfxlen+1);2801# we check related file in $projectroot2802if(check_export_ok("$projectroot/$path")) {2803push@list, { path =>$path};2804$File::Find::prune =1;2805}2806},2807},"$dir");28082809}elsif(-f $projects_list) {2810# read from file(url-encoded):2811# 'git%2Fgit.git Linus+Torvalds'2812# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2813# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2814open my$fd,'<',$projects_listorreturn;2815 PROJECT:2816while(my$line= <$fd>) {2817chomp$line;2818my($path,$owner) =split' ',$line;2819$path= unescape($path);2820$owner= unescape($owner);2821if(!defined$path) {2822next;2823}2824# if $filter is rpovided, check if $path begins with $filter2825if($filter&&$path!~m!^\Q$filter\E/!) {2826next;2827}2828if(check_export_ok("$projectroot/$path")) {2829my$pr= {2830 path =>$path,2831 owner => to_utf8($owner),2832};2833push@list,$pr;2834}2835}2836close$fd;2837}2838return@list;2839}28402841# written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)2842# as side effects it sets 'forks' field to list of forks for forked projects2843sub filter_forks_from_projects_list {2844my$projects=shift;28452846my%trie;# prefix tree of directories (path components)2847# generate trie out of those directories that might contain forks2848foreachmy$pr(@$projects) {2849my$path=$pr->{'path'};2850$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory2851next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'2852next unless($path);# skip '.git' repository: tests, git-instaweb2853next unless(-d $path);# containing directory exists2854$pr->{'forks'} = [];# there can be 0 or more forks of project28552856# add to trie2857my@dirs=split('/',$path);2858# walk the trie, until either runs out of components or out of trie2859my$ref= \%trie;2860while(scalar@dirs&&2861exists($ref->{$dirs[0]})) {2862$ref=$ref->{shift@dirs};2863}2864# create rest of trie structure from rest of components2865foreachmy$dir(@dirs) {2866$ref=$ref->{$dir} = {};2867}2868# create end marker, store $pr as a data2869$ref->{''} =$prif(!exists$ref->{''});2870}28712872# filter out forks, by finding shortest prefix match for paths2873my@filtered;2874 PROJECT:2875foreachmy$pr(@$projects) {2876# trie lookup2877my$ref= \%trie;2878 DIR:2879foreachmy$dir(split('/',$pr->{'path'})) {2880if(exists$ref->{''}) {2881# found [shortest] prefix, is a fork - skip it2882push@{$ref->{''}{'forks'}},$pr;2883next PROJECT;2884}2885if(!exists$ref->{$dir}) {2886# not in trie, cannot have prefix, not a fork2887push@filtered,$pr;2888next PROJECT;2889}2890# If the dir is there, we just walk one step down the trie.2891$ref=$ref->{$dir};2892}2893# we ran out of trie2894# (shouldn't happen: it's either no match, or end marker)2895push@filtered,$pr;2896}28972898return@filtered;2899}29002901# note: fill_project_list_info must be run first,2902# for 'descr_long' and 'ctags' to be filled2903sub search_projects_list {2904my($projlist,%opts) =@_;2905my$tagfilter=$opts{'tagfilter'};2906my$searchtext=$opts{'searchtext'};29072908return@$projlist2909unless($tagfilter||$searchtext);29102911my@projects;2912 PROJECT:2913foreachmy$pr(@$projlist) {29142915if($tagfilter) {2916next unlessref($pr->{'ctags'})eq'HASH';2917next unless2918grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};2919}29202921if($searchtext) {2922next unless2923$pr->{'path'} =~/$searchtext/||2924$pr->{'descr_long'} =~/$searchtext/;2925}29262927push@projects,$pr;2928}29292930return@projects;2931}29322933our$gitweb_project_owner=undef;2934sub git_get_project_list_from_file {29352936return if(defined$gitweb_project_owner);29372938$gitweb_project_owner= {};2939# read from file (url-encoded):2940# 'git%2Fgit.git Linus+Torvalds'2941# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2942# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2943if(-f $projects_list) {2944open(my$fd,'<',$projects_list);2945while(my$line= <$fd>) {2946chomp$line;2947my($pr,$ow) =split' ',$line;2948$pr= unescape($pr);2949$ow= unescape($ow);2950$gitweb_project_owner->{$pr} = to_utf8($ow);2951}2952close$fd;2953}2954}29552956sub git_get_project_owner {2957my$project=shift;2958my$owner;29592960returnundefunless$project;2961$git_dir="$projectroot/$project";29622963if(!defined$gitweb_project_owner) {2964 git_get_project_list_from_file();2965}29662967if(exists$gitweb_project_owner->{$project}) {2968$owner=$gitweb_project_owner->{$project};2969}2970if(!defined$owner){2971$owner= git_get_project_config('owner');2972}2973if(!defined$owner) {2974$owner= get_file_owner("$git_dir");2975}29762977return$owner;2978}29792980sub git_get_last_activity {2981my($path) =@_;2982my$fd;29832984$git_dir="$projectroot/$path";2985open($fd,"-|", git_cmd(),'for-each-ref',2986'--format=%(committer)',2987'--sort=-committerdate',2988'--count=1',2989'refs/heads')orreturn;2990my$most_recent= <$fd>;2991close$fdorreturn;2992if(defined$most_recent&&2993$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {2994my$timestamp=$1;2995my$age=time-$timestamp;2996return($age, age_string($age));2997}2998return(undef,undef);2999}30003001# Implementation note: when a single remote is wanted, we cannot use 'git3002# remote show -n' because that command always work (assuming it's a remote URL3003# if it's not defined), and we cannot use 'git remote show' because that would3004# try to make a network roundtrip. So the only way to find if that particular3005# remote is defined is to walk the list provided by 'git remote -v' and stop if3006# and when we find what we want.3007sub git_get_remotes_list {3008my$wanted=shift;3009my%remotes= ();30103011open my$fd,'-|', git_cmd(),'remote','-v';3012return unless$fd;3013while(my$remote= <$fd>) {3014chomp$remote;3015$remote=~s!\t(.*?)\s+\((\w+)\)$!!;3016next if$wantedand not$remoteeq$wanted;3017my($url,$key) = ($1,$2);30183019$remotes{$remote} ||= {'heads'=> () };3020$remotes{$remote}{$key} =$url;3021}3022close$fdorreturn;3023returnwantarray?%remotes: \%remotes;3024}30253026# Takes a hash of remotes as first parameter and fills it by adding the3027# available remote heads for each of the indicated remotes.3028sub fill_remote_heads {3029my$remotes=shift;3030my@heads=map{"remotes/$_"}keys%$remotes;3031my@remoteheads= git_get_heads_list(undef,@heads);3032foreachmy$remote(keys%$remotes) {3033$remotes->{$remote}{'heads'} = [grep{3034$_->{'name'} =~s!^$remote/!!3035}@remoteheads];3036}3037}30383039sub git_get_references {3040my$type=shift||"";3041my%refs;3042# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113043# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3044open my$fd,"-|", git_cmd(),"show-ref","--dereference",3045($type? ("--","refs/$type") : ())# use -- <pattern> if $type3046orreturn;30473048while(my$line= <$fd>) {3049chomp$line;3050if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3051if(defined$refs{$1}) {3052push@{$refs{$1}},$2;3053}else{3054$refs{$1} = [$2];3055}3056}3057}3058close$fdorreturn;3059return \%refs;3060}30613062sub git_get_rev_name_tags {3063my$hash=shift||returnundef;30643065open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3066orreturn;3067my$name_rev= <$fd>;3068close$fd;30693070if($name_rev=~ m|^$hash tags/(.*)$|) {3071return$1;3072}else{3073# catches also '$hash undefined' output3074returnundef;3075}3076}30773078## ----------------------------------------------------------------------3079## parse to hash functions30803081sub parse_date {3082my$epoch=shift;3083my$tz=shift||"-0000";30843085my%date;3086my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3087my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3088my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3089$date{'hour'} =$hour;3090$date{'minute'} =$min;3091$date{'mday'} =$mday;3092$date{'day'} =$days[$wday];3093$date{'month'} =$months[$mon];3094$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3095$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3096$date{'mday-time'} =sprintf"%d%s%02d:%02d",3097$mday,$months[$mon],$hour,$min;3098$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",30991900+$year,1+$mon,$mday,$hour,$min,$sec;31003101my($tz_sign,$tz_hour,$tz_min) =3102($tz=~m/^([-+])(\d\d)(\d\d)$/);3103$tz_sign= ($tz_signeq'-'? -1: +1);3104my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3105($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3106$date{'hour_local'} =$hour;3107$date{'minute_local'} =$min;3108$date{'tz_local'} =$tz;3109$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",31101900+$year,$mon+1,$mday,3111$hour,$min,$sec,$tz);3112return%date;3113}31143115sub parse_tag {3116my$tag_id=shift;3117my%tag;3118my@comment;31193120open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3121$tag{'id'} =$tag_id;3122while(my$line= <$fd>) {3123chomp$line;3124if($line=~m/^object ([0-9a-fA-F]{40})$/) {3125$tag{'object'} =$1;3126}elsif($line=~m/^type (.+)$/) {3127$tag{'type'} =$1;3128}elsif($line=~m/^tag (.+)$/) {3129$tag{'name'} =$1;3130}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3131$tag{'author'} =$1;3132$tag{'author_epoch'} =$2;3133$tag{'author_tz'} =$3;3134if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3135$tag{'author_name'} =$1;3136$tag{'author_email'} =$2;3137}else{3138$tag{'author_name'} =$tag{'author'};3139}3140}elsif($line=~m/--BEGIN/) {3141push@comment,$line;3142last;3143}elsif($lineeq"") {3144last;3145}3146}3147push@comment, <$fd>;3148$tag{'comment'} = \@comment;3149close$fdorreturn;3150if(!defined$tag{'name'}) {3151return3152};3153return%tag3154}31553156sub parse_commit_text {3157my($commit_text,$withparents) =@_;3158my@commit_lines=split'\n',$commit_text;3159my%co;31603161pop@commit_lines;# Remove '\0'31623163if(!@commit_lines) {3164return;3165}31663167my$header=shift@commit_lines;3168if($header!~m/^[0-9a-fA-F]{40}/) {3169return;3170}3171($co{'id'},my@parents) =split' ',$header;3172while(my$line=shift@commit_lines) {3173last if$lineeq"\n";3174if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3175$co{'tree'} =$1;3176}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3177push@parents,$1;3178}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3179$co{'author'} = to_utf8($1);3180$co{'author_epoch'} =$2;3181$co{'author_tz'} =$3;3182if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3183$co{'author_name'} =$1;3184$co{'author_email'} =$2;3185}else{3186$co{'author_name'} =$co{'author'};3187}3188}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3189$co{'committer'} = to_utf8($1);3190$co{'committer_epoch'} =$2;3191$co{'committer_tz'} =$3;3192if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3193$co{'committer_name'} =$1;3194$co{'committer_email'} =$2;3195}else{3196$co{'committer_name'} =$co{'committer'};3197}3198}3199}3200if(!defined$co{'tree'}) {3201return;3202};3203$co{'parents'} = \@parents;3204$co{'parent'} =$parents[0];32053206foreachmy$title(@commit_lines) {3207$title=~s/^ //;3208if($titlene"") {3209$co{'title'} = chop_str($title,80,5);3210# remove leading stuff of merges to make the interesting part visible3211if(length($title) >50) {3212$title=~s/^Automatic //;3213$title=~s/^merge (of|with) /Merge ... /i;3214if(length($title) >50) {3215$title=~s/(http|rsync):\/\///;3216}3217if(length($title) >50) {3218$title=~s/(master|www|rsync)\.//;3219}3220if(length($title) >50) {3221$title=~s/kernel.org:?//;3222}3223if(length($title) >50) {3224$title=~s/\/pub\/scm//;3225}3226}3227$co{'title_short'} = chop_str($title,50,5);3228last;3229}3230}3231if(!defined$co{'title'} ||$co{'title'}eq"") {3232$co{'title'} =$co{'title_short'} ='(no commit message)';3233}3234# remove added spaces3235foreachmy$line(@commit_lines) {3236$line=~s/^ //;3237}3238$co{'comment'} = \@commit_lines;32393240my$age=time-$co{'committer_epoch'};3241$co{'age'} =$age;3242$co{'age_string'} = age_string($age);3243my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3244if($age>60*60*24*7*2) {3245$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3246$co{'age_string_age'} =$co{'age_string'};3247}else{3248$co{'age_string_date'} =$co{'age_string'};3249$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3250}3251return%co;3252}32533254sub parse_commit {3255my($commit_id) =@_;3256my%co;32573258local$/="\0";32593260open my$fd,"-|", git_cmd(),"rev-list",3261"--parents",3262"--header",3263"--max-count=1",3264$commit_id,3265"--",3266or die_error(500,"Open git-rev-list failed");3267%co= parse_commit_text(<$fd>,1);3268close$fd;32693270return%co;3271}32723273sub parse_commits {3274my($commit_id,$maxcount,$skip,$filename,@args) =@_;3275my@cos;32763277$maxcount||=1;3278$skip||=0;32793280local$/="\0";32813282open my$fd,"-|", git_cmd(),"rev-list",3283"--header",3284@args,3285("--max-count=".$maxcount),3286("--skip=".$skip),3287@extra_options,3288$commit_id,3289"--",3290($filename? ($filename) : ())3291or die_error(500,"Open git-rev-list failed");3292while(my$line= <$fd>) {3293my%co= parse_commit_text($line);3294push@cos, \%co;3295}3296close$fd;32973298returnwantarray?@cos: \@cos;3299}33003301# parse line of git-diff-tree "raw" output3302sub parse_difftree_raw_line {3303my$line=shift;3304my%res;33053306# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3307# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3308if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3309$res{'from_mode'} =$1;3310$res{'to_mode'} =$2;3311$res{'from_id'} =$3;3312$res{'to_id'} =$4;3313$res{'status'} =$5;3314$res{'similarity'} =$6;3315if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3316($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3317}else{3318$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3319}3320}3321# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3322# combined diff (for merge commit)3323elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3324$res{'nparents'} =length($1);3325$res{'from_mode'} = [split(' ',$2) ];3326$res{'to_mode'} =pop@{$res{'from_mode'}};3327$res{'from_id'} = [split(' ',$3) ];3328$res{'to_id'} =pop@{$res{'from_id'}};3329$res{'status'} = [split('',$4) ];3330$res{'to_file'} = unquote($5);3331}3332# 'c512b523472485aef4fff9e57b229d9d243c967f'3333elsif($line=~m/^([0-9a-fA-F]{40})$/) {3334$res{'commit'} =$1;3335}33363337returnwantarray?%res: \%res;3338}33393340# wrapper: return parsed line of git-diff-tree "raw" output3341# (the argument might be raw line, or parsed info)3342sub parsed_difftree_line {3343my$line_or_ref=shift;33443345if(ref($line_or_ref)eq"HASH") {3346# pre-parsed (or generated by hand)3347return$line_or_ref;3348}else{3349return parse_difftree_raw_line($line_or_ref);3350}3351}33523353# parse line of git-ls-tree output3354sub parse_ls_tree_line {3355my$line=shift;3356my%opts=@_;3357my%res;33583359if($opts{'-l'}) {3360#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3361$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;33623363$res{'mode'} =$1;3364$res{'type'} =$2;3365$res{'hash'} =$3;3366$res{'size'} =$4;3367if($opts{'-z'}) {3368$res{'name'} =$5;3369}else{3370$res{'name'} = unquote($5);3371}3372}else{3373#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3374$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;33753376$res{'mode'} =$1;3377$res{'type'} =$2;3378$res{'hash'} =$3;3379if($opts{'-z'}) {3380$res{'name'} =$4;3381}else{3382$res{'name'} = unquote($4);3383}3384}33853386returnwantarray?%res: \%res;3387}33883389# generates _two_ hashes, references to which are passed as 2 and 3 argument3390sub parse_from_to_diffinfo {3391my($diffinfo,$from,$to,@parents) =@_;33923393if($diffinfo->{'nparents'}) {3394# combined diff3395$from->{'file'} = [];3396$from->{'href'} = [];3397 fill_from_file_info($diffinfo,@parents)3398unlessexists$diffinfo->{'from_file'};3399for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3400$from->{'file'}[$i] =3401defined$diffinfo->{'from_file'}[$i] ?3402$diffinfo->{'from_file'}[$i] :3403$diffinfo->{'to_file'};3404if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3405$from->{'href'}[$i] = href(action=>"blob",3406 hash_base=>$parents[$i],3407 hash=>$diffinfo->{'from_id'}[$i],3408 file_name=>$from->{'file'}[$i]);3409}else{3410$from->{'href'}[$i] =undef;3411}3412}3413}else{3414# ordinary (not combined) diff3415$from->{'file'} =$diffinfo->{'from_file'};3416if($diffinfo->{'status'}ne"A") {# not new (added) file3417$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3418 hash=>$diffinfo->{'from_id'},3419 file_name=>$from->{'file'});3420}else{3421delete$from->{'href'};3422}3423}34243425$to->{'file'} =$diffinfo->{'to_file'};3426if(!is_deleted($diffinfo)) {# file exists in result3427$to->{'href'} = href(action=>"blob", hash_base=>$hash,3428 hash=>$diffinfo->{'to_id'},3429 file_name=>$to->{'file'});3430}else{3431delete$to->{'href'};3432}3433}34343435## ......................................................................3436## parse to array of hashes functions34373438sub git_get_heads_list {3439my($limit,@classes) =@_;3440@classes= ('heads')unless@classes;3441my@patterns=map{"refs/$_"}@classes;3442my@headslist;34433444open my$fd,'-|', git_cmd(),'for-each-ref',3445($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3446'--format=%(objectname) %(refname) %(subject)%00%(committer)',3447@patterns3448orreturn;3449while(my$line= <$fd>) {3450my%ref_item;34513452chomp$line;3453my($refinfo,$committerinfo) =split(/\0/,$line);3454my($hash,$name,$title) =split(' ',$refinfo,3);3455my($committer,$epoch,$tz) =3456($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3457$ref_item{'fullname'} =$name;3458$name=~s!^refs/(?:head|remote)s/!!;34593460$ref_item{'name'} =$name;3461$ref_item{'id'} =$hash;3462$ref_item{'title'} =$title||'(no commit message)';3463$ref_item{'epoch'} =$epoch;3464if($epoch) {3465$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3466}else{3467$ref_item{'age'} ="unknown";3468}34693470push@headslist, \%ref_item;3471}3472close$fd;34733474returnwantarray?@headslist: \@headslist;3475}34763477sub git_get_tags_list {3478my$limit=shift;3479my@tagslist;34803481open my$fd,'-|', git_cmd(),'for-each-ref',3482($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3483'--format=%(objectname) %(objecttype) %(refname) '.3484'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3485'refs/tags'3486orreturn;3487while(my$line= <$fd>) {3488my%ref_item;34893490chomp$line;3491my($refinfo,$creatorinfo) =split(/\0/,$line);3492my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3493my($creator,$epoch,$tz) =3494($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3495$ref_item{'fullname'} =$name;3496$name=~s!^refs/tags/!!;34973498$ref_item{'type'} =$type;3499$ref_item{'id'} =$id;3500$ref_item{'name'} =$name;3501if($typeeq"tag") {3502$ref_item{'subject'} =$title;3503$ref_item{'reftype'} =$reftype;3504$ref_item{'refid'} =$refid;3505}else{3506$ref_item{'reftype'} =$type;3507$ref_item{'refid'} =$id;3508}35093510if($typeeq"tag"||$typeeq"commit") {3511$ref_item{'epoch'} =$epoch;3512if($epoch) {3513$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3514}else{3515$ref_item{'age'} ="unknown";3516}3517}35183519push@tagslist, \%ref_item;3520}3521close$fd;35223523returnwantarray?@tagslist: \@tagslist;3524}35253526## ----------------------------------------------------------------------3527## filesystem-related functions35283529sub get_file_owner {3530my$path=shift;35313532my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3533my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3534if(!defined$gcos) {3535returnundef;3536}3537my$owner=$gcos;3538$owner=~s/[,;].*$//;3539return to_utf8($owner);3540}35413542# assume that file exists3543sub insert_file {3544my$filename=shift;35453546open my$fd,'<',$filename;3547print map{ to_utf8($_) } <$fd>;3548close$fd;3549}35503551## ......................................................................3552## mimetype related functions35533554sub mimetype_guess_file {3555my$filename=shift;3556my$mimemap=shift;3557-r $mimemaporreturnundef;35583559my%mimemap;3560open(my$mh,'<',$mimemap)orreturnundef;3561while(<$mh>) {3562next ifm/^#/;# skip comments3563my($mimetype,$exts) =split(/\t+/);3564if(defined$exts) {3565my@exts=split(/\s+/,$exts);3566foreachmy$ext(@exts) {3567$mimemap{$ext} =$mimetype;3568}3569}3570}3571close($mh);35723573$filename=~/\.([^.]*)$/;3574return$mimemap{$1};3575}35763577sub mimetype_guess {3578my$filename=shift;3579my$mime;3580$filename=~/\./orreturnundef;35813582if($mimetypes_file) {3583my$file=$mimetypes_file;3584if($file!~m!^/!) {# if it is relative path3585# it is relative to project3586$file="$projectroot/$project/$file";3587}3588$mime= mimetype_guess_file($filename,$file);3589}3590$mime||= mimetype_guess_file($filename,'/etc/mime.types');3591return$mime;3592}35933594sub blob_mimetype {3595my$fd=shift;3596my$filename=shift;35973598if($filename) {3599my$mime= mimetype_guess($filename);3600$mimeandreturn$mime;3601}36023603# just in case3604return$default_blob_plain_mimetypeunless$fd;36053606if(-T $fd) {3607return'text/plain';3608}elsif(!$filename) {3609return'application/octet-stream';3610}elsif($filename=~m/\.png$/i) {3611return'image/png';3612}elsif($filename=~m/\.gif$/i) {3613return'image/gif';3614}elsif($filename=~m/\.jpe?g$/i) {3615return'image/jpeg';3616}else{3617return'application/octet-stream';3618}3619}36203621sub blob_contenttype {3622my($fd,$file_name,$type) =@_;36233624$type||= blob_mimetype($fd,$file_name);3625if($typeeq'text/plain'&&defined$default_text_plain_charset) {3626$type.="; charset=$default_text_plain_charset";3627}36283629return$type;3630}36313632# guess file syntax for syntax highlighting; return undef if no highlighting3633# the name of syntax can (in the future) depend on syntax highlighter used3634sub guess_file_syntax {3635my($highlight,$mimetype,$file_name) =@_;3636returnundefunless($highlight&&defined$file_name);3637my$basename= basename($file_name,'.in');3638return$highlight_basename{$basename}3639ifexists$highlight_basename{$basename};36403641$basename=~/\.([^.]*)$/;3642my$ext=$1orreturnundef;3643return$highlight_ext{$ext}3644ifexists$highlight_ext{$ext};36453646returnundef;3647}36483649# run highlighter and return FD of its output,3650# or return original FD if no highlighting3651sub run_highlighter {3652my($fd,$highlight,$syntax) =@_;3653return$fdunless($highlight&&defined$syntax);36543655close$fd;3656open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3657 quote_command($highlight_bin).3658" --replace-tabs=8 --fragment --syntax$syntax|"3659or die_error(500,"Couldn't open file or run syntax highlighter");3660return$fd;3661}36623663## ======================================================================3664## functions printing HTML: header, footer, error page36653666sub get_page_title {3667my$title= to_utf8($site_name);36683669return$titleunless(defined$project);3670$title.=" - ". to_utf8($project);36713672return$titleunless(defined$action);3673$title.="/$action";# $action is US-ASCII (7bit ASCII)36743675return$titleunless(defined$file_name);3676$title.=" - ". esc_path($file_name);3677if($actioneq"tree"&&$file_name!~ m|/$|) {3678$title.="/";3679}36803681return$title;3682}36833684sub print_feed_meta {3685if(defined$project) {3686my%href_params= get_feed_info();3687if(!exists$href_params{'-title'}) {3688$href_params{'-title'} ='log';3689}36903691foreachmy$format(qw(RSS Atom)) {3692my$type=lc($format);3693my%link_attr= (3694'-rel'=>'alternate',3695'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3696'-type'=>"application/$type+xml"3697);36983699$href_params{'action'} =$type;3700$link_attr{'-href'} = href(%href_params);3701print"<link ".3702"rel=\"$link_attr{'-rel'}\"".3703"title=\"$link_attr{'-title'}\"".3704"href=\"$link_attr{'-href'}\"".3705"type=\"$link_attr{'-type'}\"".3706"/>\n";37073708$href_params{'extra_options'} ='--no-merges';3709$link_attr{'-href'} = href(%href_params);3710$link_attr{'-title'} .=' (no merges)';3711print"<link ".3712"rel=\"$link_attr{'-rel'}\"".3713"title=\"$link_attr{'-title'}\"".3714"href=\"$link_attr{'-href'}\"".3715"type=\"$link_attr{'-type'}\"".3716"/>\n";3717}37183719}else{3720printf('<link rel="alternate" title="%sprojects list" '.3721'href="%s" type="text/plain; charset=utf-8" />'."\n",3722 esc_attr($site_name), href(project=>undef, action=>"project_index"));3723printf('<link rel="alternate" title="%sprojects feeds" '.3724'href="%s" type="text/x-opml" />'."\n",3725 esc_attr($site_name), href(project=>undef, action=>"opml"));3726}3727}37283729sub git_header_html {3730my$status=shift||"200 OK";3731my$expires=shift;3732my%opts=@_;37333734my$title= get_page_title();3735my$content_type;3736# require explicit support from the UA if we are to send the page as3737# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3738# we have to do this because MSIE sometimes globs '*/*', pretending to3739# support xhtml+xml but choking when it gets what it asked for.3740if(defined$cgi->http('HTTP_ACCEPT') &&3741$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3742$cgi->Accept('application/xhtml+xml') !=0) {3743$content_type='application/xhtml+xml';3744}else{3745$content_type='text/html';3746}3747print$cgi->header(-type=>$content_type, -charset =>'utf-8',3748-status=>$status, -expires =>$expires)3749unless($opts{'-no_http_header'});3750my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3751print<<EOF;3752<?xml version="1.0" encoding="utf-8"?>3753<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3754<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3755<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3756<!-- git core binaries version$git_version-->3757<head>3758<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3759<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3760<meta name="robots" content="index, nofollow"/>3761<title>$title</title>3762EOF3763# the stylesheet, favicon etc urls won't work correctly with path_info3764# unless we set the appropriate base URL3765if($ENV{'PATH_INFO'}) {3766print"<base href=\"".esc_url($base_url)."\"/>\n";3767}3768# print out each stylesheet that exist, providing backwards capability3769# for those people who defined $stylesheet in a config file3770if(defined$stylesheet) {3771print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3772}else{3773foreachmy$stylesheet(@stylesheets) {3774next unless$stylesheet;3775print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3776}3777}3778 print_feed_meta()3779if($statuseq'200 OK');3780if(defined$favicon) {3781printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);3782}37833784print"</head>\n".3785"<body>\n";37863787if(defined$site_header&& -f $site_header) {3788 insert_file($site_header);3789}37903791print"<div class=\"page_header\">\n";3792if(defined$logo) {3793print$cgi->a({-href => esc_url($logo_url),3794-title =>$logo_label},3795$cgi->img({-src => esc_url($logo),3796-width =>72, -height =>27,3797-alt =>"git",3798-class=>"logo"}));3799}3800print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3801if(defined$project) {3802print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3803if(defined$action) {3804my$action_print=$action;3805if(defined$opts{-action_extra}) {3806$action_print=$cgi->a({-href => href(action=>$action)},3807$action);3808}3809print" /$action_print";3810}3811if(defined$opts{-action_extra}) {3812print" /$opts{-action_extra}";3813}3814print"\n";3815}3816print"</div>\n";38173818my$have_search= gitweb_check_feature('search');3819if(defined$project&&$have_search) {3820if(!defined$searchtext) {3821$searchtext="";3822}3823my$search_hash;3824if(defined$hash_base) {3825$search_hash=$hash_base;3826}elsif(defined$hash) {3827$search_hash=$hash;3828}else{3829$search_hash="HEAD";3830}3831my$action=$my_uri;3832my$use_pathinfo= gitweb_check_feature('pathinfo');3833if($use_pathinfo) {3834$action.="/".esc_url($project);3835}3836print$cgi->startform(-method=>"get", -action =>$action) .3837"<div class=\"search\">\n".3838(!$use_pathinfo&&3839$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3840$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3841$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3842$cgi->popup_menu(-name =>'st', -default=>'commit',3843-values=> ['commit','grep','author','committer','pickaxe']) .3844$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3845" search:\n",3846$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3847"<span title=\"Extended regular expression\">".3848$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3849-checked =>$search_use_regexp) .3850"</span>".3851"</div>".3852$cgi->end_form() ."\n";3853}3854}38553856sub git_footer_html {3857my$feed_class='rss_logo';38583859print"<div class=\"page_footer\">\n";3860if(defined$project) {3861my$descr= git_get_project_description($project);3862if(defined$descr) {3863print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3864}38653866my%href_params= get_feed_info();3867if(!%href_params) {3868$feed_class.=' generic';3869}3870$href_params{'-title'} ||='log';38713872foreachmy$format(qw(RSS Atom)) {3873$href_params{'action'} =lc($format);3874print$cgi->a({-href => href(%href_params),3875-title =>"$href_params{'-title'}$formatfeed",3876-class=>$feed_class},$format)."\n";3877}38783879}else{3880print$cgi->a({-href => href(project=>undef, action=>"opml"),3881-class=>$feed_class},"OPML") ." ";3882print$cgi->a({-href => href(project=>undef, action=>"project_index"),3883-class=>$feed_class},"TXT") ."\n";3884}3885print"</div>\n";# class="page_footer"38863887if(defined$t0&& gitweb_check_feature('timed')) {3888print"<div id=\"generating_info\">\n";3889print'This page took '.3890'<span id="generating_time" class="time_span">'.3891 tv_interval($t0, [ gettimeofday() ]).3892' seconds </span>'.3893' and '.3894'<span id="generating_cmd">'.3895$number_of_git_cmds.3896'</span> git commands '.3897" to generate.\n";3898print"</div>\n";# class="page_footer"3899}39003901if(defined$site_footer&& -f $site_footer) {3902 insert_file($site_footer);3903}39043905print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;3906if(defined$action&&3907$actioneq'blame_incremental') {3908print qq!<script type="text/javascript">\n!.3909 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.3910 qq!"!. href() .qq!");\n!.3911 qq!</script>\n!;3912}else{3913my($jstimezone,$tz_cookie,$datetime_class) =3914 gitweb_get_feature('javascript-timezone');39153916print qq!<script type="text/javascript">\n!.3917 qq!window.onload = function () {\n!;3918if(gitweb_check_feature('javascript-actions')) {3919print qq! fixLinks();\n!;3920}3921if($jstimezone&&$tz_cookie&&$datetime_class) {3922print qq! var tz_cookie = { name:'$tz_cookie', expires:14, path:'/'};\n!.# in days3923 qq! onloadTZSetup('$jstimezone', tz_cookie,'$datetime_class');\n!;3924}3925print qq!};\n!.3926 qq!</script>\n!;3927}39283929print"</body>\n".3930"</html>";3931}39323933# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])3934# Example: die_error(404, 'Hash not found')3935# By convention, use the following status codes (as defined in RFC 2616):3936# 400: Invalid or missing CGI parameters, or3937# requested object exists but has wrong type.3938# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3939# this server or project.3940# 404: Requested object/revision/project doesn't exist.3941# 500: The server isn't configured properly, or3942# an internal error occurred (e.g. failed assertions caused by bugs), or3943# an unknown error occurred (e.g. the git binary died unexpectedly).3944# 503: The server is currently unavailable (because it is overloaded,3945# or down for maintenance). Generally, this is a temporary state.3946sub die_error {3947my$status=shift||500;3948my$error= esc_html(shift) ||"Internal Server Error";3949my$extra=shift;3950my%opts=@_;39513952my%http_responses= (3953400=>'400 Bad Request',3954403=>'403 Forbidden',3955404=>'404 Not Found',3956500=>'500 Internal Server Error',3957503=>'503 Service Unavailable',3958);3959 git_header_html($http_responses{$status},undef,%opts);3960print<<EOF;3961<div class="page_body">3962<br /><br />3963$status-$error3964<br />3965EOF3966if(defined$extra) {3967print"<hr />\n".3968"$extra\n";3969}3970print"</div>\n";39713972 git_footer_html();3973goto DONE_GITWEB3974unless($opts{'-error_handler'});3975}39763977## ----------------------------------------------------------------------3978## functions printing or outputting HTML: navigation39793980sub git_print_page_nav {3981my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;3982$extra=''if!defined$extra;# pager or formats39833984my@navs=qw(summary shortlog log commit commitdiff tree);3985if($suppress) {3986@navs=grep{$_ne$suppress}@navs;3987}39883989my%arg=map{$_=> {action=>$_} }@navs;3990if(defined$head) {3991for(qw(commit commitdiff)) {3992$arg{$_}{'hash'} =$head;3993}3994if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {3995for(qw(shortlog log)) {3996$arg{$_}{'hash'} =$head;3997}3998}3999}40004001$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;4002$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;40034004my@actions= gitweb_get_feature('actions');4005my%repl= (4006'%'=>'%',4007'n'=>$project,# project name4008'f'=>$git_dir,# project path within filesystem4009'h'=>$treehead||'',# current hash ('h' parameter)4010'b'=>$treebase||'',# hash base ('hb' parameter)4011);4012while(@actions) {4013my($label,$link,$pos) =splice(@actions,0,3);4014# insert4015@navs=map{$_eq$pos? ($_,$label) :$_}@navs;4016# munch munch4017$link=~s/%([%nfhb])/$repl{$1}/g;4018$arg{$label}{'_href'} =$link;4019}40204021print"<div class=\"page_nav\">\n".4022(join" | ",4023map{$_eq$current?4024$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4025}@navs);4026print"<br/>\n$extra<br/>\n".4027"</div>\n";4028}40294030# returns a submenu for the nagivation of the refs views (tags, heads,4031# remotes) with the current view disabled and the remotes view only4032# available if the feature is enabled4033sub format_ref_views {4034my($current) =@_;4035my@ref_views=qw{tags heads};4036push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4037returnjoin" | ",map{4038$_eq$current?$_:4039$cgi->a({-href => href(action=>$_)},$_)4040}@ref_views4041}40424043sub format_paging_nav {4044my($action,$page,$has_next_link) =@_;4045my$paging_nav;404640474048if($page>0) {4049$paging_nav.=4050$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4051" ⋅ ".4052$cgi->a({-href => href(-replay=>1, page=>$page-1),4053-accesskey =>"p", -title =>"Alt-p"},"prev");4054}else{4055$paging_nav.="first ⋅ prev";4056}40574058if($has_next_link) {4059$paging_nav.=" ⋅ ".4060$cgi->a({-href => href(-replay=>1, page=>$page+1),4061-accesskey =>"n", -title =>"Alt-n"},"next");4062}else{4063$paging_nav.=" ⋅ next";4064}40654066return$paging_nav;4067}40684069## ......................................................................4070## functions printing or outputting HTML: div40714072sub git_print_header_div {4073my($action,$title,$hash,$hash_base) =@_;4074my%args= ();40754076$args{'action'} =$action;4077$args{'hash'} =$hashif$hash;4078$args{'hash_base'} =$hash_baseif$hash_base;40794080print"<div class=\"header\">\n".4081$cgi->a({-href => href(%args), -class=>"title"},4082$title?$title:$action) .4083"\n</div>\n";4084}40854086sub format_repo_url {4087my($name,$url) =@_;4088return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4089}40904091# Group output by placing it in a DIV element and adding a header.4092# Options for start_div() can be provided by passing a hash reference as the4093# first parameter to the function.4094# Options to git_print_header_div() can be provided by passing an array4095# reference. This must follow the options to start_div if they are present.4096# The content can be a scalar, which is output as-is, a scalar reference, which4097# is output after html escaping, an IO handle passed either as *handle or4098# *handle{IO}, or a function reference. In the latter case all following4099# parameters will be taken as argument to the content function call.4100sub git_print_section {4101my($div_args,$header_args,$content);4102my$arg=shift;4103if(ref($arg)eq'HASH') {4104$div_args=$arg;4105$arg=shift;4106}4107if(ref($arg)eq'ARRAY') {4108$header_args=$arg;4109$arg=shift;4110}4111$content=$arg;41124113print$cgi->start_div($div_args);4114 git_print_header_div(@$header_args);41154116if(ref($content)eq'CODE') {4117$content->(@_);4118}elsif(ref($content)eq'SCALAR') {4119print esc_html($$content);4120}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4121print<$content>;4122}elsif(!ref($content) &&defined($content)) {4123print$content;4124}41254126print$cgi->end_div;4127}41284129sub format_timestamp_html {4130my$date=shift;4131my$strtime=$date->{'rfc2822'};41324133my(undef,undef,$datetime_class) =4134 gitweb_get_feature('javascript-timezone');4135if($datetime_class) {4136$strtime= qq!<span class="$datetime_class">$strtime</span>!;4137}41384139my$localtime_format='(%02d:%02d%s)';4140if($date->{'hour_local'} <6) {4141$localtime_format='(<span class="atnight">%02d:%02d</span>%s)';4142}4143$strtime.=' '.4144sprintf($localtime_format,4145$date->{'hour_local'},$date->{'minute_local'},$date->{'tz_local'});41464147return$strtime;4148}41494150# Outputs the author name and date in long form4151sub git_print_authorship {4152my$co=shift;4153my%opts=@_;4154my$tag=$opts{-tag} ||'div';4155my$author=$co->{'author_name'};41564157my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4158print"<$tagclass=\"author_date\">".4159 format_search_author($author,"author", esc_html($author)) .4160" [".format_timestamp_html(\%ad)."]".4161 git_get_avatar($co->{'author_email'}, -pad_before =>1) .4162"</$tag>\n";4163}41644165# Outputs table rows containing the full author or committer information,4166# in the format expected for 'commit' view (& similar).4167# Parameters are a commit hash reference, followed by the list of people4168# to output information for. If the list is empty it defaults to both4169# author and committer.4170sub git_print_authorship_rows {4171my$co=shift;4172# too bad we can't use @people = @_ || ('author', 'committer')4173my@people=@_;4174@people= ('author','committer')unless@people;4175foreachmy$who(@people) {4176my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4177print"<tr><td>$who</td><td>".4178 format_search_author($co->{"${who}_name"},$who,4179 esc_html($co->{"${who}_name"})) ." ".4180 format_search_author($co->{"${who}_email"},$who,4181 esc_html("<".$co->{"${who}_email"} .">")) .4182"</td><td rowspan=\"2\">".4183 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4184"</td></tr>\n".4185"<tr>".4186"<td></td><td>".4187 format_timestamp_html(\%wd) .4188"</td>".4189"</tr>\n";4190}4191}41924193sub git_print_page_path {4194my$name=shift;4195my$type=shift;4196my$hb=shift;419741984199print"<div class=\"page_path\">";4200print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4201-title =>'tree root'}, to_utf8("[$project]"));4202print" / ";4203if(defined$name) {4204my@dirname=split'/',$name;4205my$basename=pop@dirname;4206my$fullname='';42074208foreachmy$dir(@dirname) {4209$fullname.= ($fullname?'/':'') .$dir;4210print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4211 hash_base=>$hb),4212-title =>$fullname}, esc_path($dir));4213print" / ";4214}4215if(defined$type&&$typeeq'blob') {4216print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4217 hash_base=>$hb),4218-title =>$name}, esc_path($basename));4219}elsif(defined$type&&$typeeq'tree') {4220print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4221 hash_base=>$hb),4222-title =>$name}, esc_path($basename));4223print" / ";4224}else{4225print esc_path($basename);4226}4227}4228print"<br/></div>\n";4229}42304231sub git_print_log {4232my$log=shift;4233my%opts=@_;42344235if($opts{'-remove_title'}) {4236# remove title, i.e. first line of log4237shift@$log;4238}4239# remove leading empty lines4240while(defined$log->[0] &&$log->[0]eq"") {4241shift@$log;4242}42434244# print log4245my$signoff=0;4246my$empty=0;4247foreachmy$line(@$log) {4248if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {4249$signoff=1;4250$empty=0;4251if(!$opts{'-remove_signoff'}) {4252print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4253next;4254}else{4255# remove signoff lines4256next;4257}4258}else{4259$signoff=0;4260}42614262# print only one empty line4263# do not print empty line after signoff4264if($lineeq"") {4265next if($empty||$signoff);4266$empty=1;4267}else{4268$empty=0;4269}42704271print format_log_line_html($line) ."<br/>\n";4272}42734274if($opts{'-final_empty_line'}) {4275# end with single empty line4276print"<br/>\n"unless$empty;4277}4278}42794280# return link target (what link points to)4281sub git_get_link_target {4282my$hash=shift;4283my$link_target;42844285# read link4286open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4287orreturn;4288{4289local$/=undef;4290$link_target= <$fd>;4291}4292close$fd4293orreturn;42944295return$link_target;4296}42974298# given link target, and the directory (basedir) the link is in,4299# return target of link relative to top directory (top tree);4300# return undef if it is not possible (including absolute links).4301sub normalize_link_target {4302my($link_target,$basedir) =@_;43034304# absolute symlinks (beginning with '/') cannot be normalized4305return if(substr($link_target,0,1)eq'/');43064307# normalize link target to path from top (root) tree (dir)4308my$path;4309if($basedir) {4310$path=$basedir.'/'.$link_target;4311}else{4312# we are in top (root) tree (dir)4313$path=$link_target;4314}43154316# remove //, /./, and /../4317my@path_parts;4318foreachmy$part(split('/',$path)) {4319# discard '.' and ''4320next if(!$part||$parteq'.');4321# handle '..'4322if($parteq'..') {4323if(@path_parts) {4324pop@path_parts;4325}else{4326# link leads outside repository (outside top dir)4327return;4328}4329}else{4330push@path_parts,$part;4331}4332}4333$path=join('/',@path_parts);43344335return$path;4336}43374338# print tree entry (row of git_tree), but without encompassing <tr> element4339sub git_print_tree_entry {4340my($t,$basedir,$hash_base,$have_blame) =@_;43414342my%base_key= ();4343$base_key{'hash_base'} =$hash_baseifdefined$hash_base;43444345# The format of a table row is: mode list link. Where mode is4346# the mode of the entry, list is the name of the entry, an href,4347# and link is the action links of the entry.43484349print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4350if(exists$t->{'size'}) {4351print"<td class=\"size\">$t->{'size'}</td>\n";4352}4353if($t->{'type'}eq"blob") {4354print"<td class=\"list\">".4355$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4356 file_name=>"$basedir$t->{'name'}",%base_key),4357-class=>"list"}, esc_path($t->{'name'}));4358if(S_ISLNK(oct$t->{'mode'})) {4359my$link_target= git_get_link_target($t->{'hash'});4360if($link_target) {4361my$norm_target= normalize_link_target($link_target,$basedir);4362if(defined$norm_target) {4363print" -> ".4364$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4365 file_name=>$norm_target),4366-title =>$norm_target}, esc_path($link_target));4367}else{4368print" -> ". esc_path($link_target);4369}4370}4371}4372print"</td>\n";4373print"<td class=\"link\">";4374print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4375 file_name=>"$basedir$t->{'name'}",%base_key)},4376"blob");4377if($have_blame) {4378print" | ".4379$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4380 file_name=>"$basedir$t->{'name'}",%base_key)},4381"blame");4382}4383if(defined$hash_base) {4384print" | ".4385$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4386 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4387"history");4388}4389print" | ".4390$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4391 file_name=>"$basedir$t->{'name'}")},4392"raw");4393print"</td>\n";43944395}elsif($t->{'type'}eq"tree") {4396print"<td class=\"list\">";4397print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4398 file_name=>"$basedir$t->{'name'}",4399%base_key)},4400 esc_path($t->{'name'}));4401print"</td>\n";4402print"<td class=\"link\">";4403print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4404 file_name=>"$basedir$t->{'name'}",4405%base_key)},4406"tree");4407if(defined$hash_base) {4408print" | ".4409$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4410 file_name=>"$basedir$t->{'name'}")},4411"history");4412}4413print"</td>\n";4414}else{4415# unknown object: we can only present history for it4416# (this includes 'commit' object, i.e. submodule support)4417print"<td class=\"list\">".4418 esc_path($t->{'name'}) .4419"</td>\n";4420print"<td class=\"link\">";4421if(defined$hash_base) {4422print$cgi->a({-href => href(action=>"history",4423 hash_base=>$hash_base,4424 file_name=>"$basedir$t->{'name'}")},4425"history");4426}4427print"</td>\n";4428}4429}44304431## ......................................................................4432## functions printing large fragments of HTML44334434# get pre-image filenames for merge (combined) diff4435sub fill_from_file_info {4436my($diff,@parents) =@_;44374438$diff->{'from_file'} = [ ];4439$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4440for(my$i=0;$i<$diff->{'nparents'};$i++) {4441if($diff->{'status'}[$i]eq'R'||4442$diff->{'status'}[$i]eq'C') {4443$diff->{'from_file'}[$i] =4444 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4445}4446}44474448return$diff;4449}44504451# is current raw difftree line of file deletion4452sub is_deleted {4453my$diffinfo=shift;44544455return$diffinfo->{'to_id'}eq('0' x 40);4456}44574458# does patch correspond to [previous] difftree raw line4459# $diffinfo - hashref of parsed raw diff format4460# $patchinfo - hashref of parsed patch diff format4461# (the same keys as in $diffinfo)4462sub is_patch_split {4463my($diffinfo,$patchinfo) =@_;44644465returndefined$diffinfo&&defined$patchinfo4466&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4467}446844694470sub git_difftree_body {4471my($difftree,$hash,@parents) =@_;4472my($parent) =$parents[0];4473my$have_blame= gitweb_check_feature('blame');4474print"<div class=\"list_head\">\n";4475if($#{$difftree} >10) {4476print(($#{$difftree} +1) ." files changed:\n");4477}4478print"</div>\n";44794480print"<table class=\"".4481(@parents>1?"combined ":"") .4482"diff_tree\">\n";44834484# header only for combined diff in 'commitdiff' view4485my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4486if($has_header) {4487# table header4488print"<thead><tr>\n".4489"<th></th><th></th>\n";# filename, patchN link4490for(my$i=0;$i<@parents;$i++) {4491my$par=$parents[$i];4492print"<th>".4493$cgi->a({-href => href(action=>"commitdiff",4494 hash=>$hash, hash_parent=>$par),4495-title =>'commitdiff to parent number '.4496($i+1) .': '.substr($par,0,7)},4497$i+1) .4498" </th>\n";4499}4500print"</tr></thead>\n<tbody>\n";4501}45024503my$alternate=1;4504my$patchno=0;4505foreachmy$line(@{$difftree}) {4506my$diff= parsed_difftree_line($line);45074508if($alternate) {4509print"<tr class=\"dark\">\n";4510}else{4511print"<tr class=\"light\">\n";4512}4513$alternate^=1;45144515if(exists$diff->{'nparents'}) {# combined diff45164517 fill_from_file_info($diff,@parents)4518unlessexists$diff->{'from_file'};45194520if(!is_deleted($diff)) {4521# file exists in the result (child) commit4522print"<td>".4523$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4524 file_name=>$diff->{'to_file'},4525 hash_base=>$hash),4526-class=>"list"}, esc_path($diff->{'to_file'})) .4527"</td>\n";4528}else{4529print"<td>".4530 esc_path($diff->{'to_file'}) .4531"</td>\n";4532}45334534if($actioneq'commitdiff') {4535# link to patch4536$patchno++;4537print"<td class=\"link\">".4538$cgi->a({-href => href(-anchor=>"patch$patchno")},4539"patch") .4540" | ".4541"</td>\n";4542}45434544my$has_history=0;4545my$not_deleted=0;4546for(my$i=0;$i<$diff->{'nparents'};$i++) {4547my$hash_parent=$parents[$i];4548my$from_hash=$diff->{'from_id'}[$i];4549my$from_path=$diff->{'from_file'}[$i];4550my$status=$diff->{'status'}[$i];45514552$has_history||= ($statusne'A');4553$not_deleted||= ($statusne'D');45544555if($statuseq'A') {4556print"<td class=\"link\"align=\"right\"> | </td>\n";4557}elsif($statuseq'D') {4558print"<td class=\"link\">".4559$cgi->a({-href => href(action=>"blob",4560 hash_base=>$hash,4561 hash=>$from_hash,4562 file_name=>$from_path)},4563"blob". ($i+1)) .4564" | </td>\n";4565}else{4566if($diff->{'to_id'}eq$from_hash) {4567print"<td class=\"link nochange\">";4568}else{4569print"<td class=\"link\">";4570}4571print$cgi->a({-href => href(action=>"blobdiff",4572 hash=>$diff->{'to_id'},4573 hash_parent=>$from_hash,4574 hash_base=>$hash,4575 hash_parent_base=>$hash_parent,4576 file_name=>$diff->{'to_file'},4577 file_parent=>$from_path)},4578"diff". ($i+1)) .4579" | </td>\n";4580}4581}45824583print"<td class=\"link\">";4584if($not_deleted) {4585print$cgi->a({-href => href(action=>"blob",4586 hash=>$diff->{'to_id'},4587 file_name=>$diff->{'to_file'},4588 hash_base=>$hash)},4589"blob");4590print" | "if($has_history);4591}4592if($has_history) {4593print$cgi->a({-href => href(action=>"history",4594 file_name=>$diff->{'to_file'},4595 hash_base=>$hash)},4596"history");4597}4598print"</td>\n";45994600print"</tr>\n";4601next;# instead of 'else' clause, to avoid extra indent4602}4603# else ordinary diff46044605my($to_mode_oct,$to_mode_str,$to_file_type);4606my($from_mode_oct,$from_mode_str,$from_file_type);4607if($diff->{'to_mode'}ne('0' x 6)) {4608$to_mode_oct=oct$diff->{'to_mode'};4609if(S_ISREG($to_mode_oct)) {# only for regular file4610$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4611}4612$to_file_type= file_type($diff->{'to_mode'});4613}4614if($diff->{'from_mode'}ne('0' x 6)) {4615$from_mode_oct=oct$diff->{'from_mode'};4616if(S_ISREG($from_mode_oct)) {# only for regular file4617$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4618}4619$from_file_type= file_type($diff->{'from_mode'});4620}46214622if($diff->{'status'}eq"A") {# created4623my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4624$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4625$mode_chng.="]</span>";4626print"<td>";4627print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4628 hash_base=>$hash, file_name=>$diff->{'file'}),4629-class=>"list"}, esc_path($diff->{'file'}));4630print"</td>\n";4631print"<td>$mode_chng</td>\n";4632print"<td class=\"link\">";4633if($actioneq'commitdiff') {4634# link to patch4635$patchno++;4636print$cgi->a({-href => href(-anchor=>"patch$patchno")},4637"patch") .4638" | ";4639}4640print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4641 hash_base=>$hash, file_name=>$diff->{'file'})},4642"blob");4643print"</td>\n";46444645}elsif($diff->{'status'}eq"D") {# deleted4646my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4647print"<td>";4648print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4649 hash_base=>$parent, file_name=>$diff->{'file'}),4650-class=>"list"}, esc_path($diff->{'file'}));4651print"</td>\n";4652print"<td>$mode_chng</td>\n";4653print"<td class=\"link\">";4654if($actioneq'commitdiff') {4655# link to patch4656$patchno++;4657print$cgi->a({-href => href(-anchor=>"patch$patchno")},4658"patch") .4659" | ";4660}4661print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4662 hash_base=>$parent, file_name=>$diff->{'file'})},4663"blob") ." | ";4664if($have_blame) {4665print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4666 file_name=>$diff->{'file'})},4667"blame") ." | ";4668}4669print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4670 file_name=>$diff->{'file'})},4671"history");4672print"</td>\n";46734674}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4675my$mode_chnge="";4676if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4677$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4678if($from_file_typene$to_file_type) {4679$mode_chnge.=" from$from_file_typeto$to_file_type";4680}4681if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4682if($from_mode_str&&$to_mode_str) {4683$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4684}elsif($to_mode_str) {4685$mode_chnge.=" mode:$to_mode_str";4686}4687}4688$mode_chnge.="]</span>\n";4689}4690print"<td>";4691print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4692 hash_base=>$hash, file_name=>$diff->{'file'}),4693-class=>"list"}, esc_path($diff->{'file'}));4694print"</td>\n";4695print"<td>$mode_chnge</td>\n";4696print"<td class=\"link\">";4697if($actioneq'commitdiff') {4698# link to patch4699$patchno++;4700print$cgi->a({-href => href(-anchor=>"patch$patchno")},4701"patch") .4702" | ";4703}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4704# "commit" view and modified file (not onlu mode changed)4705print$cgi->a({-href => href(action=>"blobdiff",4706 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4707 hash_base=>$hash, hash_parent_base=>$parent,4708 file_name=>$diff->{'file'})},4709"diff") .4710" | ";4711}4712print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4713 hash_base=>$hash, file_name=>$diff->{'file'})},4714"blob") ." | ";4715if($have_blame) {4716print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4717 file_name=>$diff->{'file'})},4718"blame") ." | ";4719}4720print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4721 file_name=>$diff->{'file'})},4722"history");4723print"</td>\n";47244725}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4726my%status_name= ('R'=>'moved','C'=>'copied');4727my$nstatus=$status_name{$diff->{'status'}};4728my$mode_chng="";4729if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4730# mode also for directories, so we cannot use $to_mode_str4731$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4732}4733print"<td>".4734$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4735 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4736-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4737"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4738$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4739 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4740-class=>"list"}, esc_path($diff->{'from_file'})) .4741" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4742"<td class=\"link\">";4743if($actioneq'commitdiff') {4744# link to patch4745$patchno++;4746print$cgi->a({-href => href(-anchor=>"patch$patchno")},4747"patch") .4748" | ";4749}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4750# "commit" view and modified file (not only pure rename or copy)4751print$cgi->a({-href => href(action=>"blobdiff",4752 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4753 hash_base=>$hash, hash_parent_base=>$parent,4754 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4755"diff") .4756" | ";4757}4758print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4759 hash_base=>$parent, file_name=>$diff->{'to_file'})},4760"blob") ." | ";4761if($have_blame) {4762print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4763 file_name=>$diff->{'to_file'})},4764"blame") ." | ";4765}4766print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4767 file_name=>$diff->{'to_file'})},4768"history");4769print"</td>\n";47704771}# we should not encounter Unmerged (U) or Unknown (X) status4772print"</tr>\n";4773}4774print"</tbody>"if$has_header;4775print"</table>\n";4776}47774778sub git_patchset_body {4779my($fd,$difftree,$hash,@hash_parents) =@_;4780my($hash_parent) =$hash_parents[0];47814782my$is_combined= (@hash_parents>1);4783my$patch_idx=0;4784my$patch_number=0;4785my$patch_line;4786my$diffinfo;4787my$to_name;4788my(%from,%to);47894790print"<div class=\"patchset\">\n";47914792# skip to first patch4793while($patch_line= <$fd>) {4794chomp$patch_line;47954796last if($patch_line=~m/^diff /);4797}47984799 PATCH:4800while($patch_line) {48014802# parse "git diff" header line4803if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4804# $1 is from_name, which we do not use4805$to_name= unquote($2);4806$to_name=~s!^b/!!;4807}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4808# $1 is 'cc' or 'combined', which we do not use4809$to_name= unquote($2);4810}else{4811$to_name=undef;4812}48134814# check if current patch belong to current raw line4815# and parse raw git-diff line if needed4816if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4817# this is continuation of a split patch4818print"<div class=\"patch cont\">\n";4819}else{4820# advance raw git-diff output if needed4821$patch_idx++ifdefined$diffinfo;48224823# read and prepare patch information4824$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);48254826# compact combined diff output can have some patches skipped4827# find which patch (using pathname of result) we are at now;4828if($is_combined) {4829while($to_namene$diffinfo->{'to_file'}) {4830print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4831 format_diff_cc_simplified($diffinfo,@hash_parents) .4832"</div>\n";# class="patch"48334834$patch_idx++;4835$patch_number++;48364837last if$patch_idx>$#$difftree;4838$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4839}4840}48414842# modifies %from, %to hashes4843 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);48444845# this is first patch for raw difftree line with $patch_idx index4846# we index @$difftree array from 0, but number patches from 14847print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4848}48494850# git diff header4851#assert($patch_line =~ m/^diff /) if DEBUG;4852#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4853$patch_number++;4854# print "git diff" header4855print format_git_diff_header_line($patch_line,$diffinfo,4856 \%from, \%to);48574858# print extended diff header4859print"<div class=\"diff extended_header\">\n";4860 EXTENDED_HEADER:4861while($patch_line= <$fd>) {4862chomp$patch_line;48634864last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);48654866print format_extended_diff_header_line($patch_line,$diffinfo,4867 \%from, \%to);4868}4869print"</div>\n";# class="diff extended_header"48704871# from-file/to-file diff header4872if(!$patch_line) {4873print"</div>\n";# class="patch"4874last PATCH;4875}4876next PATCH if($patch_line=~m/^diff /);4877#assert($patch_line =~ m/^---/) if DEBUG;48784879my$last_patch_line=$patch_line;4880$patch_line= <$fd>;4881chomp$patch_line;4882#assert($patch_line =~ m/^\+\+\+/) if DEBUG;48834884print format_diff_from_to_header($last_patch_line,$patch_line,4885$diffinfo, \%from, \%to,4886@hash_parents);48874888# the patch itself4889 LINE:4890while($patch_line= <$fd>) {4891chomp$patch_line;48924893next PATCH if($patch_line=~m/^diff /);48944895print format_diff_line($patch_line, \%from, \%to);4896}48974898}continue{4899print"</div>\n";# class="patch"4900}49014902# for compact combined (--cc) format, with chunk and patch simplification4903# the patchset might be empty, but there might be unprocessed raw lines4904for(++$patch_idxif$patch_number>0;4905$patch_idx<@$difftree;4906++$patch_idx) {4907# read and prepare patch information4908$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);49094910# generate anchor for "patch" links in difftree / whatchanged part4911print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4912 format_diff_cc_simplified($diffinfo,@hash_parents) .4913"</div>\n";# class="patch"49144915$patch_number++;4916}49174918if($patch_number==0) {4919if(@hash_parents>1) {4920print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4921}else{4922print"<div class=\"diff nodifferences\">No differences found</div>\n";4923}4924}49254926print"</div>\n";# class="patchset"4927}49284929# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49304931# fills project list info (age, description, owner, category, forks)4932# for each project in the list, removing invalid projects from4933# returned list4934# NOTE: modifies $projlist, but does not remove entries from it4935sub fill_project_list_info {4936my$projlist=shift;4937my@projects;49384939my$show_ctags= gitweb_check_feature('ctags');4940 PROJECT:4941foreachmy$pr(@$projlist) {4942my(@activity) = git_get_last_activity($pr->{'path'});4943unless(@activity) {4944next PROJECT;4945}4946($pr->{'age'},$pr->{'age_string'}) =@activity;4947if(!defined$pr->{'descr'}) {4948my$descr= git_get_project_description($pr->{'path'}) ||"";4949$descr= to_utf8($descr);4950$pr->{'descr_long'} =$descr;4951$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);4952}4953if(!defined$pr->{'owner'}) {4954$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";4955}4956if($show_ctags) {4957$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});4958}4959if($projects_list_group_categories&& !defined$pr->{'category'}) {4960my$cat= git_get_project_category($pr->{'path'}) ||4961$project_list_default_category;4962$pr->{'category'} = to_utf8($cat);4963}49644965push@projects,$pr;4966}49674968return@projects;4969}49704971sub sort_projects_list {4972my($projlist,$order) =@_;4973my@projects;49744975my%order_info= (4976 project => { key =>'path', type =>'str'},4977 descr => { key =>'descr_long', type =>'str'},4978 owner => { key =>'owner', type =>'str'},4979 age => { key =>'age', type =>'num'}4980);4981my$oi=$order_info{$order};4982return@$projlistunlessdefined$oi;4983if($oi->{'type'}eq'str') {4984@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@$projlist;4985}else{4986@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@$projlist;4987}49884989return@projects;4990}49914992# returns a hash of categories, containing the list of project4993# belonging to each category4994sub build_projlist_by_category {4995my($projlist,$from,$to) =@_;4996my%categories;49974998$from=0unlessdefined$from;4999$to=$#$projlistif(!defined$to||$#$projlist<$to);50005001for(my$i=$from;$i<=$to;$i++) {5002my$pr=$projlist->[$i];5003push@{$categories{$pr->{'category'} }},$pr;5004}50055006returnwantarray?%categories: \%categories;5007}50085009# print 'sort by' <th> element, generating 'sort by $name' replay link5010# if that order is not selected5011sub print_sort_th {5012print format_sort_th(@_);5013}50145015sub format_sort_th {5016my($name,$order,$header) =@_;5017my$sort_th="";5018$header||=ucfirst($name);50195020if($ordereq$name) {5021$sort_th.="<th>$header</th>\n";5022}else{5023$sort_th.="<th>".5024$cgi->a({-href => href(-replay=>1, order=>$name),5025-class=>"header"},$header) .5026"</th>\n";5027}50285029return$sort_th;5030}50315032sub git_project_list_rows {5033my($projlist,$from,$to,$check_forks) =@_;50345035$from=0unlessdefined$from;5036$to=$#$projlistif(!defined$to||$#$projlist<$to);50375038my$alternate=1;5039for(my$i=$from;$i<=$to;$i++) {5040my$pr=$projlist->[$i];50415042if($alternate) {5043print"<tr class=\"dark\">\n";5044}else{5045print"<tr class=\"light\">\n";5046}5047$alternate^=1;50485049if($check_forks) {5050print"<td>";5051if($pr->{'forks'}) {5052my$nforks=scalar@{$pr->{'forks'}};5053if($nforks>0) {5054print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5055-title =>"$nforksforks"},"+");5056}else{5057print$cgi->span({-title =>"$nforksforks"},"+");5058}5059}5060print"</td>\n";5061}5062print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5063-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".5064"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5065-class=>"list", -title =>$pr->{'descr_long'}},5066 esc_html($pr->{'descr'})) ."</td>\n".5067"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5068print"<td class=\"". age_class($pr->{'age'}) ."\">".5069(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".5070"<td class=\"link\">".5071$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5072$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5073$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5074$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5075($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5076"</td>\n".5077"</tr>\n";5078}5079}50805081sub git_project_list_body {5082# actually uses global variable $project5083my($projlist,$order,$from,$to,$extra,$no_header) =@_;5084my@projects=@$projlist;50855086my$check_forks= gitweb_check_feature('forks');5087my$show_ctags= gitweb_check_feature('ctags');5088my$tagfilter=$show_ctags?$cgi->param('by_tag') :undef;5089$check_forks=undef5090if($tagfilter||$searchtext);50915092# filtering out forks before filling info allows to do less work5093@projects= filter_forks_from_projects_list(\@projects)5094if($check_forks);5095@projects= fill_project_list_info(\@projects);5096# searching projects require filling to be run before it5097@projects= search_projects_list(\@projects,5098'searchtext'=>$searchtext,5099'tagfilter'=>$tagfilter)5100if($tagfilter||$searchtext);51015102$order||=$default_projects_order;5103$from=0unlessdefined$from;5104$to=$#projectsif(!defined$to||$#projects<$to);51055106# short circuit5107if($from>$to) {5108print"<center>\n".5109"<b>No such projects found</b><br />\n".5110"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5111"</center>\n<br />\n";5112return;5113}51145115@projects= sort_projects_list(\@projects,$order);51165117if($show_ctags) {5118my$ctags= git_gather_all_ctags(\@projects);5119my$cloud= git_populate_project_tagcloud($ctags);5120print git_show_project_tagcloud($cloud,64);5121}51225123print"<table class=\"project_list\">\n";5124unless($no_header) {5125print"<tr>\n";5126if($check_forks) {5127print"<th></th>\n";5128}5129 print_sort_th('project',$order,'Project');5130 print_sort_th('descr',$order,'Description');5131 print_sort_th('owner',$order,'Owner');5132 print_sort_th('age',$order,'Last Change');5133print"<th></th>\n".# for links5134"</tr>\n";5135}51365137if($projects_list_group_categories) {5138# only display categories with projects in the $from-$to window5139@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5140my%categories= build_projlist_by_category(\@projects,$from,$to);5141foreachmy$cat(sort keys%categories) {5142unless($cateq"") {5143print"<tr>\n";5144if($check_forks) {5145print"<td></td>\n";5146}5147print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5148print"</tr>\n";5149}51505151 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5152}5153}else{5154 git_project_list_rows(\@projects,$from,$to,$check_forks);5155}51565157if(defined$extra) {5158print"<tr>\n";5159if($check_forks) {5160print"<td></td>\n";5161}5162print"<td colspan=\"5\">$extra</td>\n".5163"</tr>\n";5164}5165print"</table>\n";5166}51675168sub git_log_body {5169# uses global variable $project5170my($commitlist,$from,$to,$refs,$extra) =@_;51715172$from=0unlessdefined$from;5173$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);51745175for(my$i=0;$i<=$to;$i++) {5176my%co= %{$commitlist->[$i]};5177next if!%co;5178my$commit=$co{'id'};5179my$ref= format_ref_marker($refs,$commit);5180 git_print_header_div('commit',5181"<span class=\"age\">$co{'age_string'}</span>".5182 esc_html($co{'title'}) .$ref,5183$commit);5184print"<div class=\"title_text\">\n".5185"<div class=\"log_link\">\n".5186$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5187" | ".5188$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5189" | ".5190$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5191"<br/>\n".5192"</div>\n";5193 git_print_authorship(\%co, -tag =>'span');5194print"<br/>\n</div>\n";51955196print"<div class=\"log_body\">\n";5197 git_print_log($co{'comment'}, -final_empty_line=>1);5198print"</div>\n";5199}5200if($extra) {5201print"<div class=\"page_nav\">\n";5202print"$extra\n";5203print"</div>\n";5204}5205}52065207sub git_shortlog_body {5208# uses global variable $project5209my($commitlist,$from,$to,$refs,$extra) =@_;52105211$from=0unlessdefined$from;5212$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);52135214print"<table class=\"shortlog\">\n";5215my$alternate=1;5216for(my$i=$from;$i<=$to;$i++) {5217my%co= %{$commitlist->[$i]};5218my$commit=$co{'id'};5219my$ref= format_ref_marker($refs,$commit);5220if($alternate) {5221print"<tr class=\"dark\">\n";5222}else{5223print"<tr class=\"light\">\n";5224}5225$alternate^=1;5226# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5227print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5228 format_author_html('td', \%co,10) ."<td>";5229print format_subject_html($co{'title'},$co{'title_short'},5230 href(action=>"commit", hash=>$commit),$ref);5231print"</td>\n".5232"<td class=\"link\">".5233$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5234$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5235$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5236my$snapshot_links= format_snapshot_links($commit);5237if(defined$snapshot_links) {5238print" | ".$snapshot_links;5239}5240print"</td>\n".5241"</tr>\n";5242}5243if(defined$extra) {5244print"<tr>\n".5245"<td colspan=\"4\">$extra</td>\n".5246"</tr>\n";5247}5248print"</table>\n";5249}52505251sub git_history_body {5252# Warning: assumes constant type (blob or tree) during history5253my($commitlist,$from,$to,$refs,$extra,5254$file_name,$file_hash,$ftype) =@_;52555256$from=0unlessdefined$from;5257$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});52585259print"<table class=\"history\">\n";5260my$alternate=1;5261for(my$i=$from;$i<=$to;$i++) {5262my%co= %{$commitlist->[$i]};5263if(!%co) {5264next;5265}5266my$commit=$co{'id'};52675268my$ref= format_ref_marker($refs,$commit);52695270if($alternate) {5271print"<tr class=\"dark\">\n";5272}else{5273print"<tr class=\"light\">\n";5274}5275$alternate^=1;5276print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5277# shortlog: format_author_html('td', \%co, 10)5278 format_author_html('td', \%co,15,3) ."<td>";5279# originally git_history used chop_str($co{'title'}, 50)5280print format_subject_html($co{'title'},$co{'title_short'},5281 href(action=>"commit", hash=>$commit),$ref);5282print"</td>\n".5283"<td class=\"link\">".5284$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5285$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");52865287if($ftypeeq'blob') {5288my$blob_current=$file_hash;5289my$blob_parent= git_get_hash_by_path($commit,$file_name);5290if(defined$blob_current&&defined$blob_parent&&5291$blob_currentne$blob_parent) {5292print" | ".5293$cgi->a({-href => href(action=>"blobdiff",5294 hash=>$blob_current, hash_parent=>$blob_parent,5295 hash_base=>$hash_base, hash_parent_base=>$commit,5296 file_name=>$file_name)},5297"diff to current");5298}5299}5300print"</td>\n".5301"</tr>\n";5302}5303if(defined$extra) {5304print"<tr>\n".5305"<td colspan=\"4\">$extra</td>\n".5306"</tr>\n";5307}5308print"</table>\n";5309}53105311sub git_tags_body {5312# uses global variable $project5313my($taglist,$from,$to,$extra) =@_;5314$from=0unlessdefined$from;5315$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);53165317print"<table class=\"tags\">\n";5318my$alternate=1;5319for(my$i=$from;$i<=$to;$i++) {5320my$entry=$taglist->[$i];5321my%tag=%$entry;5322my$comment=$tag{'subject'};5323my$comment_short;5324if(defined$comment) {5325$comment_short= chop_str($comment,30,5);5326}5327if($alternate) {5328print"<tr class=\"dark\">\n";5329}else{5330print"<tr class=\"light\">\n";5331}5332$alternate^=1;5333if(defined$tag{'age'}) {5334print"<td><i>$tag{'age'}</i></td>\n";5335}else{5336print"<td></td>\n";5337}5338print"<td>".5339$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5340-class=>"list name"}, esc_html($tag{'name'})) .5341"</td>\n".5342"<td>";5343if(defined$comment) {5344print format_subject_html($comment,$comment_short,5345 href(action=>"tag", hash=>$tag{'id'}));5346}5347print"</td>\n".5348"<td class=\"selflink\">";5349if($tag{'type'}eq"tag") {5350print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");5351}else{5352print" ";5353}5354print"</td>\n".5355"<td class=\"link\">"." | ".5356$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});5357if($tag{'reftype'}eq"commit") {5358print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .5359" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");5360}elsif($tag{'reftype'}eq"blob") {5361print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");5362}5363print"</td>\n".5364"</tr>";5365}5366if(defined$extra) {5367print"<tr>\n".5368"<td colspan=\"5\">$extra</td>\n".5369"</tr>\n";5370}5371print"</table>\n";5372}53735374sub git_heads_body {5375# uses global variable $project5376my($headlist,$head,$from,$to,$extra) =@_;5377$from=0unlessdefined$from;5378$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);53795380print"<table class=\"heads\">\n";5381my$alternate=1;5382for(my$i=$from;$i<=$to;$i++) {5383my$entry=$headlist->[$i];5384my%ref=%$entry;5385my$curr=$ref{'id'}eq$head;5386if($alternate) {5387print"<tr class=\"dark\">\n";5388}else{5389print"<tr class=\"light\">\n";5390}5391$alternate^=1;5392print"<td><i>$ref{'age'}</i></td>\n".5393($curr?"<td class=\"current_head\">":"<td>") .5394$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),5395-class=>"list name"},esc_html($ref{'name'})) .5396"</td>\n".5397"<td class=\"link\">".5398$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".5399$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".5400$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .5401"</td>\n".5402"</tr>";5403}5404if(defined$extra) {5405print"<tr>\n".5406"<td colspan=\"3\">$extra</td>\n".5407"</tr>\n";5408}5409print"</table>\n";5410}54115412# Display a single remote block5413sub git_remote_block {5414my($remote,$rdata,$limit,$head) =@_;54155416my$heads=$rdata->{'heads'};5417my$fetch=$rdata->{'fetch'};5418my$push=$rdata->{'push'};54195420my$urls_table="<table class=\"projects_list\">\n";54215422if(defined$fetch) {5423if($fetcheq$push) {5424$urls_table.= format_repo_url("URL",$fetch);5425}else{5426$urls_table.= format_repo_url("Fetch URL",$fetch);5427$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;5428}5429}elsif(defined$push) {5430$urls_table.= format_repo_url("Push URL",$push);5431}else{5432$urls_table.= format_repo_url("","No remote URL");5433}54345435$urls_table.="</table>\n";54365437my$dots;5438if(defined$limit&&$limit<@$heads) {5439$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");5440}54415442print$urls_table;5443 git_heads_body($heads,$head,0,$limit,$dots);5444}54455446# Display a list of remote names with the respective fetch and push URLs5447sub git_remotes_list {5448my($remotedata,$limit) =@_;5449print"<table class=\"heads\">\n";5450my$alternate=1;5451my@remotes=sort keys%$remotedata;54525453my$limited=$limit&&$limit<@remotes;54545455$#remotes=$limit-1if$limited;54565457while(my$remote=shift@remotes) {5458my$rdata=$remotedata->{$remote};5459my$fetch=$rdata->{'fetch'};5460my$push=$rdata->{'push'};5461if($alternate) {5462print"<tr class=\"dark\">\n";5463}else{5464print"<tr class=\"light\">\n";5465}5466$alternate^=1;5467print"<td>".5468$cgi->a({-href=> href(action=>'remotes', hash=>$remote),5469-class=>"list name"},esc_html($remote)) .5470"</td>";5471print"<td class=\"link\">".5472(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .5473" | ".5474(defined$push?$cgi->a({-href=>$push},"push") :"push") .5475"</td>";54765477print"</tr>\n";5478}54795480if($limited) {5481print"<tr>\n".5482"<td colspan=\"3\">".5483$cgi->a({-href => href(action=>"remotes")},"...") .5484"</td>\n"."</tr>\n";5485}54865487print"</table>";5488}54895490# Display remote heads grouped by remote, unless there are too many5491# remotes, in which case we only display the remote names5492sub git_remotes_body {5493my($remotedata,$limit,$head) =@_;5494if($limitand$limit<keys%$remotedata) {5495 git_remotes_list($remotedata,$limit);5496}else{5497 fill_remote_heads($remotedata);5498while(my($remote,$rdata) =each%$remotedata) {5499 git_print_section({-class=>"remote", -id=>$remote},5500["remotes",$remote,$remote],sub{5501 git_remote_block($remote,$rdata,$limit,$head);5502});5503}5504}5505}55065507sub git_search_grep_body {5508my($commitlist,$from,$to,$extra) =@_;5509$from=0unlessdefined$from;5510$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);55115512print"<table class=\"commit_search\">\n";5513my$alternate=1;5514for(my$i=$from;$i<=$to;$i++) {5515my%co= %{$commitlist->[$i]};5516if(!%co) {5517next;5518}5519my$commit=$co{'id'};5520if($alternate) {5521print"<tr class=\"dark\">\n";5522}else{5523print"<tr class=\"light\">\n";5524}5525$alternate^=1;5526print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5527 format_author_html('td', \%co,15,5) .5528"<td>".5529$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5530-class=>"list subject"},5531 chop_and_escape_str($co{'title'},50) ."<br/>");5532my$comment=$co{'comment'};5533foreachmy$line(@$comment) {5534if($line=~m/^(.*?)($search_regexp)(.*)$/i) {5535my($lead,$match,$trail) = ($1,$2,$3);5536$match= chop_str($match,70,5,'center');5537my$contextlen=int((80-length($match))/2);5538$contextlen=30if($contextlen>30);5539$lead= chop_str($lead,$contextlen,10,'left');5540$trail= chop_str($trail,$contextlen,10,'right');55415542$lead= esc_html($lead);5543$match= esc_html($match);5544$trail= esc_html($trail);55455546print"$lead<span class=\"match\">$match</span>$trail<br />";5547}5548}5549print"</td>\n".5550"<td class=\"link\">".5551$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .5552" | ".5553$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .5554" | ".5555$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");5556print"</td>\n".5557"</tr>\n";5558}5559if(defined$extra) {5560print"<tr>\n".5561"<td colspan=\"3\">$extra</td>\n".5562"</tr>\n";5563}5564print"</table>\n";5565}55665567## ======================================================================5568## ======================================================================5569## actions55705571sub git_project_list {5572my$order=$input_params{'order'};5573if(defined$order&&$order!~m/none|project|descr|owner|age/) {5574 die_error(400,"Unknown order parameter");5575}55765577my@list= git_get_projects_list();5578if(!@list) {5579 die_error(404,"No projects found");5580}55815582 git_header_html();5583if(defined$home_text&& -f $home_text) {5584print"<div class=\"index_include\">\n";5585 insert_file($home_text);5586print"</div>\n";5587}5588print$cgi->startform(-method=>"get") .5589"<p class=\"projsearch\">Search:\n".5590$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".5591"</p>".5592$cgi->end_form() ."\n";5593 git_project_list_body(\@list,$order);5594 git_footer_html();5595}55965597sub git_forks {5598my$order=$input_params{'order'};5599if(defined$order&&$order!~m/none|project|descr|owner|age/) {5600 die_error(400,"Unknown order parameter");5601}56025603my@list= git_get_projects_list($project);5604if(!@list) {5605 die_error(404,"No forks found");5606}56075608 git_header_html();5609 git_print_page_nav('','');5610 git_print_header_div('summary',"$projectforks");5611 git_project_list_body(\@list,$order);5612 git_footer_html();5613}56145615sub git_project_index {5616my@projects= git_get_projects_list();5617if(!@projects) {5618 die_error(404,"No projects found");5619}56205621print$cgi->header(5622-type =>'text/plain',5623-charset =>'utf-8',5624-content_disposition =>'inline; filename="index.aux"');56255626foreachmy$pr(@projects) {5627if(!exists$pr->{'owner'}) {5628$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");5629}56305631my($path,$owner) = ($pr->{'path'},$pr->{'owner'});5632# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '5633$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5634$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5635$path=~s/ /\+/g;5636$owner=~s/ /\+/g;56375638print"$path$owner\n";5639}5640}56415642sub git_summary {5643my$descr= git_get_project_description($project) ||"none";5644my%co= parse_commit("HEAD");5645my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();5646my$head=$co{'id'};5647my$remote_heads= gitweb_check_feature('remote_heads');56485649my$owner= git_get_project_owner($project);56505651my$refs= git_get_references();5652# These get_*_list functions return one more to allow us to see if5653# there are more ...5654my@taglist= git_get_tags_list(16);5655my@headlist= git_get_heads_list(16);5656my%remotedata=$remote_heads? git_get_remotes_list() : ();5657my@forklist;5658my$check_forks= gitweb_check_feature('forks');56595660if($check_forks) {5661# find forks of a project5662@forklist= git_get_projects_list($project);5663# filter out forks of forks5664@forklist= filter_forks_from_projects_list(\@forklist)5665if(@forklist);5666}56675668 git_header_html();5669 git_print_page_nav('summary','',$head);56705671print"<div class=\"title\"> </div>\n";5672print"<table class=\"projects_list\">\n".5673"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".5674"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";5675if(defined$cd{'rfc2822'}) {5676print"<tr id=\"metadata_lchange\"><td>last change</td>".5677"<td>".format_timestamp_html(\%cd)."</td></tr>\n";5678}56795680# use per project git URL list in $projectroot/$project/cloneurl5681# or make project git URL from git base URL and project name5682my$url_tag="URL";5683my@url_list= git_get_project_url_list($project);5684@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;5685foreachmy$git_url(@url_list) {5686next unless$git_url;5687print format_repo_url($url_tag,$git_url);5688$url_tag="";5689}56905691# Tag cloud5692my$show_ctags= gitweb_check_feature('ctags');5693if($show_ctags) {5694my$ctags= git_get_project_ctags($project);5695if(%$ctags) {5696# without ability to add tags, don't show if there are none5697my$cloud= git_populate_project_tagcloud($ctags);5698print"<tr id=\"metadata_ctags\">".5699"<td>content tags</td>".5700"<td>".git_show_project_tagcloud($cloud,48)."</td>".5701"</tr>\n";5702}5703}57045705print"</table>\n";57065707# If XSS prevention is on, we don't include README.html.5708# TODO: Allow a readme in some safe format.5709if(!$prevent_xss&& -s "$projectroot/$project/README.html") {5710print"<div class=\"title\">readme</div>\n".5711"<div class=\"readme\">\n";5712 insert_file("$projectroot/$project/README.html");5713print"\n</div>\n";# class="readme"5714}57155716# we need to request one more than 16 (0..15) to check if5717# those 16 are all5718my@commitlist=$head? parse_commits($head,17) : ();5719if(@commitlist) {5720 git_print_header_div('shortlog');5721 git_shortlog_body(\@commitlist,0,15,$refs,5722$#commitlist<=15?undef:5723$cgi->a({-href => href(action=>"shortlog")},"..."));5724}57255726if(@taglist) {5727 git_print_header_div('tags');5728 git_tags_body(\@taglist,0,15,5729$#taglist<=15?undef:5730$cgi->a({-href => href(action=>"tags")},"..."));5731}57325733if(@headlist) {5734 git_print_header_div('heads');5735 git_heads_body(\@headlist,$head,0,15,5736$#headlist<=15?undef:5737$cgi->a({-href => href(action=>"heads")},"..."));5738}57395740if(%remotedata) {5741 git_print_header_div('remotes');5742 git_remotes_body(\%remotedata,15,$head);5743}57445745if(@forklist) {5746 git_print_header_div('forks');5747 git_project_list_body(\@forklist,'age',0,15,5748$#forklist<=15?undef:5749$cgi->a({-href => href(action=>"forks")},"..."),5750'no_header');5751}57525753 git_footer_html();5754}57555756sub git_tag {5757my%tag= parse_tag($hash);57585759if(!%tag) {5760 die_error(404,"Unknown tag object");5761}57625763my$head= git_get_head_hash($project);5764 git_header_html();5765 git_print_page_nav('','',$head,undef,$head);5766 git_print_header_div('commit', esc_html($tag{'name'}),$hash);5767print"<div class=\"title_text\">\n".5768"<table class=\"object_header\">\n".5769"<tr>\n".5770"<td>object</td>\n".5771"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5772$tag{'object'}) ."</td>\n".5773"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5774$tag{'type'}) ."</td>\n".5775"</tr>\n";5776if(defined($tag{'author'})) {5777 git_print_authorship_rows(\%tag,'author');5778}5779print"</table>\n\n".5780"</div>\n";5781print"<div class=\"page_body\">";5782my$comment=$tag{'comment'};5783foreachmy$line(@$comment) {5784chomp$line;5785print esc_html($line, -nbsp=>1) ."<br/>\n";5786}5787print"</div>\n";5788 git_footer_html();5789}57905791sub git_blame_common {5792my$format=shift||'porcelain';5793if($formateq'porcelain'&&$cgi->param('js')) {5794$format='incremental';5795$action='blame_incremental';# for page title etc5796}57975798# permissions5799 gitweb_check_feature('blame')5800or die_error(403,"Blame view not allowed");58015802# error checking5803 die_error(400,"No file name given")unless$file_name;5804$hash_base||= git_get_head_hash($project);5805 die_error(404,"Couldn't find base commit")unless$hash_base;5806my%co= parse_commit($hash_base)5807or die_error(404,"Commit not found");5808my$ftype="blob";5809if(!defined$hash) {5810$hash= git_get_hash_by_path($hash_base,$file_name,"blob")5811or die_error(404,"Error looking up file");5812}else{5813$ftype= git_get_type($hash);5814if($ftype!~"blob") {5815 die_error(400,"Object is not a blob");5816}5817}58185819my$fd;5820if($formateq'incremental') {5821# get file contents (as base)5822open$fd,"-|", git_cmd(),'cat-file','blob',$hash5823or die_error(500,"Open git-cat-file failed");5824}elsif($formateq'data') {5825# run git-blame --incremental5826open$fd,"-|", git_cmd(),"blame","--incremental",5827$hash_base,"--",$file_name5828or die_error(500,"Open git-blame --incremental failed");5829}else{5830# run git-blame --porcelain5831open$fd,"-|", git_cmd(),"blame",'-p',5832$hash_base,'--',$file_name5833or die_error(500,"Open git-blame --porcelain failed");5834}58355836# incremental blame data returns early5837if($formateq'data') {5838print$cgi->header(5839-type=>"text/plain", -charset =>"utf-8",5840-status=>"200 OK");5841local$| =1;# output autoflush5842printwhile<$fd>;5843close$fd5844or print"ERROR$!\n";58455846print'END';5847if(defined$t0&& gitweb_check_feature('timed')) {5848print' '.5849 tv_interval($t0, [ gettimeofday() ]).5850' '.$number_of_git_cmds;5851}5852print"\n";58535854return;5855}58565857# page header5858 git_header_html();5859my$formats_nav=5860$cgi->a({-href => href(action=>"blob", -replay=>1)},5861"blob") .5862" | ";5863if($formateq'incremental') {5864$formats_nav.=5865$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},5866"blame") ." (non-incremental)";5867}else{5868$formats_nav.=5869$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},5870"blame") ." (incremental)";5871}5872$formats_nav.=5873" | ".5874$cgi->a({-href => href(action=>"history", -replay=>1)},5875"history") .5876" | ".5877$cgi->a({-href => href(action=>$action, file_name=>$file_name)},5878"HEAD");5879 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5880 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5881 git_print_page_path($file_name,$ftype,$hash_base);58825883# page body5884if($formateq'incremental') {5885print"<noscript>\n<div class=\"error\"><center><b>\n".5886"This page requires JavaScript to run.\nUse ".5887$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},5888'this page').5889" instead.\n".5890"</b></center></div>\n</noscript>\n";58915892print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;5893}58945895print qq!<div class="page_body">\n!;5896print qq!<div id="progress_info">.../ ...</div>\n!5897if($formateq'incremental');5898print qq!<table id="blame_table"class="blame" width="100%">\n!.5899#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.5900 qq!<thead>\n!.5901 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.5902 qq!</thead>\n!.5903 qq!<tbody>\n!;59045905my@rev_color=qw(light dark);5906my$num_colors=scalar(@rev_color);5907my$current_color=0;59085909if($formateq'incremental') {5910my$color_class=$rev_color[$current_color];59115912#contents of a file5913my$linenr=0;5914 LINE:5915while(my$line= <$fd>) {5916chomp$line;5917$linenr++;59185919print qq!<tr id="l$linenr"class="$color_class">!.5920 qq!<td class="sha1"><a href=""> </a></td>!.5921 qq!<td class="linenr">!.5922 qq!<a class="linenr" href="">$linenr</a></td>!;5923print qq!<td class="pre">! . esc_html($line) ."</td>\n";5924print qq!</tr>\n!;5925}59265927}else{# porcelain, i.e. ordinary blame5928my%metainfo= ();# saves information about commits59295930# blame data5931 LINE:5932while(my$line= <$fd>) {5933chomp$line;5934# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]5935# no <lines in group> for subsequent lines in group of lines5936my($full_rev,$orig_lineno,$lineno,$group_size) =5937($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);5938if(!exists$metainfo{$full_rev}) {5939$metainfo{$full_rev} = {'nprevious'=>0};5940}5941my$meta=$metainfo{$full_rev};5942my$data;5943while($data= <$fd>) {5944chomp$data;5945last if($data=~s/^\t//);# contents of line5946if($data=~/^(\S+)(?: (.*))?$/) {5947$meta->{$1} =$2unlessexists$meta->{$1};5948}5949if($data=~/^previous /) {5950$meta->{'nprevious'}++;5951}5952}5953my$short_rev=substr($full_rev,0,8);5954my$author=$meta->{'author'};5955my%date=5956 parse_date($meta->{'author-time'},$meta->{'author-tz'});5957my$date=$date{'iso-tz'};5958if($group_size) {5959$current_color= ($current_color+1) %$num_colors;5960}5961my$tr_class=$rev_color[$current_color];5962$tr_class.=' boundary'if(exists$meta->{'boundary'});5963$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);5964$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);5965print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";5966if($group_size) {5967print"<td class=\"sha1\"";5968print" title=\"". esc_html($author) .",$date\"";5969print" rowspan=\"$group_size\""if($group_size>1);5970print">";5971print$cgi->a({-href => href(action=>"commit",5972 hash=>$full_rev,5973 file_name=>$file_name)},5974 esc_html($short_rev));5975if($group_size>=2) {5976my@author_initials= ($author=~/\b([[:upper:]])\B/g);5977if(@author_initials) {5978print"<br />".5979 esc_html(join('',@author_initials));5980# or join('.', ...)5981}5982}5983print"</td>\n";5984}5985# 'previous' <sha1 of parent commit> <filename at commit>5986if(exists$meta->{'previous'} &&5987$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {5988$meta->{'parent'} =$1;5989$meta->{'file_parent'} = unquote($2);5990}5991my$linenr_commit=5992exists($meta->{'parent'}) ?5993$meta->{'parent'} :$full_rev;5994my$linenr_filename=5995exists($meta->{'file_parent'}) ?5996$meta->{'file_parent'} : unquote($meta->{'filename'});5997my$blamed= href(action =>'blame',5998 file_name =>$linenr_filename,5999 hash_base =>$linenr_commit);6000print"<td class=\"linenr\">";6001print$cgi->a({ -href =>"$blamed#l$orig_lineno",6002-class=>"linenr"},6003 esc_html($lineno));6004print"</td>";6005print"<td class=\"pre\">". esc_html($data) ."</td>\n";6006print"</tr>\n";6007}# end while60086009}60106011# footer6012print"</tbody>\n".6013"</table>\n";# class="blame"6014print"</div>\n";# class="blame_body"6015close$fd6016or print"Reading blob failed\n";60176018 git_footer_html();6019}60206021sub git_blame {6022 git_blame_common();6023}60246025sub git_blame_incremental {6026 git_blame_common('incremental');6027}60286029sub git_blame_data {6030 git_blame_common('data');6031}60326033sub git_tags {6034my$head= git_get_head_hash($project);6035 git_header_html();6036 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6037 git_print_header_div('summary',$project);60386039my@tagslist= git_get_tags_list();6040if(@tagslist) {6041 git_tags_body(\@tagslist);6042}6043 git_footer_html();6044}60456046sub git_heads {6047my$head= git_get_head_hash($project);6048 git_header_html();6049 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6050 git_print_header_div('summary',$project);60516052my@headslist= git_get_heads_list();6053if(@headslist) {6054 git_heads_body(\@headslist,$head);6055}6056 git_footer_html();6057}60586059# used both for single remote view and for list of all the remotes6060sub git_remotes {6061 gitweb_check_feature('remote_heads')6062or die_error(403,"Remote heads view is disabled");60636064my$head= git_get_head_hash($project);6065my$remote=$input_params{'hash'};60666067my$remotedata= git_get_remotes_list($remote);6068 die_error(500,"Unable to get remote information")unlessdefined$remotedata;60696070unless(%$remotedata) {6071 die_error(404,defined$remote?6072"Remote$remotenot found":6073"No remotes found");6074}60756076 git_header_html(undef,undef, -action_extra =>$remote);6077 git_print_page_nav('','',$head,undef,$head,6078 format_ref_views($remote?'':'remotes'));60796080 fill_remote_heads($remotedata);6081if(defined$remote) {6082 git_print_header_div('remotes',"$remoteremote for$project");6083 git_remote_block($remote,$remotedata->{$remote},undef,$head);6084}else{6085 git_print_header_div('summary',"$projectremotes");6086 git_remotes_body($remotedata,undef,$head);6087}60886089 git_footer_html();6090}60916092sub git_blob_plain {6093my$type=shift;6094my$expires;60956096if(!defined$hash) {6097if(defined$file_name) {6098my$base=$hash_base|| git_get_head_hash($project);6099$hash= git_get_hash_by_path($base,$file_name,"blob")6100or die_error(404,"Cannot find file");6101}else{6102 die_error(400,"No file name defined");6103}6104}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6105# blobs defined by non-textual hash id's can be cached6106$expires="+1d";6107}61086109open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6110or die_error(500,"Open git-cat-file blob '$hash' failed");61116112# content-type (can include charset)6113$type= blob_contenttype($fd,$file_name,$type);61146115# "save as" filename, even when no $file_name is given6116my$save_as="$hash";6117if(defined$file_name) {6118$save_as=$file_name;6119}elsif($type=~m/^text\//) {6120$save_as.='.txt';6121}61226123# With XSS prevention on, blobs of all types except a few known safe6124# ones are served with "Content-Disposition: attachment" to make sure6125# they don't run in our security domain. For certain image types,6126# blob view writes an <img> tag referring to blob_plain view, and we6127# want to be sure not to break that by serving the image as an6128# attachment (though Firefox 3 doesn't seem to care).6129my$sandbox=$prevent_xss&&6130$type!~m!^(?:text/plain|image/(?:gif|png|jpeg))$!;61316132print$cgi->header(6133-type =>$type,6134-expires =>$expires,6135-content_disposition =>6136($sandbox?'attachment':'inline')6137.'; filename="'.$save_as.'"');6138local$/=undef;6139binmode STDOUT,':raw';6140print<$fd>;6141binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6142close$fd;6143}61446145sub git_blob {6146my$expires;61476148if(!defined$hash) {6149if(defined$file_name) {6150my$base=$hash_base|| git_get_head_hash($project);6151$hash= git_get_hash_by_path($base,$file_name,"blob")6152or die_error(404,"Cannot find file");6153}else{6154 die_error(400,"No file name defined");6155}6156}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6157# blobs defined by non-textual hash id's can be cached6158$expires="+1d";6159}61606161my$have_blame= gitweb_check_feature('blame');6162open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6163or die_error(500,"Couldn't cat$file_name,$hash");6164my$mimetype= blob_mimetype($fd,$file_name);6165# use 'blob_plain' (aka 'raw') view for files that cannot be displayed6166if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {6167close$fd;6168return git_blob_plain($mimetype);6169}6170# we can have blame only for text/* mimetype6171$have_blame&&= ($mimetype=~m!^text/!);61726173my$highlight= gitweb_check_feature('highlight');6174my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);6175$fd= run_highlighter($fd,$highlight,$syntax)6176if$syntax;61776178 git_header_html(undef,$expires);6179my$formats_nav='';6180if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6181if(defined$file_name) {6182if($have_blame) {6183$formats_nav.=6184$cgi->a({-href => href(action=>"blame", -replay=>1)},6185"blame") .6186" | ";6187}6188$formats_nav.=6189$cgi->a({-href => href(action=>"history", -replay=>1)},6190"history") .6191" | ".6192$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6193"raw") .6194" | ".6195$cgi->a({-href => href(action=>"blob",6196 hash_base=>"HEAD", file_name=>$file_name)},6197"HEAD");6198}else{6199$formats_nav.=6200$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6201"raw");6202}6203 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6204 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6205}else{6206print"<div class=\"page_nav\">\n".6207"<br/><br/></div>\n".6208"<div class=\"title\">".esc_html($hash)."</div>\n";6209}6210 git_print_page_path($file_name,"blob",$hash_base);6211print"<div class=\"page_body\">\n";6212if($mimetype=~m!^image/!) {6213print qq!<img type="!.esc_attr($mimetype).qq!"!;6214if($file_name) {6215print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;6216}6217print qq! src="! .6218 href(action=>"blob_plain", hash=>$hash,6219 hash_base=>$hash_base, file_name=>$file_name) .6220 qq!"/>\n!;6221}else{6222my$nr;6223while(my$line= <$fd>) {6224chomp$line;6225$nr++;6226$line= untabify($line);6227printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,6228$nr, esc_attr(href(-replay =>1)),$nr,$nr,$syntax?$line: esc_html($line, -nbsp=>1);6229}6230}6231close$fd6232or print"Reading blob failed.\n";6233print"</div>";6234 git_footer_html();6235}62366237sub git_tree {6238if(!defined$hash_base) {6239$hash_base="HEAD";6240}6241if(!defined$hash) {6242if(defined$file_name) {6243$hash= git_get_hash_by_path($hash_base,$file_name,"tree");6244}else{6245$hash=$hash_base;6246}6247}6248 die_error(404,"No such tree")unlessdefined($hash);62496250my$show_sizes= gitweb_check_feature('show-sizes');6251my$have_blame= gitweb_check_feature('blame');62526253my@entries= ();6254{6255local$/="\0";6256open my$fd,"-|", git_cmd(),"ls-tree",'-z',6257($show_sizes?'-l': ()),@extra_options,$hash6258or die_error(500,"Open git-ls-tree failed");6259@entries=map{chomp;$_} <$fd>;6260close$fd6261or die_error(404,"Reading tree failed");6262}62636264my$refs= git_get_references();6265my$ref= format_ref_marker($refs,$hash_base);6266 git_header_html();6267my$basedir='';6268if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6269my@views_nav= ();6270if(defined$file_name) {6271push@views_nav,6272$cgi->a({-href => href(action=>"history", -replay=>1)},6273"history"),6274$cgi->a({-href => href(action=>"tree",6275 hash_base=>"HEAD", file_name=>$file_name)},6276"HEAD"),6277}6278my$snapshot_links= format_snapshot_links($hash);6279if(defined$snapshot_links) {6280# FIXME: Should be available when we have no hash base as well.6281push@views_nav,$snapshot_links;6282}6283 git_print_page_nav('tree','',$hash_base,undef,undef,6284join(' | ',@views_nav));6285 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);6286}else{6287undef$hash_base;6288print"<div class=\"page_nav\">\n";6289print"<br/><br/></div>\n";6290print"<div class=\"title\">".esc_html($hash)."</div>\n";6291}6292if(defined$file_name) {6293$basedir=$file_name;6294if($basedirne''&&substr($basedir, -1)ne'/') {6295$basedir.='/';6296}6297 git_print_page_path($file_name,'tree',$hash_base);6298}6299print"<div class=\"page_body\">\n";6300print"<table class=\"tree\">\n";6301my$alternate=1;6302# '..' (top directory) link if possible6303if(defined$hash_base&&6304defined$file_name&&$file_name=~m![^/]+$!) {6305if($alternate) {6306print"<tr class=\"dark\">\n";6307}else{6308print"<tr class=\"light\">\n";6309}6310$alternate^=1;63116312my$up=$file_name;6313$up=~s!/?[^/]+$!!;6314undef$upunless$up;6315# based on git_print_tree_entry6316print'<td class="mode">'. mode_str('040000') ."</td>\n";6317print'<td class="size"> </td>'."\n"if$show_sizes;6318print'<td class="list">';6319print$cgi->a({-href => href(action=>"tree",6320 hash_base=>$hash_base,6321 file_name=>$up)},6322"..");6323print"</td>\n";6324print"<td class=\"link\"></td>\n";63256326print"</tr>\n";6327}6328foreachmy$line(@entries) {6329my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);63306331if($alternate) {6332print"<tr class=\"dark\">\n";6333}else{6334print"<tr class=\"light\">\n";6335}6336$alternate^=1;63376338 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);63396340print"</tr>\n";6341}6342print"</table>\n".6343"</div>";6344 git_footer_html();6345}63466347sub snapshot_name {6348my($project,$hash) =@_;63496350# path/to/project.git -> project6351# path/to/project/.git -> project6352my$name= to_utf8($project);6353$name=~ s,([^/])/*\.git$,$1,;6354$name= basename($name);6355# sanitize name6356$name=~s/[[:cntrl:]]/?/g;63576358my$ver=$hash;6359if($hash=~/^[0-9a-fA-F]+$/) {6360# shorten SHA-1 hash6361my$full_hash= git_get_full_hash($project,$hash);6362if($full_hash=~/^$hash/&&length($hash) >7) {6363$ver= git_get_short_hash($project,$hash);6364}6365}elsif($hash=~m!^refs/tags/(.*)$!) {6366# tags don't need shortened SHA-1 hash6367$ver=$1;6368}else{6369# branches and other need shortened SHA-1 hash6370if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {6371$ver=$1;6372}6373$ver.='-'. git_get_short_hash($project,$hash);6374}6375# in case of hierarchical branch names6376$ver=~s!/!.!g;63776378# name = project-version_string6379$name="$name-$ver";63806381returnwantarray? ($name,$name) :$name;6382}63836384sub git_snapshot {6385my$format=$input_params{'snapshot_format'};6386if(!@snapshot_fmts) {6387 die_error(403,"Snapshots not allowed");6388}6389# default to first supported snapshot format6390$format||=$snapshot_fmts[0];6391if($format!~m/^[a-z0-9]+$/) {6392 die_error(400,"Invalid snapshot format parameter");6393}elsif(!exists($known_snapshot_formats{$format})) {6394 die_error(400,"Unknown snapshot format");6395}elsif($known_snapshot_formats{$format}{'disabled'}) {6396 die_error(403,"Snapshot format not allowed");6397}elsif(!grep($_eq$format,@snapshot_fmts)) {6398 die_error(403,"Unsupported snapshot format");6399}64006401my$type= git_get_type("$hash^{}");6402if(!$type) {6403 die_error(404,'Object does not exist');6404}elsif($typeeq'blob') {6405 die_error(400,'Object is not a tree-ish');6406}64076408my($name,$prefix) = snapshot_name($project,$hash);6409my$filename="$name$known_snapshot_formats{$format}{'suffix'}";6410my$cmd= quote_command(6411 git_cmd(),'archive',6412"--format=$known_snapshot_formats{$format}{'format'}",6413"--prefix=$prefix/",$hash);6414if(exists$known_snapshot_formats{$format}{'compressor'}) {6415$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});6416}64176418$filename=~s/(["\\])/\\$1/g;6419print$cgi->header(6420-type =>$known_snapshot_formats{$format}{'type'},6421-content_disposition =>'inline; filename="'.$filename.'"',6422-status =>'200 OK');64236424open my$fd,"-|",$cmd6425or die_error(500,"Execute git-archive failed");6426binmode STDOUT,':raw';6427print<$fd>;6428binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6429close$fd;6430}64316432sub git_log_generic {6433my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;64346435my$head= git_get_head_hash($project);6436if(!defined$base) {6437$base=$head;6438}6439if(!defined$page) {6440$page=0;6441}6442my$refs= git_get_references();64436444my$commit_hash=$base;6445if(defined$parent) {6446$commit_hash="$parent..$base";6447}6448my@commitlist=6449 parse_commits($commit_hash,101, (100*$page),6450defined$file_name? ($file_name,"--full-history") : ());64516452my$ftype;6453if(!defined$file_hash&&defined$file_name) {6454# some commits could have deleted file in question,6455# and not have it in tree, but one of them has to have it6456for(my$i=0;$i<@commitlist;$i++) {6457$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);6458last ifdefined$file_hash;6459}6460}6461if(defined$file_hash) {6462$ftype= git_get_type($file_hash);6463}6464if(defined$file_name&& !defined$ftype) {6465 die_error(500,"Unknown type of object");6466}6467my%co;6468if(defined$file_name) {6469%co= parse_commit($base)6470or die_error(404,"Unknown commit object");6471}647264736474my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);6475my$next_link='';6476if($#commitlist>=100) {6477$next_link=6478$cgi->a({-href => href(-replay=>1, page=>$page+1),6479-accesskey =>"n", -title =>"Alt-n"},"next");6480}6481my$patch_max= gitweb_get_feature('patches');6482if($patch_max&& !defined$file_name) {6483if($patch_max<0||@commitlist<=$patch_max) {6484$paging_nav.=" ⋅ ".6485$cgi->a({-href => href(action=>"patches", -replay=>1)},6486"patches");6487}6488}64896490 git_header_html();6491 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);6492if(defined$file_name) {6493 git_print_header_div('commit', esc_html($co{'title'}),$base);6494}else{6495 git_print_header_div('summary',$project)6496}6497 git_print_page_path($file_name,$ftype,$hash_base)6498if(defined$file_name);64996500$body_subr->(\@commitlist,0,99,$refs,$next_link,6501$file_name,$file_hash,$ftype);65026503 git_footer_html();6504}65056506sub git_log {6507 git_log_generic('log', \&git_log_body,6508$hash,$hash_parent);6509}65106511sub git_commit {6512$hash||=$hash_base||"HEAD";6513my%co= parse_commit($hash)6514or die_error(404,"Unknown commit object");65156516my$parent=$co{'parent'};6517my$parents=$co{'parents'};# listref65186519# we need to prepare $formats_nav before any parameter munging6520my$formats_nav;6521if(!defined$parent) {6522# --root commitdiff6523$formats_nav.='(initial)';6524}elsif(@$parents==1) {6525# single parent commit6526$formats_nav.=6527'(parent: '.6528$cgi->a({-href => href(action=>"commit",6529 hash=>$parent)},6530 esc_html(substr($parent,0,7))) .6531')';6532}else{6533# merge commit6534$formats_nav.=6535'(merge: '.6536join(' ',map{6537$cgi->a({-href => href(action=>"commit",6538 hash=>$_)},6539 esc_html(substr($_,0,7)));6540}@$parents) .6541')';6542}6543if(gitweb_check_feature('patches') &&@$parents<=1) {6544$formats_nav.=" | ".6545$cgi->a({-href => href(action=>"patch", -replay=>1)},6546"patch");6547}65486549if(!defined$parent) {6550$parent="--root";6551}6552my@difftree;6553open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",6554@diff_opts,6555(@$parents<=1?$parent:'-c'),6556$hash,"--"6557or die_error(500,"Open git-diff-tree failed");6558@difftree=map{chomp;$_} <$fd>;6559close$fdor die_error(404,"Reading git-diff-tree failed");65606561# non-textual hash id's can be cached6562my$expires;6563if($hash=~m/^[0-9a-fA-F]{40}$/) {6564$expires="+1d";6565}6566my$refs= git_get_references();6567my$ref= format_ref_marker($refs,$co{'id'});65686569 git_header_html(undef,$expires);6570 git_print_page_nav('commit','',6571$hash,$co{'tree'},$hash,6572$formats_nav);65736574if(defined$co{'parent'}) {6575 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);6576}else{6577 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);6578}6579print"<div class=\"title_text\">\n".6580"<table class=\"object_header\">\n";6581 git_print_authorship_rows(\%co);6582print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";6583print"<tr>".6584"<td>tree</td>".6585"<td class=\"sha1\">".6586$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),6587class=>"list"},$co{'tree'}) .6588"</td>".6589"<td class=\"link\">".6590$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},6591"tree");6592my$snapshot_links= format_snapshot_links($hash);6593if(defined$snapshot_links) {6594print" | ".$snapshot_links;6595}6596print"</td>".6597"</tr>\n";65986599foreachmy$par(@$parents) {6600print"<tr>".6601"<td>parent</td>".6602"<td class=\"sha1\">".6603$cgi->a({-href => href(action=>"commit", hash=>$par),6604class=>"list"},$par) .6605"</td>".6606"<td class=\"link\">".6607$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .6608" | ".6609$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .6610"</td>".6611"</tr>\n";6612}6613print"</table>".6614"</div>\n";66156616print"<div class=\"page_body\">\n";6617 git_print_log($co{'comment'});6618print"</div>\n";66196620 git_difftree_body(\@difftree,$hash,@$parents);66216622 git_footer_html();6623}66246625sub git_object {6626# object is defined by:6627# - hash or hash_base alone6628# - hash_base and file_name6629my$type;66306631# - hash or hash_base alone6632if($hash|| ($hash_base&& !defined$file_name)) {6633my$object_id=$hash||$hash_base;66346635open my$fd,"-|", quote_command(6636 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'6637or die_error(404,"Object does not exist");6638$type= <$fd>;6639chomp$type;6640close$fd6641or die_error(404,"Object does not exist");66426643# - hash_base and file_name6644}elsif($hash_base&&defined$file_name) {6645$file_name=~ s,/+$,,;66466647system(git_cmd(),"cat-file",'-e',$hash_base) ==06648or die_error(404,"Base object does not exist");66496650# here errors should not hapen6651open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name6652or die_error(500,"Open git-ls-tree failed");6653my$line= <$fd>;6654close$fd;66556656#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'6657unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {6658 die_error(404,"File or directory for given base does not exist");6659}6660$type=$2;6661$hash=$3;6662}else{6663 die_error(400,"Not enough information to find object");6664}66656666print$cgi->redirect(-uri => href(action=>$type, -full=>1,6667 hash=>$hash, hash_base=>$hash_base,6668 file_name=>$file_name),6669-status =>'302 Found');6670}66716672sub git_blobdiff {6673my$format=shift||'html';66746675my$fd;6676my@difftree;6677my%diffinfo;6678my$expires;66796680# preparing $fd and %diffinfo for git_patchset_body6681# new style URI6682if(defined$hash_base&&defined$hash_parent_base) {6683if(defined$file_name) {6684# read raw output6685open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6686$hash_parent_base,$hash_base,6687"--", (defined$file_parent?$file_parent: ()),$file_name6688or die_error(500,"Open git-diff-tree failed");6689@difftree=map{chomp;$_} <$fd>;6690close$fd6691or die_error(404,"Reading git-diff-tree failed");6692@difftree6693or die_error(404,"Blob diff not found");66946695}elsif(defined$hash&&6696$hash=~/[0-9a-fA-F]{40}/) {6697# try to find filename from $hash66986699# read filtered raw output6700open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6701$hash_parent_base,$hash_base,"--"6702or die_error(500,"Open git-diff-tree failed");6703@difftree=6704# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'6705# $hash == to_id6706grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}6707map{chomp;$_} <$fd>;6708close$fd6709or die_error(404,"Reading git-diff-tree failed");6710@difftree6711or die_error(404,"Blob diff not found");67126713}else{6714 die_error(400,"Missing one of the blob diff parameters");6715}67166717if(@difftree>1) {6718 die_error(400,"Ambiguous blob diff specification");6719}67206721%diffinfo= parse_difftree_raw_line($difftree[0]);6722$file_parent||=$diffinfo{'from_file'} ||$file_name;6723$file_name||=$diffinfo{'to_file'};67246725$hash_parent||=$diffinfo{'from_id'};6726$hash||=$diffinfo{'to_id'};67276728# non-textual hash id's can be cached6729if($hash_base=~m/^[0-9a-fA-F]{40}$/&&6730$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {6731$expires='+1d';6732}67336734# open patch output6735open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6736'-p', ($formateq'html'?"--full-index": ()),6737$hash_parent_base,$hash_base,6738"--", (defined$file_parent?$file_parent: ()),$file_name6739or die_error(500,"Open git-diff-tree failed");6740}67416742# old/legacy style URI -- not generated anymore since 1.4.3.6743if(!%diffinfo) {6744 die_error('404 Not Found',"Missing one of the blob diff parameters")6745}67466747# header6748if($formateq'html') {6749my$formats_nav=6750$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},6751"raw");6752 git_header_html(undef,$expires);6753if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6754 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6755 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6756}else{6757print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";6758print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";6759}6760if(defined$file_name) {6761 git_print_page_path($file_name,"blob",$hash_base);6762}else{6763print"<div class=\"page_path\"></div>\n";6764}67656766}elsif($formateq'plain') {6767print$cgi->header(6768-type =>'text/plain',6769-charset =>'utf-8',6770-expires =>$expires,6771-content_disposition =>'inline; filename="'."$file_name".'.patch"');67726773print"X-Git-Url: ".$cgi->self_url() ."\n\n";67746775}else{6776 die_error(400,"Unknown blobdiff format");6777}67786779# patch6780if($formateq'html') {6781print"<div class=\"page_body\">\n";67826783 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);6784close$fd;67856786print"</div>\n";# class="page_body"6787 git_footer_html();67886789}else{6790while(my$line= <$fd>) {6791$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;6792$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;67936794print$line;67956796last if$line=~m!^\+\+\+!;6797}6798local$/=undef;6799print<$fd>;6800close$fd;6801}6802}68036804sub git_blobdiff_plain {6805 git_blobdiff('plain');6806}68076808sub git_commitdiff {6809my%params=@_;6810my$format=$params{-format} ||'html';68116812my($patch_max) = gitweb_get_feature('patches');6813if($formateq'patch') {6814 die_error(403,"Patch view not allowed")unless$patch_max;6815}68166817$hash||=$hash_base||"HEAD";6818my%co= parse_commit($hash)6819or die_error(404,"Unknown commit object");68206821# choose format for commitdiff for merge6822if(!defined$hash_parent&& @{$co{'parents'}} >1) {6823$hash_parent='--cc';6824}6825# we need to prepare $formats_nav before almost any parameter munging6826my$formats_nav;6827if($formateq'html') {6828$formats_nav=6829$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},6830"raw");6831if($patch_max&& @{$co{'parents'}} <=1) {6832$formats_nav.=" | ".6833$cgi->a({-href => href(action=>"patch", -replay=>1)},6834"patch");6835}68366837if(defined$hash_parent&&6838$hash_parentne'-c'&&$hash_parentne'--cc') {6839# commitdiff with two commits given6840my$hash_parent_short=$hash_parent;6841if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {6842$hash_parent_short=substr($hash_parent,0,7);6843}6844$formats_nav.=6845' (from';6846for(my$i=0;$i< @{$co{'parents'}};$i++) {6847if($co{'parents'}[$i]eq$hash_parent) {6848$formats_nav.=' parent '. ($i+1);6849last;6850}6851}6852$formats_nav.=': '.6853$cgi->a({-href => href(action=>"commitdiff",6854 hash=>$hash_parent)},6855 esc_html($hash_parent_short)) .6856')';6857}elsif(!$co{'parent'}) {6858# --root commitdiff6859$formats_nav.=' (initial)';6860}elsif(scalar@{$co{'parents'}} ==1) {6861# single parent commit6862$formats_nav.=6863' (parent: '.6864$cgi->a({-href => href(action=>"commitdiff",6865 hash=>$co{'parent'})},6866 esc_html(substr($co{'parent'},0,7))) .6867')';6868}else{6869# merge commit6870if($hash_parenteq'--cc') {6871$formats_nav.=' | '.6872$cgi->a({-href => href(action=>"commitdiff",6873 hash=>$hash, hash_parent=>'-c')},6874'combined');6875}else{# $hash_parent eq '-c'6876$formats_nav.=' | '.6877$cgi->a({-href => href(action=>"commitdiff",6878 hash=>$hash, hash_parent=>'--cc')},6879'compact');6880}6881$formats_nav.=6882' (merge: '.6883join(' ',map{6884$cgi->a({-href => href(action=>"commitdiff",6885 hash=>$_)},6886 esc_html(substr($_,0,7)));6887} @{$co{'parents'}} ) .6888')';6889}6890}68916892my$hash_parent_param=$hash_parent;6893if(!defined$hash_parent_param) {6894# --cc for multiple parents, --root for parentless6895$hash_parent_param=6896@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';6897}68986899# read commitdiff6900my$fd;6901my@difftree;6902if($formateq'html') {6903open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6904"--no-commit-id","--patch-with-raw","--full-index",6905$hash_parent_param,$hash,"--"6906or die_error(500,"Open git-diff-tree failed");69076908while(my$line= <$fd>) {6909chomp$line;6910# empty line ends raw part of diff-tree output6911last unless$line;6912push@difftree,scalar parse_difftree_raw_line($line);6913}69146915}elsif($formateq'plain') {6916open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6917'-p',$hash_parent_param,$hash,"--"6918or die_error(500,"Open git-diff-tree failed");6919}elsif($formateq'patch') {6920# For commit ranges, we limit the output to the number of6921# patches specified in the 'patches' feature.6922# For single commits, we limit the output to a single patch,6923# diverging from the git-format-patch default.6924my@commit_spec= ();6925if($hash_parent) {6926if($patch_max>0) {6927push@commit_spec,"-$patch_max";6928}6929push@commit_spec,'-n',"$hash_parent..$hash";6930}else{6931if($params{-single}) {6932push@commit_spec,'-1';6933}else{6934if($patch_max>0) {6935push@commit_spec,"-$patch_max";6936}6937push@commit_spec,"-n";6938}6939push@commit_spec,'--root',$hash;6940}6941open$fd,"-|", git_cmd(),"format-patch",@diff_opts,6942'--encoding=utf8','--stdout',@commit_spec6943or die_error(500,"Open git-format-patch failed");6944}else{6945 die_error(400,"Unknown commitdiff format");6946}69476948# non-textual hash id's can be cached6949my$expires;6950if($hash=~m/^[0-9a-fA-F]{40}$/) {6951$expires="+1d";6952}69536954# write commit message6955if($formateq'html') {6956my$refs= git_get_references();6957my$ref= format_ref_marker($refs,$co{'id'});69586959 git_header_html(undef,$expires);6960 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);6961 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);6962print"<div class=\"title_text\">\n".6963"<table class=\"object_header\">\n";6964 git_print_authorship_rows(\%co);6965print"</table>".6966"</div>\n";6967print"<div class=\"page_body\">\n";6968if(@{$co{'comment'}} >1) {6969print"<div class=\"log\">\n";6970 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);6971print"</div>\n";# class="log"6972}69736974}elsif($formateq'plain') {6975my$refs= git_get_references("tags");6976my$tagname= git_get_rev_name_tags($hash);6977my$filename= basename($project) ."-$hash.patch";69786979print$cgi->header(6980-type =>'text/plain',6981-charset =>'utf-8',6982-expires =>$expires,6983-content_disposition =>'inline; filename="'."$filename".'"');6984my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});6985print"From: ". to_utf8($co{'author'}) ."\n";6986print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";6987print"Subject: ". to_utf8($co{'title'}) ."\n";69886989print"X-Git-Tag:$tagname\n"if$tagname;6990print"X-Git-Url: ".$cgi->self_url() ."\n\n";69916992foreachmy$line(@{$co{'comment'}}) {6993print to_utf8($line) ."\n";6994}6995print"---\n\n";6996}elsif($formateq'patch') {6997my$filename= basename($project) ."-$hash.patch";69986999print$cgi->header(7000-type =>'text/plain',7001-charset =>'utf-8',7002-expires =>$expires,7003-content_disposition =>'inline; filename="'."$filename".'"');7004}70057006# write patch7007if($formateq'html') {7008my$use_parents= !defined$hash_parent||7009$hash_parenteq'-c'||$hash_parenteq'--cc';7010 git_difftree_body(\@difftree,$hash,7011$use_parents? @{$co{'parents'}} :$hash_parent);7012print"<br/>\n";70137014 git_patchset_body($fd, \@difftree,$hash,7015$use_parents? @{$co{'parents'}} :$hash_parent);7016close$fd;7017print"</div>\n";# class="page_body"7018 git_footer_html();70197020}elsif($formateq'plain') {7021local$/=undef;7022print<$fd>;7023close$fd7024or print"Reading git-diff-tree failed\n";7025}elsif($formateq'patch') {7026local$/=undef;7027print<$fd>;7028close$fd7029or print"Reading git-format-patch failed\n";7030}7031}70327033sub git_commitdiff_plain {7034 git_commitdiff(-format =>'plain');7035}70367037# format-patch-style patches7038sub git_patch {7039 git_commitdiff(-format =>'patch', -single =>1);7040}70417042sub git_patches {7043 git_commitdiff(-format =>'patch');7044}70457046sub git_history {7047 git_log_generic('history', \&git_history_body,7048$hash_base,$hash_parent_base,7049$file_name,$hash);7050}70517052sub git_search {7053 gitweb_check_feature('search')or die_error(403,"Search is disabled");7054if(!defined$searchtext) {7055 die_error(400,"Text field is empty");7056}7057if(!defined$hash) {7058$hash= git_get_head_hash($project);7059}7060my%co= parse_commit($hash);7061if(!%co) {7062 die_error(404,"Unknown commit object");7063}7064if(!defined$page) {7065$page=0;7066}70677068$searchtype||='commit';7069if($searchtypeeq'pickaxe') {7070# pickaxe may take all resources of your box and run for several minutes7071# with every query - so decide by yourself how public you make this feature7072 gitweb_check_feature('pickaxe')7073or die_error(403,"Pickaxe is disabled");7074}7075if($searchtypeeq'grep') {7076 gitweb_check_feature('grep')7077or die_error(403,"Grep is disabled");7078}70797080 git_header_html();70817082if($searchtypeeq'commit'or$searchtypeeq'author'or$searchtypeeq'committer') {7083my$greptype;7084if($searchtypeeq'commit') {7085$greptype="--grep=";7086}elsif($searchtypeeq'author') {7087$greptype="--author=";7088}elsif($searchtypeeq'committer') {7089$greptype="--committer=";7090}7091$greptype.=$searchtext;7092my@commitlist= parse_commits($hash,101, (100*$page),undef,7093$greptype,'--regexp-ignore-case',7094$search_use_regexp?'--extended-regexp':'--fixed-strings');70957096my$paging_nav='';7097if($page>0) {7098$paging_nav.=7099$cgi->a({-href => href(action=>"search", hash=>$hash,7100 searchtext=>$searchtext,7101 searchtype=>$searchtype)},7102"first");7103$paging_nav.=" ⋅ ".7104$cgi->a({-href => href(-replay=>1, page=>$page-1),7105-accesskey =>"p", -title =>"Alt-p"},"prev");7106}else{7107$paging_nav.="first";7108$paging_nav.=" ⋅ prev";7109}7110my$next_link='';7111if($#commitlist>=100) {7112$next_link=7113$cgi->a({-href => href(-replay=>1, page=>$page+1),7114-accesskey =>"n", -title =>"Alt-n"},"next");7115$paging_nav.=" ⋅$next_link";7116}else{7117$paging_nav.=" ⋅ next";7118}71197120 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);7121 git_print_header_div('commit', esc_html($co{'title'}),$hash);7122if($page==0&& !@commitlist) {7123print"<p>No match.</p>\n";7124}else{7125 git_search_grep_body(\@commitlist,0,99,$next_link);7126}7127}71287129if($searchtypeeq'pickaxe') {7130 git_print_page_nav('','',$hash,$co{'tree'},$hash);7131 git_print_header_div('commit', esc_html($co{'title'}),$hash);71327133print"<table class=\"pickaxe search\">\n";7134my$alternate=1;7135local$/="\n";7136open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,7137'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",7138($search_use_regexp?'--pickaxe-regex': ());7139undef%co;7140my@files;7141while(my$line= <$fd>) {7142chomp$line;7143next unless$line;71447145my%set= parse_difftree_raw_line($line);7146if(defined$set{'commit'}) {7147# finish previous commit7148if(%co) {7149print"</td>\n".7150"<td class=\"link\">".7151$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .7152" | ".7153$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");7154print"</td>\n".7155"</tr>\n";7156}71577158if($alternate) {7159print"<tr class=\"dark\">\n";7160}else{7161print"<tr class=\"light\">\n";7162}7163$alternate^=1;7164%co= parse_commit($set{'commit'});7165my$author= chop_and_escape_str($co{'author_name'},15,5);7166print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".7167"<td><i>$author</i></td>\n".7168"<td>".7169$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),7170-class=>"list subject"},7171 chop_and_escape_str($co{'title'},50) ."<br/>");7172}elsif(defined$set{'to_id'}) {7173next if($set{'to_id'} =~m/^0{40}$/);71747175print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},7176 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),7177-class=>"list"},7178"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .7179"<br/>\n";7180}7181}7182close$fd;71837184# finish last commit (warning: repetition!)7185if(%co) {7186print"</td>\n".7187"<td class=\"link\">".7188$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .7189" | ".7190$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");7191print"</td>\n".7192"</tr>\n";7193}71947195print"</table>\n";7196}71977198if($searchtypeeq'grep') {7199 git_print_page_nav('','',$hash,$co{'tree'},$hash);7200 git_print_header_div('commit', esc_html($co{'title'}),$hash);72017202print"<table class=\"grep_search\">\n";7203my$alternate=1;7204my$matches=0;7205local$/="\n";7206open my$fd,"-|", git_cmd(),'grep','-n',7207$search_use_regexp? ('-E','-i') :'-F',7208$searchtext,$co{'tree'};7209my$lastfile='';7210while(my$line= <$fd>) {7211chomp$line;7212my($file,$lno,$ltext,$binary);7213last if($matches++>1000);7214if($line=~/^Binary file (.+) matches$/) {7215$file=$1;7216$binary=1;7217}else{7218(undef,$file,$lno,$ltext) =split(/:/,$line,4);7219}7220if($filene$lastfile) {7221$lastfileand print"</td></tr>\n";7222if($alternate++) {7223print"<tr class=\"dark\">\n";7224}else{7225print"<tr class=\"light\">\n";7226}7227print"<td class=\"list\">".7228$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},7229 file_name=>"$file"),7230-class=>"list"}, esc_path($file));7231print"</td><td>\n";7232$lastfile=$file;7233}7234if($binary) {7235print"<div class=\"binary\">Binary file</div>\n";7236}else{7237$ltext= untabify($ltext);7238if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {7239$ltext= esc_html($1, -nbsp=>1);7240$ltext.='<span class="match">';7241$ltext.= esc_html($2, -nbsp=>1);7242$ltext.='</span>';7243$ltext.= esc_html($3, -nbsp=>1);7244}else{7245$ltext= esc_html($ltext, -nbsp=>1);7246}7247print"<div class=\"pre\">".7248$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},7249 file_name=>"$file").'#l'.$lno,7250-class=>"linenr"},sprintf('%4i',$lno))7251.' '.$ltext."</div>\n";7252}7253}7254if($lastfile) {7255print"</td></tr>\n";7256if($matches>1000) {7257print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";7258}7259}else{7260print"<div class=\"diff nodifferences\">No matches found</div>\n";7261}7262close$fd;72637264print"</table>\n";7265}7266 git_footer_html();7267}72687269sub git_search_help {7270 git_header_html();7271 git_print_page_nav('','',$hash,$hash,$hash);7272print<<EOT;7273<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without7274regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,7275the pattern entered is recognized as the POSIX extended7276<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case7277insensitive).</p>7278<dl>7279<dt><b>commit</b></dt>7280<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>7281EOT7282my$have_grep= gitweb_check_feature('grep');7283if($have_grep) {7284print<<EOT;7285<dt><b>grep</b></dt>7286<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing7287 a different one) are searched for the given pattern. On large trees, this search can take7288a while and put some strain on the server, so please use it with some consideration. Note that7289due to git-grep peculiarity, currently if regexp mode is turned off, the matches are7290case-sensitive.</dd>7291EOT7292}7293print<<EOT;7294<dt><b>author</b></dt>7295<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>7296<dt><b>committer</b></dt>7297<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>7298EOT7299my$have_pickaxe= gitweb_check_feature('pickaxe');7300if($have_pickaxe) {7301print<<EOT;7302<dt><b>pickaxe</b></dt>7303<dd>All commits that caused the string to appear or disappear from any file (changes that7304added, removed or "modified" the string) will be listed. This search can take a while and7305takes a lot of strain on the server, so please use it wisely. Note that since you may be7306interested even in changes just changing the case as well, this search is case sensitive.</dd>7307EOT7308}7309print"</dl>\n";7310 git_footer_html();7311}73127313sub git_shortlog {7314 git_log_generic('shortlog', \&git_shortlog_body,7315$hash,$hash_parent);7316}73177318## ......................................................................7319## feeds (RSS, Atom; OPML)73207321sub git_feed {7322my$format=shift||'atom';7323my$have_blame= gitweb_check_feature('blame');73247325# Atom: http://www.atomenabled.org/developers/syndication/7326# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ7327if($formatne'rss'&&$formatne'atom') {7328 die_error(400,"Unknown web feed format");7329}73307331# log/feed of current (HEAD) branch, log of given branch, history of file/directory7332my$head=$hash||'HEAD';7333my@commitlist= parse_commits($head,150,0,$file_name);73347335my%latest_commit;7336my%latest_date;7337my$content_type="application/$format+xml";7338if(defined$cgi->http('HTTP_ACCEPT') &&7339$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {7340# browser (feed reader) prefers text/xml7341$content_type='text/xml';7342}7343if(defined($commitlist[0])) {7344%latest_commit= %{$commitlist[0]};7345my$latest_epoch=$latest_commit{'committer_epoch'};7346%latest_date= parse_date($latest_epoch,$latest_commit{'comitter_tz'});7347my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7348if(defined$if_modified) {7349my$since;7350if(eval{require HTTP::Date;1; }) {7351$since= HTTP::Date::str2time($if_modified);7352}elsif(eval{require Time::ParseDate;1; }) {7353$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7354}7355if(defined$since&&$latest_epoch<=$since) {7356print$cgi->header(7357-type =>$content_type,7358-charset =>'utf-8',7359-last_modified =>$latest_date{'rfc2822'},7360-status =>'304 Not Modified');7361return;7362}7363}7364print$cgi->header(7365-type =>$content_type,7366-charset =>'utf-8',7367-last_modified =>$latest_date{'rfc2822'});7368}else{7369print$cgi->header(7370-type =>$content_type,7371-charset =>'utf-8');7372}73737374# Optimization: skip generating the body if client asks only7375# for Last-Modified date.7376return if($cgi->request_method()eq'HEAD');73777378# header variables7379my$title="$site_name-$project/$action";7380my$feed_type='log';7381if(defined$hash) {7382$title.=" - '$hash'";7383$feed_type='branch log';7384if(defined$file_name) {7385$title.=" ::$file_name";7386$feed_type='history';7387}7388}elsif(defined$file_name) {7389$title.=" -$file_name";7390$feed_type='history';7391}7392$title.="$feed_type";7393my$descr= git_get_project_description($project);7394if(defined$descr) {7395$descr= esc_html($descr);7396}else{7397$descr="$project".7398($formateq'rss'?'RSS':'Atom') .7399" feed";7400}7401my$owner= git_get_project_owner($project);7402$owner= esc_html($owner);74037404#header7405my$alt_url;7406if(defined$file_name) {7407$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);7408}elsif(defined$hash) {7409$alt_url= href(-full=>1, action=>"log", hash=>$hash);7410}else{7411$alt_url= href(-full=>1, action=>"summary");7412}7413print qq!<?xml version="1.0" encoding="utf-8"?>\n!;7414if($formateq'rss') {7415print<<XML;7416<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">7417<channel>7418XML7419print"<title>$title</title>\n".7420"<link>$alt_url</link>\n".7421"<description>$descr</description>\n".7422"<language>en</language>\n".7423# project owner is responsible for 'editorial' content7424"<managingEditor>$owner</managingEditor>\n";7425if(defined$logo||defined$favicon) {7426# prefer the logo to the favicon, since RSS7427# doesn't allow both7428my$img= esc_url($logo||$favicon);7429print"<image>\n".7430"<url>$img</url>\n".7431"<title>$title</title>\n".7432"<link>$alt_url</link>\n".7433"</image>\n";7434}7435if(%latest_date) {7436print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";7437print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";7438}7439print"<generator>gitweb v.$version/$git_version</generator>\n";7440}elsif($formateq'atom') {7441print<<XML;7442<feed xmlns="http://www.w3.org/2005/Atom">7443XML7444print"<title>$title</title>\n".7445"<subtitle>$descr</subtitle>\n".7446'<link rel="alternate" type="text/html" href="'.7447$alt_url.'" />'."\n".7448'<link rel="self" type="'.$content_type.'" href="'.7449$cgi->self_url() .'" />'."\n".7450"<id>". href(-full=>1) ."</id>\n".7451# use project owner for feed author7452"<author><name>$owner</name></author>\n";7453if(defined$favicon) {7454print"<icon>". esc_url($favicon) ."</icon>\n";7455}7456if(defined$logo) {7457# not twice as wide as tall: 72 x 27 pixels7458print"<logo>". esc_url($logo) ."</logo>\n";7459}7460if(!%latest_date) {7461# dummy date to keep the feed valid until commits trickle in:7462print"<updated>1970-01-01T00:00:00Z</updated>\n";7463}else{7464print"<updated>$latest_date{'iso-8601'}</updated>\n";7465}7466print"<generator version='$version/$git_version'>gitweb</generator>\n";7467}74687469# contents7470for(my$i=0;$i<=$#commitlist;$i++) {7471my%co= %{$commitlist[$i]};7472my$commit=$co{'id'};7473# we read 150, we always show 30 and the ones more recent than 48 hours7474if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {7475last;7476}7477my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});74787479# get list of changed files7480open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7481$co{'parent'} ||"--root",7482$co{'id'},"--", (defined$file_name?$file_name: ())7483ornext;7484my@difftree=map{chomp;$_} <$fd>;7485close$fd7486ornext;74877488# print element (entry, item)7489my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);7490if($formateq'rss') {7491print"<item>\n".7492"<title>". esc_html($co{'title'}) ."</title>\n".7493"<author>". esc_html($co{'author'}) ."</author>\n".7494"<pubDate>$cd{'rfc2822'}</pubDate>\n".7495"<guid isPermaLink=\"true\">$co_url</guid>\n".7496"<link>$co_url</link>\n".7497"<description>". esc_html($co{'title'}) ."</description>\n".7498"<content:encoded>".7499"<![CDATA[\n";7500}elsif($formateq'atom') {7501print"<entry>\n".7502"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".7503"<updated>$cd{'iso-8601'}</updated>\n".7504"<author>\n".7505" <name>". esc_html($co{'author_name'}) ."</name>\n";7506if($co{'author_email'}) {7507print" <email>". esc_html($co{'author_email'}) ."</email>\n";7508}7509print"</author>\n".7510# use committer for contributor7511"<contributor>\n".7512" <name>". esc_html($co{'committer_name'}) ."</name>\n";7513if($co{'committer_email'}) {7514print" <email>". esc_html($co{'committer_email'}) ."</email>\n";7515}7516print"</contributor>\n".7517"<published>$cd{'iso-8601'}</published>\n".7518"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".7519"<id>$co_url</id>\n".7520"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".7521"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";7522}7523my$comment=$co{'comment'};7524print"<pre>\n";7525foreachmy$line(@$comment) {7526$line= esc_html($line);7527print"$line\n";7528}7529print"</pre><ul>\n";7530foreachmy$difftree_line(@difftree) {7531my%difftree= parse_difftree_raw_line($difftree_line);7532next if!$difftree{'from_id'};75337534my$file=$difftree{'file'} ||$difftree{'to_file'};75357536print"<li>".7537"[".7538$cgi->a({-href => href(-full=>1, action=>"blobdiff",7539 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},7540 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},7541 file_name=>$file, file_parent=>$difftree{'from_file'}),7542-title =>"diff"},'D');7543if($have_blame) {7544print$cgi->a({-href => href(-full=>1, action=>"blame",7545 file_name=>$file, hash_base=>$commit),7546-title =>"blame"},'B');7547}7548# if this is not a feed of a file history7549if(!defined$file_name||$file_namene$file) {7550print$cgi->a({-href => href(-full=>1, action=>"history",7551 file_name=>$file, hash=>$commit),7552-title =>"history"},'H');7553}7554$file= esc_path($file);7555print"] ".7556"$file</li>\n";7557}7558if($formateq'rss') {7559print"</ul>]]>\n".7560"</content:encoded>\n".7561"</item>\n";7562}elsif($formateq'atom') {7563print"</ul>\n</div>\n".7564"</content>\n".7565"</entry>\n";7566}7567}75687569# end of feed7570if($formateq'rss') {7571print"</channel>\n</rss>\n";7572}elsif($formateq'atom') {7573print"</feed>\n";7574}7575}75767577sub git_rss {7578 git_feed('rss');7579}75807581sub git_atom {7582 git_feed('atom');7583}75847585sub git_opml {7586my@list= git_get_projects_list();7587if(!@list) {7588 die_error(404,"No projects found");7589}75907591print$cgi->header(7592-type =>'text/xml',7593-charset =>'utf-8',7594-content_disposition =>'inline; filename="opml.xml"');75957596print<<XML;7597<?xml version="1.0" encoding="utf-8"?>7598<opml version="1.0">7599<head>7600 <title>$site_nameOPML Export</title>7601</head>7602<body>7603<outline text="git RSS feeds">7604XML76057606foreachmy$pr(@list) {7607my%proj=%$pr;7608my$head= git_get_head_hash($proj{'path'});7609if(!defined$head) {7610next;7611}7612$git_dir="$projectroot/$proj{'path'}";7613my%co= parse_commit($head);7614if(!%co) {7615next;7616}76177618my$path= esc_html(chop_str($proj{'path'},25,5));7619my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);7620my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);7621print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";7622}7623print<<XML;7624</outline>7625</body>7626</opml>7627XML7628}