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# Note that you need to have 'search' feature enabled too. 332 333# To enable system wide have in $GITWEB_CONFIG 334# $feature{'grep'}{'default'} = [1]; 335# To have project specific config enable override in $GITWEB_CONFIG 336# $feature{'grep'}{'override'} = 1; 337# and in project config gitweb.grep = 0|1; 338'grep'=> { 339'sub'=>sub{ feature_bool('grep',@_) }, 340'override'=>0, 341'default'=> [1]}, 342 343# Enable the pickaxe search, which will list the commits that modified 344# a given string in a file. This can be practical and quite faster 345# alternative to 'blame', but still potentially CPU-intensive. 346# Note that you need to have 'search' feature enabled too. 347 348# To enable system wide have in $GITWEB_CONFIG 349# $feature{'pickaxe'}{'default'} = [1]; 350# To have project specific config enable override in $GITWEB_CONFIG 351# $feature{'pickaxe'}{'override'} = 1; 352# and in project config gitweb.pickaxe = 0|1; 353'pickaxe'=> { 354'sub'=>sub{ feature_bool('pickaxe',@_) }, 355'override'=>0, 356'default'=> [1]}, 357 358# Enable showing size of blobs in a 'tree' view, in a separate 359# column, similar to what 'ls -l' does. This cost a bit of IO. 360 361# To disable system wide have in $GITWEB_CONFIG 362# $feature{'show-sizes'}{'default'} = [0]; 363# To have project specific config enable override in $GITWEB_CONFIG 364# $feature{'show-sizes'}{'override'} = 1; 365# and in project config gitweb.showsizes = 0|1; 366'show-sizes'=> { 367'sub'=>sub{ feature_bool('showsizes',@_) }, 368'override'=>0, 369'default'=> [1]}, 370 371# Make gitweb use an alternative format of the URLs which can be 372# more readable and natural-looking: project name is embedded 373# directly in the path and the query string contains other 374# auxiliary information. All gitweb installations recognize 375# URL in either format; this configures in which formats gitweb 376# generates links. 377 378# To enable system wide have in $GITWEB_CONFIG 379# $feature{'pathinfo'}{'default'} = [1]; 380# Project specific override is not supported. 381 382# Note that you will need to change the default location of CSS, 383# favicon, logo and possibly other files to an absolute URL. Also, 384# if gitweb.cgi serves as your indexfile, you will need to force 385# $my_uri to contain the script name in your $GITWEB_CONFIG. 386'pathinfo'=> { 387'override'=>0, 388'default'=> [0]}, 389 390# Make gitweb consider projects in project root subdirectories 391# to be forks of existing projects. Given project $projname.git, 392# projects matching $projname/*.git will not be shown in the main 393# projects list, instead a '+' mark will be added to $projname 394# there and a 'forks' view will be enabled for the project, listing 395# all the forks. If project list is taken from a file, forks have 396# to be listed after the main project. 397 398# To enable system wide have in $GITWEB_CONFIG 399# $feature{'forks'}{'default'} = [1]; 400# Project specific override is not supported. 401'forks'=> { 402'override'=>0, 403'default'=> [0]}, 404 405# Insert custom links to the action bar of all project pages. 406# This enables you mainly to link to third-party scripts integrating 407# into gitweb; e.g. git-browser for graphical history representation 408# or custom web-based repository administration interface. 409 410# The 'default' value consists of a list of triplets in the form 411# (label, link, position) where position is the label after which 412# to insert the link and link is a format string where %n expands 413# to the project name, %f to the project path within the filesystem, 414# %h to the current hash (h gitweb parameter) and %b to the current 415# hash base (hb gitweb parameter); %% expands to %. 416 417# To enable system wide have in $GITWEB_CONFIG e.g. 418# $feature{'actions'}{'default'} = [('graphiclog', 419# '/git-browser/by-commit.html?r=%n', 'summary')]; 420# Project specific override is not supported. 421'actions'=> { 422'override'=>0, 423'default'=> []}, 424 425# Allow gitweb scan project content tags of project repository, 426# and display the popular Web 2.0-ish "tag cloud" near the projects 427# list. Note that this is something COMPLETELY different from the 428# normal Git tags. 429 430# gitweb by itself can show existing tags, but it does not handle 431# tagging itself; you need to do it externally, outside gitweb. 432# The format is described in git_get_project_ctags() subroutine. 433# You may want to install the HTML::TagCloud Perl module to get 434# a pretty tag cloud instead of just a list of tags. 435 436# To enable system wide have in $GITWEB_CONFIG 437# $feature{'ctags'}{'default'} = [1]; 438# Project specific override is not supported. 439 440# In the future whether ctags editing is enabled might depend 441# on the value, but using 1 should always mean no editing of ctags. 442'ctags'=> { 443'override'=>0, 444'default'=> [0]}, 445 446# The maximum number of patches in a patchset generated in patch 447# view. Set this to 0 or undef to disable patch view, or to a 448# negative number to remove any limit. 449 450# To disable system wide have in $GITWEB_CONFIG 451# $feature{'patches'}{'default'} = [0]; 452# To have project specific config enable override in $GITWEB_CONFIG 453# $feature{'patches'}{'override'} = 1; 454# and in project config gitweb.patches = 0|n; 455# where n is the maximum number of patches allowed in a patchset. 456'patches'=> { 457'sub'=> \&feature_patches, 458'override'=>0, 459'default'=> [16]}, 460 461# Avatar support. When this feature is enabled, views such as 462# shortlog or commit will display an avatar associated with 463# the email of the committer(s) and/or author(s). 464 465# Currently available providers are gravatar and picon. 466# If an unknown provider is specified, the feature is disabled. 467 468# Gravatar depends on Digest::MD5. 469# Picon currently relies on the indiana.edu database. 470 471# To enable system wide have in $GITWEB_CONFIG 472# $feature{'avatar'}{'default'} = ['<provider>']; 473# where <provider> is either gravatar or picon. 474# To have project specific config enable override in $GITWEB_CONFIG 475# $feature{'avatar'}{'override'} = 1; 476# and in project config gitweb.avatar = <provider>; 477'avatar'=> { 478'sub'=> \&feature_avatar, 479'override'=>0, 480'default'=> ['']}, 481 482# Enable displaying how much time and how many git commands 483# it took to generate and display page. Disabled by default. 484# Project specific override is not supported. 485'timed'=> { 486'override'=>0, 487'default'=> [0]}, 488 489# Enable turning some links into links to actions which require 490# JavaScript to run (like 'blame_incremental'). Not enabled by 491# default. Project specific override is currently not supported. 492'javascript-actions'=> { 493'override'=>0, 494'default'=> [0]}, 495 496# Enable and configure ability to change common timezone for dates 497# in gitweb output via JavaScript. Enabled by default. 498# Project specific override is not supported. 499'javascript-timezone'=> { 500'override'=>0, 501'default'=> [ 502'local',# default timezone: 'utc', 'local', or '(-|+)HHMM' format, 503# or undef to turn off this feature 504'gitweb_tz',# name of cookie where to store selected timezone 505'datetime',# CSS class used to mark up dates for manipulation 506]}, 507 508# Syntax highlighting support. This is based on Daniel Svensson's 509# and Sham Chukoury's work in gitweb-xmms2.git. 510# It requires the 'highlight' program present in $PATH, 511# and therefore is disabled by default. 512 513# To enable system wide have in $GITWEB_CONFIG 514# $feature{'highlight'}{'default'} = [1]; 515 516'highlight'=> { 517'sub'=>sub{ feature_bool('highlight',@_) }, 518'override'=>0, 519'default'=> [0]}, 520 521# Enable displaying of remote heads in the heads list 522 523# To enable system wide have in $GITWEB_CONFIG 524# $feature{'remote_heads'}{'default'} = [1]; 525# To have project specific config enable override in $GITWEB_CONFIG 526# $feature{'remote_heads'}{'override'} = 1; 527# and in project config gitweb.remote_heads = 0|1; 528'remote_heads'=> { 529'sub'=>sub{ feature_bool('remote_heads',@_) }, 530'override'=>0, 531'default'=> [0]}, 532); 533 534sub gitweb_get_feature { 535my($name) =@_; 536return unlessexists$feature{$name}; 537my($sub,$override,@defaults) = ( 538$feature{$name}{'sub'}, 539$feature{$name}{'override'}, 540@{$feature{$name}{'default'}}); 541# project specific override is possible only if we have project 542our$git_dir;# global variable, declared later 543if(!$override|| !defined$git_dir) { 544return@defaults; 545} 546if(!defined$sub) { 547warn"feature$nameis not overridable"; 548return@defaults; 549} 550return$sub->(@defaults); 551} 552 553# A wrapper to check if a given feature is enabled. 554# With this, you can say 555# 556# my $bool_feat = gitweb_check_feature('bool_feat'); 557# gitweb_check_feature('bool_feat') or somecode; 558# 559# instead of 560# 561# my ($bool_feat) = gitweb_get_feature('bool_feat'); 562# (gitweb_get_feature('bool_feat'))[0] or somecode; 563# 564sub gitweb_check_feature { 565return(gitweb_get_feature(@_))[0]; 566} 567 568 569sub feature_bool { 570my$key=shift; 571my($val) = git_get_project_config($key,'--bool'); 572 573if(!defined$val) { 574return($_[0]); 575}elsif($valeq'true') { 576return(1); 577}elsif($valeq'false') { 578return(0); 579} 580} 581 582sub feature_snapshot { 583my(@fmts) =@_; 584 585my($val) = git_get_project_config('snapshot'); 586 587if($val) { 588@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 589} 590 591return@fmts; 592} 593 594sub feature_patches { 595my@val= (git_get_project_config('patches','--int')); 596 597if(@val) { 598return@val; 599} 600 601return($_[0]); 602} 603 604sub feature_avatar { 605my@val= (git_get_project_config('avatar')); 606 607return@val?@val:@_; 608} 609 610# checking HEAD file with -e is fragile if the repository was 611# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 612# and then pruned. 613sub check_head_link { 614my($dir) =@_; 615my$headfile="$dir/HEAD"; 616return((-e $headfile) || 617(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 618} 619 620sub check_export_ok { 621my($dir) =@_; 622return(check_head_link($dir) && 623(!$export_ok|| -e "$dir/$export_ok") && 624(!$export_auth_hook||$export_auth_hook->($dir))); 625} 626 627# process alternate names for backward compatibility 628# filter out unsupported (unknown) snapshot formats 629sub filter_snapshot_fmts { 630my@fmts=@_; 631 632@fmts=map{ 633exists$known_snapshot_format_aliases{$_} ? 634$known_snapshot_format_aliases{$_} :$_}@fmts; 635@fmts=grep{ 636exists$known_snapshot_formats{$_} && 637!$known_snapshot_formats{$_}{'disabled'}}@fmts; 638} 639 640# If it is set to code reference, it is code that it is to be run once per 641# request, allowing updating configurations that change with each request, 642# while running other code in config file only once. 643# 644# Otherwise, if it is false then gitweb would process config file only once; 645# if it is true then gitweb config would be run for each request. 646our$per_request_config=1; 647 648# read and parse gitweb config file given by its parameter. 649# returns true on success, false on recoverable error, allowing 650# to chain this subroutine, using first file that exists. 651# dies on errors during parsing config file, as it is unrecoverable. 652sub read_config_file { 653my$filename=shift; 654return unlessdefined$filename; 655# die if there are errors parsing config file 656if(-e $filename) { 657do$filename; 658die$@if$@; 659return1; 660} 661return; 662} 663 664our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM); 665sub evaluate_gitweb_config { 666our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 667our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 668 669# use first config file that exists 670 read_config_file($GITWEB_CONFIG)or 671 read_config_file($GITWEB_CONFIG_SYSTEM); 672} 673 674# Get loadavg of system, to compare against $maxload. 675# Currently it requires '/proc/loadavg' present to get loadavg; 676# if it is not present it returns 0, which means no load checking. 677sub get_loadavg { 678if( -e '/proc/loadavg'){ 679open my$fd,'<','/proc/loadavg' 680orreturn0; 681my@load=split(/\s+/,scalar<$fd>); 682close$fd; 683 684# The first three columns measure CPU and IO utilization of the last one, 685# five, and 10 minute periods. The fourth column shows the number of 686# currently running processes and the total number of processes in the m/n 687# format. The last column displays the last process ID used. 688return$load[0] ||0; 689} 690# additional checks for load average should go here for things that don't export 691# /proc/loadavg 692 693return0; 694} 695 696# version of the core git binary 697our$git_version; 698sub evaluate_git_version { 699our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 700$number_of_git_cmds++; 701} 702 703sub check_loadavg { 704if(defined$maxload&& get_loadavg() >$maxload) { 705 die_error(503,"The load average on the server is too high"); 706} 707} 708 709# ====================================================================== 710# input validation and dispatch 711 712# input parameters can be collected from a variety of sources (presently, CGI 713# and PATH_INFO), so we define an %input_params hash that collects them all 714# together during validation: this allows subsequent uses (e.g. href()) to be 715# agnostic of the parameter origin 716 717our%input_params= (); 718 719# input parameters are stored with the long parameter name as key. This will 720# also be used in the href subroutine to convert parameters to their CGI 721# equivalent, and since the href() usage is the most frequent one, we store 722# the name -> CGI key mapping here, instead of the reverse. 723# 724# XXX: Warning: If you touch this, check the search form for updating, 725# too. 726 727our@cgi_param_mapping= ( 728 project =>"p", 729 action =>"a", 730 file_name =>"f", 731 file_parent =>"fp", 732 hash =>"h", 733 hash_parent =>"hp", 734 hash_base =>"hb", 735 hash_parent_base =>"hpb", 736 page =>"pg", 737 order =>"o", 738 searchtext =>"s", 739 searchtype =>"st", 740 snapshot_format =>"sf", 741 extra_options =>"opt", 742 search_use_regexp =>"sr", 743 ctag =>"by_tag", 744# this must be last entry (for manipulation from JavaScript) 745 javascript =>"js" 746); 747our%cgi_param_mapping=@cgi_param_mapping; 748 749# we will also need to know the possible actions, for validation 750our%actions= ( 751"blame"=> \&git_blame, 752"blame_incremental"=> \&git_blame_incremental, 753"blame_data"=> \&git_blame_data, 754"blobdiff"=> \&git_blobdiff, 755"blobdiff_plain"=> \&git_blobdiff_plain, 756"blob"=> \&git_blob, 757"blob_plain"=> \&git_blob_plain, 758"commitdiff"=> \&git_commitdiff, 759"commitdiff_plain"=> \&git_commitdiff_plain, 760"commit"=> \&git_commit, 761"forks"=> \&git_forks, 762"heads"=> \&git_heads, 763"history"=> \&git_history, 764"log"=> \&git_log, 765"patch"=> \&git_patch, 766"patches"=> \&git_patches, 767"remotes"=> \&git_remotes, 768"rss"=> \&git_rss, 769"atom"=> \&git_atom, 770"search"=> \&git_search, 771"search_help"=> \&git_search_help, 772"shortlog"=> \&git_shortlog, 773"summary"=> \&git_summary, 774"tag"=> \&git_tag, 775"tags"=> \&git_tags, 776"tree"=> \&git_tree, 777"snapshot"=> \&git_snapshot, 778"object"=> \&git_object, 779# those below don't need $project 780"opml"=> \&git_opml, 781"project_list"=> \&git_project_list, 782"project_index"=> \&git_project_index, 783); 784 785# finally, we have the hash of allowed extra_options for the commands that 786# allow them 787our%allowed_options= ( 788"--no-merges"=> [qw(rss atom log shortlog history)], 789); 790 791# fill %input_params with the CGI parameters. All values except for 'opt' 792# should be single values, but opt can be an array. We should probably 793# build an array of parameters that can be multi-valued, but since for the time 794# being it's only this one, we just single it out 795sub evaluate_query_params { 796our$cgi; 797 798while(my($name,$symbol) =each%cgi_param_mapping) { 799if($symboleq'opt') { 800$input_params{$name} = [$cgi->param($symbol) ]; 801}else{ 802$input_params{$name} =$cgi->param($symbol); 803} 804} 805} 806 807# now read PATH_INFO and update the parameter list for missing parameters 808sub evaluate_path_info { 809return ifdefined$input_params{'project'}; 810return if!$path_info; 811$path_info=~ s,^/+,,; 812return if!$path_info; 813 814# find which part of PATH_INFO is project 815my$project=$path_info; 816$project=~ s,/+$,,; 817while($project&& !check_head_link("$projectroot/$project")) { 818$project=~ s,/*[^/]*$,,; 819} 820return unless$project; 821$input_params{'project'} =$project; 822 823# do not change any parameters if an action is given using the query string 824return if$input_params{'action'}; 825$path_info=~ s,^\Q$project\E/*,,; 826 827# next, check if we have an action 828my$action=$path_info; 829$action=~ s,/.*$,,; 830if(exists$actions{$action}) { 831$path_info=~ s,^$action/*,,; 832$input_params{'action'} =$action; 833} 834 835# list of actions that want hash_base instead of hash, but can have no 836# pathname (f) parameter 837my@wants_base= ( 838'tree', 839'history', 840); 841 842# we want to catch, among others 843# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 844my($parentrefname,$parentpathname,$refname,$pathname) = 845($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/); 846 847# first, analyze the 'current' part 848if(defined$pathname) { 849# we got "branch:filename" or "branch:dir/" 850# we could use git_get_type(branch:pathname), but: 851# - it needs $git_dir 852# - it does a git() call 853# - the convention of terminating directories with a slash 854# makes it superfluous 855# - embedding the action in the PATH_INFO would make it even 856# more superfluous 857$pathname=~ s,^/+,,; 858if(!$pathname||substr($pathname, -1)eq"/") { 859$input_params{'action'} ||="tree"; 860$pathname=~ s,/$,,; 861}else{ 862# the default action depends on whether we had parent info 863# or not 864if($parentrefname) { 865$input_params{'action'} ||="blobdiff_plain"; 866}else{ 867$input_params{'action'} ||="blob_plain"; 868} 869} 870$input_params{'hash_base'} ||=$refname; 871$input_params{'file_name'} ||=$pathname; 872}elsif(defined$refname) { 873# we got "branch". In this case we have to choose if we have to 874# set hash or hash_base. 875# 876# Most of the actions without a pathname only want hash to be 877# set, except for the ones specified in @wants_base that want 878# hash_base instead. It should also be noted that hand-crafted 879# links having 'history' as an action and no pathname or hash 880# set will fail, but that happens regardless of PATH_INFO. 881if(defined$parentrefname) { 882# if there is parent let the default be 'shortlog' action 883# (for http://git.example.com/repo.git/A..B links); if there 884# is no parent, dispatch will detect type of object and set 885# action appropriately if required (if action is not set) 886$input_params{'action'} ||="shortlog"; 887} 888if($input_params{'action'} && 889grep{$_eq$input_params{'action'} }@wants_base) { 890$input_params{'hash_base'} ||=$refname; 891}else{ 892$input_params{'hash'} ||=$refname; 893} 894} 895 896# next, handle the 'parent' part, if present 897if(defined$parentrefname) { 898# a missing pathspec defaults to the 'current' filename, allowing e.g. 899# someproject/blobdiff/oldrev..newrev:/filename 900if($parentpathname) { 901$parentpathname=~ s,^/+,,; 902$parentpathname=~ s,/$,,; 903$input_params{'file_parent'} ||=$parentpathname; 904}else{ 905$input_params{'file_parent'} ||=$input_params{'file_name'}; 906} 907# we assume that hash_parent_base is wanted if a path was specified, 908# or if the action wants hash_base instead of hash 909if(defined$input_params{'file_parent'} || 910grep{$_eq$input_params{'action'} }@wants_base) { 911$input_params{'hash_parent_base'} ||=$parentrefname; 912}else{ 913$input_params{'hash_parent'} ||=$parentrefname; 914} 915} 916 917# for the snapshot action, we allow URLs in the form 918# $project/snapshot/$hash.ext 919# where .ext determines the snapshot and gets removed from the 920# passed $refname to provide the $hash. 921# 922# To be able to tell that $refname includes the format extension, we 923# require the following two conditions to be satisfied: 924# - the hash input parameter MUST have been set from the $refname part 925# of the URL (i.e. they must be equal) 926# - the snapshot format MUST NOT have been defined already (e.g. from 927# CGI parameter sf) 928# It's also useless to try any matching unless $refname has a dot, 929# so we check for that too 930if(defined$input_params{'action'} && 931$input_params{'action'}eq'snapshot'&& 932defined$refname&&index($refname,'.') != -1&& 933$refnameeq$input_params{'hash'} && 934!defined$input_params{'snapshot_format'}) { 935# We loop over the known snapshot formats, checking for 936# extensions. Allowed extensions are both the defined suffix 937# (which includes the initial dot already) and the snapshot 938# format key itself, with a prepended dot 939while(my($fmt,$opt) =each%known_snapshot_formats) { 940my$hash=$refname; 941unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 942next; 943} 944my$sfx=$1; 945# a valid suffix was found, so set the snapshot format 946# and reset the hash parameter 947$input_params{'snapshot_format'} =$fmt; 948$input_params{'hash'} =$hash; 949# we also set the format suffix to the one requested 950# in the URL: this way a request for e.g. .tgz returns 951# a .tgz instead of a .tar.gz 952$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 953last; 954} 955} 956} 957 958our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 959$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 960$searchtext,$search_regexp); 961sub evaluate_and_validate_params { 962our$action=$input_params{'action'}; 963if(defined$action) { 964if(!validate_action($action)) { 965 die_error(400,"Invalid action parameter"); 966} 967} 968 969# parameters which are pathnames 970our$project=$input_params{'project'}; 971if(defined$project) { 972if(!validate_project($project)) { 973undef$project; 974 die_error(404,"No such project"); 975} 976} 977 978our$file_name=$input_params{'file_name'}; 979if(defined$file_name) { 980if(!validate_pathname($file_name)) { 981 die_error(400,"Invalid file parameter"); 982} 983} 984 985our$file_parent=$input_params{'file_parent'}; 986if(defined$file_parent) { 987if(!validate_pathname($file_parent)) { 988 die_error(400,"Invalid file parent parameter"); 989} 990} 991 992# parameters which are refnames 993our$hash=$input_params{'hash'}; 994if(defined$hash) { 995if(!validate_refname($hash)) { 996 die_error(400,"Invalid hash parameter"); 997} 998} 9991000our$hash_parent=$input_params{'hash_parent'};1001if(defined$hash_parent) {1002if(!validate_refname($hash_parent)) {1003 die_error(400,"Invalid hash parent parameter");1004}1005}10061007our$hash_base=$input_params{'hash_base'};1008if(defined$hash_base) {1009if(!validate_refname($hash_base)) {1010 die_error(400,"Invalid hash base parameter");1011}1012}10131014our@extra_options= @{$input_params{'extra_options'}};1015# @extra_options is always defined, since it can only be (currently) set from1016# CGI, and $cgi->param() returns the empty array in array context if the param1017# is not set1018foreachmy$opt(@extra_options) {1019if(not exists$allowed_options{$opt}) {1020 die_error(400,"Invalid option parameter");1021}1022if(not grep(/^$action$/, @{$allowed_options{$opt}})) {1023 die_error(400,"Invalid option parameter for this action");1024}1025}10261027our$hash_parent_base=$input_params{'hash_parent_base'};1028if(defined$hash_parent_base) {1029if(!validate_refname($hash_parent_base)) {1030 die_error(400,"Invalid hash parent base parameter");1031}1032}10331034# other parameters1035our$page=$input_params{'page'};1036if(defined$page) {1037if($page=~m/[^0-9]/) {1038 die_error(400,"Invalid page parameter");1039}1040}10411042our$searchtype=$input_params{'searchtype'};1043if(defined$searchtype) {1044if($searchtype=~m/[^a-z]/) {1045 die_error(400,"Invalid searchtype parameter");1046}1047}10481049our$search_use_regexp=$input_params{'search_use_regexp'};10501051our$searchtext=$input_params{'searchtext'};1052our$search_regexp;1053if(defined$searchtext) {1054if(length($searchtext) <2) {1055 die_error(403,"At least two characters are required for search parameter");1056}1057$search_regexp=$search_use_regexp?$searchtext:quotemeta$searchtext;1058}1059}10601061# path to the current git repository1062our$git_dir;1063sub evaluate_git_dir {1064our$git_dir="$projectroot/$project"if$project;1065}10661067our(@snapshot_fmts,$git_avatar);1068sub configure_gitweb_features {1069# list of supported snapshot formats1070our@snapshot_fmts= gitweb_get_feature('snapshot');1071@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);10721073# check that the avatar feature is set to a known provider name,1074# and for each provider check if the dependencies are satisfied.1075# if the provider name is invalid or the dependencies are not met,1076# reset $git_avatar to the empty string.1077our($git_avatar) = gitweb_get_feature('avatar');1078if($git_avatareq'gravatar') {1079$git_avatar=''unless(eval{require Digest::MD5;1; });1080}elsif($git_avatareq'picon') {1081# no dependencies1082}else{1083$git_avatar='';1084}1085}10861087# custom error handler: 'die <message>' is Internal Server Error1088sub handle_errors_html {1089my$msg=shift;# it is already HTML escaped10901091# to avoid infinite loop where error occurs in die_error,1092# change handler to default handler, disabling handle_errors_html1093 set_message("Error occured when inside die_error:\n$msg");10941095# you cannot jump out of die_error when called as error handler;1096# the subroutine set via CGI::Carp::set_message is called _after_1097# HTTP headers are already written, so it cannot write them itself1098 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1099}1100set_message(\&handle_errors_html);11011102# dispatch1103sub dispatch {1104if(!defined$action) {1105if(defined$hash) {1106$action= git_get_type($hash);1107}elsif(defined$hash_base&&defined$file_name) {1108$action= git_get_type("$hash_base:$file_name");1109}elsif(defined$project) {1110$action='summary';1111}else{1112$action='project_list';1113}1114}1115if(!defined($actions{$action})) {1116 die_error(400,"Unknown action");1117}1118if($action!~m/^(?:opml|project_list|project_index)$/&&1119!$project) {1120 die_error(400,"Project needed");1121}1122$actions{$action}->();1123}11241125sub reset_timer {1126our$t0= [ gettimeofday() ]1127ifdefined$t0;1128our$number_of_git_cmds=0;1129}11301131our$first_request=1;1132sub run_request {1133 reset_timer();11341135 evaluate_uri();1136if($first_request) {1137 evaluate_gitweb_config();1138 evaluate_git_version();1139}1140if($per_request_config) {1141if(ref($per_request_config)eq'CODE') {1142$per_request_config->();1143}elsif(!$first_request) {1144 evaluate_gitweb_config();1145}1146}1147 check_loadavg();11481149# $projectroot and $projects_list might be set in gitweb config file1150$projects_list||=$projectroot;11511152 evaluate_query_params();1153 evaluate_path_info();1154 evaluate_and_validate_params();1155 evaluate_git_dir();11561157 configure_gitweb_features();11581159 dispatch();1160}11611162our$is_last_request=sub{1};1163our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1164our$CGI='CGI';1165our$cgi;1166sub configure_as_fcgi {1167require CGI::Fast;1168our$CGI='CGI::Fast';11691170my$request_number=0;1171# let each child service 100 requests1172our$is_last_request=sub{ ++$request_number>100};1173}1174sub evaluate_argv {1175my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1176 configure_as_fcgi()1177if$script_name=~/\.fcgi$/;11781179return unless(@ARGV);11801181require Getopt::Long;1182 Getopt::Long::GetOptions(1183'fastcgi|fcgi|f'=> \&configure_as_fcgi,1184'nproc|n=i'=>sub{1185my($arg,$val) =@_;1186return unlesseval{require FCGI::ProcManager;1; };1187my$proc_manager= FCGI::ProcManager->new({1188 n_processes =>$val,1189});1190our$pre_listen_hook=sub{$proc_manager->pm_manage() };1191our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1192our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1193},1194);1195}11961197sub run {1198 evaluate_argv();11991200$first_request=1;1201$pre_listen_hook->()1202if$pre_listen_hook;12031204 REQUEST:1205while($cgi=$CGI->new()) {1206$pre_dispatch_hook->()1207if$pre_dispatch_hook;12081209 run_request();12101211$post_dispatch_hook->()1212if$post_dispatch_hook;1213$first_request=0;12141215last REQUEST if($is_last_request->());1216}12171218 DONE_GITWEB:12191;1220}12211222run();12231224if(defined caller) {1225# wrapped in a subroutine processing requests,1226# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1227return;1228}else{1229# pure CGI script, serving single request1230exit;1231}12321233## ======================================================================1234## action links12351236# possible values of extra options1237# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1238# -replay => 1 - start from a current view (replay with modifications)1239# -path_info => 0|1 - don't use/use path_info URL (if possible)1240# -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone1241sub href {1242my%params=@_;1243# default is to use -absolute url() i.e. $my_uri1244my$href=$params{-full} ?$my_url:$my_uri;12451246# implicit -replay, must be first of implicit params1247$params{-replay} =1if(keys%params==1&&$params{-anchor});12481249$params{'project'} =$projectunlessexists$params{'project'};12501251if($params{-replay}) {1252while(my($name,$symbol) =each%cgi_param_mapping) {1253if(!exists$params{$name}) {1254$params{$name} =$input_params{$name};1255}1256}1257}12581259my$use_pathinfo= gitweb_check_feature('pathinfo');1260if(defined$params{'project'} &&1261(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1262# try to put as many parameters as possible in PATH_INFO:1263# - project name1264# - action1265# - hash_parent or hash_parent_base:/file_parent1266# - hash or hash_base:/filename1267# - the snapshot_format as an appropriate suffix12681269# When the script is the root DirectoryIndex for the domain,1270# $href here would be something like http://gitweb.example.com/1271# Thus, we strip any trailing / from $href, to spare us double1272# slashes in the final URL1273$href=~ s,/$,,;12741275# Then add the project name, if present1276$href.="/".esc_path_info($params{'project'});1277delete$params{'project'};12781279# since we destructively absorb parameters, we keep this1280# boolean that remembers if we're handling a snapshot1281my$is_snapshot=$params{'action'}eq'snapshot';12821283# Summary just uses the project path URL, any other action is1284# added to the URL1285if(defined$params{'action'}) {1286$href.="/".esc_path_info($params{'action'})1287unless$params{'action'}eq'summary';1288delete$params{'action'};1289}12901291# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1292# stripping nonexistent or useless pieces1293$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1294||$params{'hash_parent'} ||$params{'hash'});1295if(defined$params{'hash_base'}) {1296if(defined$params{'hash_parent_base'}) {1297$href.= esc_path_info($params{'hash_parent_base'});1298# skip the file_parent if it's the same as the file_name1299if(defined$params{'file_parent'}) {1300if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1301delete$params{'file_parent'};1302}elsif($params{'file_parent'} !~/\.\./) {1303$href.=":/".esc_path_info($params{'file_parent'});1304delete$params{'file_parent'};1305}1306}1307$href.="..";1308delete$params{'hash_parent'};1309delete$params{'hash_parent_base'};1310}elsif(defined$params{'hash_parent'}) {1311$href.= esc_path_info($params{'hash_parent'})."..";1312delete$params{'hash_parent'};1313}13141315$href.= esc_path_info($params{'hash_base'});1316if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1317$href.=":/".esc_path_info($params{'file_name'});1318delete$params{'file_name'};1319}1320delete$params{'hash'};1321delete$params{'hash_base'};1322}elsif(defined$params{'hash'}) {1323$href.= esc_path_info($params{'hash'});1324delete$params{'hash'};1325}13261327# If the action was a snapshot, we can absorb the1328# snapshot_format parameter too1329if($is_snapshot) {1330my$fmt=$params{'snapshot_format'};1331# snapshot_format should always be defined when href()1332# is called, but just in case some code forgets, we1333# fall back to the default1334$fmt||=$snapshot_fmts[0];1335$href.=$known_snapshot_formats{$fmt}{'suffix'};1336delete$params{'snapshot_format'};1337}1338}13391340# now encode the parameters explicitly1341my@result= ();1342for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1343my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1344if(defined$params{$name}) {1345if(ref($params{$name})eq"ARRAY") {1346foreachmy$par(@{$params{$name}}) {1347push@result,$symbol."=". esc_param($par);1348}1349}else{1350push@result,$symbol."=". esc_param($params{$name});1351}1352}1353}1354$href.="?".join(';',@result)ifscalar@result;13551356# final transformation: trailing spaces must be escaped (URI-encoded)1357$href=~s/(\s+)$/CGI::escape($1)/e;13581359if($params{-anchor}) {1360$href.="#".esc_param($params{-anchor});1361}13621363return$href;1364}136513661367## ======================================================================1368## validation, quoting/unquoting and escaping13691370sub validate_action {1371my$input=shift||returnundef;1372returnundefunlessexists$actions{$input};1373return$input;1374}13751376sub validate_project {1377my$input=shift||returnundef;1378if(!validate_pathname($input) ||1379!(-d "$projectroot/$input") ||1380!check_export_ok("$projectroot/$input") ||1381($strict_export&& !project_in_list($input))) {1382returnundef;1383}else{1384return$input;1385}1386}13871388sub validate_pathname {1389my$input=shift||returnundef;13901391# no '.' or '..' as elements of path, i.e. no '.' nor '..'1392# at the beginning, at the end, and between slashes.1393# also this catches doubled slashes1394if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1395returnundef;1396}1397# no null characters1398if($input=~m!\0!) {1399returnundef;1400}1401return$input;1402}14031404sub validate_refname {1405my$input=shift||returnundef;14061407# textual hashes are O.K.1408if($input=~m/^[0-9a-fA-F]{40}$/) {1409return$input;1410}1411# it must be correct pathname1412$input= validate_pathname($input)1413orreturnundef;1414# restrictions on ref name according to git-check-ref-format1415if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1416returnundef;1417}1418return$input;1419}14201421# decode sequences of octets in utf8 into Perl's internal form,1422# which is utf-8 with utf8 flag set if needed. gitweb writes out1423# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1424sub to_utf8 {1425my$str=shift;1426returnundefunlessdefined$str;1427if(utf8::valid($str)) {1428 utf8::decode($str);1429return$str;1430}else{1431return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1432}1433}14341435# quote unsafe chars, but keep the slash, even when it's not1436# correct, but quoted slashes look too horrible in bookmarks1437sub esc_param {1438my$str=shift;1439returnundefunlessdefined$str;1440$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1441$str=~s/ /\+/g;1442return$str;1443}14441445# the quoting rules for path_info fragment are slightly different1446sub esc_path_info {1447my$str=shift;1448returnundefunlessdefined$str;14491450# path_info doesn't treat '+' as space (specially), but '?' must be escaped1451$str=~s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;14521453return$str;1454}14551456# quote unsafe chars in whole URL, so some characters cannot be quoted1457sub esc_url {1458my$str=shift;1459returnundefunlessdefined$str;1460$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1461$str=~s/ /\+/g;1462return$str;1463}14641465# quote unsafe characters in HTML attributes1466sub esc_attr {14671468# for XHTML conformance escaping '"' to '"' is not enough1469return esc_html(@_);1470}14711472# replace invalid utf8 character with SUBSTITUTION sequence1473sub esc_html {1474my$str=shift;1475my%opts=@_;14761477returnundefunlessdefined$str;14781479$str= to_utf8($str);1480$str=$cgi->escapeHTML($str);1481if($opts{'-nbsp'}) {1482$str=~s/ / /g;1483}1484$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1485return$str;1486}14871488# quote control characters and escape filename to HTML1489sub esc_path {1490my$str=shift;1491my%opts=@_;14921493returnundefunlessdefined$str;14941495$str= to_utf8($str);1496$str=$cgi->escapeHTML($str);1497if($opts{'-nbsp'}) {1498$str=~s/ / /g;1499}1500$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1501return$str;1502}15031504# Make control characters "printable", using character escape codes (CEC)1505sub quot_cec {1506my$cntrl=shift;1507my%opts=@_;1508my%es= (# character escape codes, aka escape sequences1509"\t"=>'\t',# tab (HT)1510"\n"=>'\n',# line feed (LF)1511"\r"=>'\r',# carrige return (CR)1512"\f"=>'\f',# form feed (FF)1513"\b"=>'\b',# backspace (BS)1514"\a"=>'\a',# alarm (bell) (BEL)1515"\e"=>'\e',# escape (ESC)1516"\013"=>'\v',# vertical tab (VT)1517"\000"=>'\0',# nul character (NUL)1518);1519my$chr= ( (exists$es{$cntrl})1520?$es{$cntrl}1521:sprintf('\%2x',ord($cntrl)) );1522if($opts{-nohtml}) {1523return$chr;1524}else{1525return"<span class=\"cntrl\">$chr</span>";1526}1527}15281529# Alternatively use unicode control pictures codepoints,1530# Unicode "printable representation" (PR)1531sub quot_upr {1532my$cntrl=shift;1533my%opts=@_;15341535my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1536if($opts{-nohtml}) {1537return$chr;1538}else{1539return"<span class=\"cntrl\">$chr</span>";1540}1541}15421543# git may return quoted and escaped filenames1544sub unquote {1545my$str=shift;15461547sub unq {1548my$seq=shift;1549my%es= (# character escape codes, aka escape sequences1550't'=>"\t",# tab (HT, TAB)1551'n'=>"\n",# newline (NL)1552'r'=>"\r",# return (CR)1553'f'=>"\f",# form feed (FF)1554'b'=>"\b",# backspace (BS)1555'a'=>"\a",# alarm (bell) (BEL)1556'e'=>"\e",# escape (ESC)1557'v'=>"\013",# vertical tab (VT)1558);15591560if($seq=~m/^[0-7]{1,3}$/) {1561# octal char sequence1562returnchr(oct($seq));1563}elsif(exists$es{$seq}) {1564# C escape sequence, aka character escape code1565return$es{$seq};1566}1567# quoted ordinary character1568return$seq;1569}15701571if($str=~m/^"(.*)"$/) {1572# needs unquoting1573$str=$1;1574$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1575}1576return$str;1577}15781579# escape tabs (convert tabs to spaces)1580sub untabify {1581my$line=shift;15821583while((my$pos=index($line,"\t")) != -1) {1584if(my$count= (8- ($pos%8))) {1585my$spaces=' ' x $count;1586$line=~s/\t/$spaces/;1587}1588}15891590return$line;1591}15921593sub project_in_list {1594my$project=shift;1595my@list= git_get_projects_list();1596return@list&&scalar(grep{$_->{'path'}eq$project}@list);1597}15981599## ----------------------------------------------------------------------1600## HTML aware string manipulation16011602# Try to chop given string on a word boundary between position1603# $len and $len+$add_len. If there is no word boundary there,1604# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1605# (marking chopped part) would be longer than given string.1606sub chop_str {1607my$str=shift;1608my$len=shift;1609my$add_len=shift||10;1610my$where=shift||'right';# 'left' | 'center' | 'right'16111612# Make sure perl knows it is utf8 encoded so we don't1613# cut in the middle of a utf8 multibyte char.1614$str= to_utf8($str);16151616# allow only $len chars, but don't cut a word if it would fit in $add_len1617# if it doesn't fit, cut it if it's still longer than the dots we would add1618# remove chopped character entities entirely16191620# when chopping in the middle, distribute $len into left and right part1621# return early if chopping wouldn't make string shorter1622if($whereeq'center') {1623return$strif($len+5>=length($str));# filler is length 51624$len=int($len/2);1625}else{1626return$strif($len+4>=length($str));# filler is length 41627}16281629# regexps: ending and beginning with word part up to $add_len1630my$endre=qr/.{$len}\w{0,$add_len}/;1631my$begre=qr/\w{0,$add_len}.{$len}/;16321633if($whereeq'left') {1634$str=~m/^(.*?)($begre)$/;1635my($lead,$body) = ($1,$2);1636if(length($lead) >4) {1637$lead=" ...";1638}1639return"$lead$body";16401641}elsif($whereeq'center') {1642$str=~m/^($endre)(.*)$/;1643my($left,$str) = ($1,$2);1644$str=~m/^(.*?)($begre)$/;1645my($mid,$right) = ($1,$2);1646if(length($mid) >5) {1647$mid=" ... ";1648}1649return"$left$mid$right";16501651}else{1652$str=~m/^($endre)(.*)$/;1653my$body=$1;1654my$tail=$2;1655if(length($tail) >4) {1656$tail="... ";1657}1658return"$body$tail";1659}1660}16611662# takes the same arguments as chop_str, but also wraps a <span> around the1663# result with a title attribute if it does get chopped. Additionally, the1664# string is HTML-escaped.1665sub chop_and_escape_str {1666my($str) =@_;16671668my$chopped= chop_str(@_);1669if($choppedeq$str) {1670return esc_html($chopped);1671}else{1672$str=~s/[[:cntrl:]]/?/g;1673return$cgi->span({-title=>$str}, esc_html($chopped));1674}1675}16761677## ----------------------------------------------------------------------1678## functions returning short strings16791680# CSS class for given age value (in seconds)1681sub age_class {1682my$age=shift;16831684if(!defined$age) {1685return"noage";1686}elsif($age<60*60*2) {1687return"age0";1688}elsif($age<60*60*24*2) {1689return"age1";1690}else{1691return"age2";1692}1693}16941695# convert age in seconds to "nn units ago" string1696sub age_string {1697my$age=shift;1698my$age_str;16991700if($age>60*60*24*365*2) {1701$age_str= (int$age/60/60/24/365);1702$age_str.=" years ago";1703}elsif($age>60*60*24*(365/12)*2) {1704$age_str=int$age/60/60/24/(365/12);1705$age_str.=" months ago";1706}elsif($age>60*60*24*7*2) {1707$age_str=int$age/60/60/24/7;1708$age_str.=" weeks ago";1709}elsif($age>60*60*24*2) {1710$age_str=int$age/60/60/24;1711$age_str.=" days ago";1712}elsif($age>60*60*2) {1713$age_str=int$age/60/60;1714$age_str.=" hours ago";1715}elsif($age>60*2) {1716$age_str=int$age/60;1717$age_str.=" min ago";1718}elsif($age>2) {1719$age_str=int$age;1720$age_str.=" sec ago";1721}else{1722$age_str.=" right now";1723}1724return$age_str;1725}17261727useconstant{1728 S_IFINVALID =>0030000,1729 S_IFGITLINK =>0160000,1730};17311732# submodule/subproject, a commit object reference1733sub S_ISGITLINK {1734my$mode=shift;17351736return(($mode& S_IFMT) == S_IFGITLINK)1737}17381739# convert file mode in octal to symbolic file mode string1740sub mode_str {1741my$mode=oct shift;17421743if(S_ISGITLINK($mode)) {1744return'm---------';1745}elsif(S_ISDIR($mode& S_IFMT)) {1746return'drwxr-xr-x';1747}elsif(S_ISLNK($mode)) {1748return'lrwxrwxrwx';1749}elsif(S_ISREG($mode)) {1750# git cares only about the executable bit1751if($mode& S_IXUSR) {1752return'-rwxr-xr-x';1753}else{1754return'-rw-r--r--';1755};1756}else{1757return'----------';1758}1759}17601761# convert file mode in octal to file type string1762sub file_type {1763my$mode=shift;17641765if($mode!~m/^[0-7]+$/) {1766return$mode;1767}else{1768$mode=oct$mode;1769}17701771if(S_ISGITLINK($mode)) {1772return"submodule";1773}elsif(S_ISDIR($mode& S_IFMT)) {1774return"directory";1775}elsif(S_ISLNK($mode)) {1776return"symlink";1777}elsif(S_ISREG($mode)) {1778return"file";1779}else{1780return"unknown";1781}1782}17831784# convert file mode in octal to file type description string1785sub file_type_long {1786my$mode=shift;17871788if($mode!~m/^[0-7]+$/) {1789return$mode;1790}else{1791$mode=oct$mode;1792}17931794if(S_ISGITLINK($mode)) {1795return"submodule";1796}elsif(S_ISDIR($mode& S_IFMT)) {1797return"directory";1798}elsif(S_ISLNK($mode)) {1799return"symlink";1800}elsif(S_ISREG($mode)) {1801if($mode& S_IXUSR) {1802return"executable";1803}else{1804return"file";1805};1806}else{1807return"unknown";1808}1809}181018111812## ----------------------------------------------------------------------1813## functions returning short HTML fragments, or transforming HTML fragments1814## which don't belong to other sections18151816# format line of commit message.1817sub format_log_line_html {1818my$line=shift;18191820$line= esc_html($line, -nbsp=>1);1821$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1822$cgi->a({-href => href(action=>"object", hash=>$1),1823-class=>"text"},$1);1824}eg;18251826return$line;1827}18281829# format marker of refs pointing to given object18301831# the destination action is chosen based on object type and current context:1832# - for annotated tags, we choose the tag view unless it's the current view1833# already, in which case we go to shortlog view1834# - for other refs, we keep the current view if we're in history, shortlog or1835# log view, and select shortlog otherwise1836sub format_ref_marker {1837my($refs,$id) =@_;1838my$markers='';18391840if(defined$refs->{$id}) {1841foreachmy$ref(@{$refs->{$id}}) {1842# this code exploits the fact that non-lightweight tags are the1843# only indirect objects, and that they are the only objects for which1844# we want to use tag instead of shortlog as action1845my($type,$name) =qw();1846my$indirect= ($ref=~s/\^\{\}$//);1847# e.g. tags/v2.6.11 or heads/next1848if($ref=~m!^(.*?)s?/(.*)$!) {1849$type=$1;1850$name=$2;1851}else{1852$type="ref";1853$name=$ref;1854}18551856my$class=$type;1857$class.=" indirect"if$indirect;18581859my$dest_action="shortlog";18601861if($indirect) {1862$dest_action="tag"unless$actioneq"tag";1863}elsif($action=~/^(history|(short)?log)$/) {1864$dest_action=$action;1865}18661867my$dest="";1868$dest.="refs/"unless$ref=~ m!^refs/!;1869$dest.=$ref;18701871my$link=$cgi->a({1872-href => href(1873 action=>$dest_action,1874 hash=>$dest1875)},$name);18761877$markers.=" <span class=\"".esc_attr($class)."\"title=\"".esc_attr($ref)."\">".1878$link."</span>";1879}1880}18811882if($markers) {1883return' <span class="refs">'.$markers.'</span>';1884}else{1885return"";1886}1887}18881889# format, perhaps shortened and with markers, title line1890sub format_subject_html {1891my($long,$short,$href,$extra) =@_;1892$extra=''unlessdefined($extra);18931894if(length($short) <length($long)) {1895$long=~s/[[:cntrl:]]/?/g;1896return$cgi->a({-href =>$href, -class=>"list subject",1897-title => to_utf8($long)},1898 esc_html($short)) .$extra;1899}else{1900return$cgi->a({-href =>$href, -class=>"list subject"},1901 esc_html($long)) .$extra;1902}1903}19041905# Rather than recomputing the url for an email multiple times, we cache it1906# after the first hit. This gives a visible benefit in views where the avatar1907# for the same email is used repeatedly (e.g. shortlog).1908# The cache is shared by all avatar engines (currently gravatar only), which1909# are free to use it as preferred. Since only one avatar engine is used for any1910# given page, there's no risk for cache conflicts.1911our%avatar_cache= ();19121913# Compute the picon url for a given email, by using the picon search service over at1914# http://www.cs.indiana.edu/picons/search.html1915sub picon_url {1916my$email=lc shift;1917if(!$avatar_cache{$email}) {1918my($user,$domain) =split('@',$email);1919$avatar_cache{$email} =1920"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1921"$domain/$user/".1922"users+domains+unknown/up/single";1923}1924return$avatar_cache{$email};1925}19261927# Compute the gravatar url for a given email, if it's not in the cache already.1928# Gravatar stores only the part of the URL before the size, since that's the1929# one computationally more expensive. This also allows reuse of the cache for1930# different sizes (for this particular engine).1931sub gravatar_url {1932my$email=lc shift;1933my$size=shift;1934$avatar_cache{$email} ||=1935"http://www.gravatar.com/avatar/".1936 Digest::MD5::md5_hex($email) ."?s=";1937return$avatar_cache{$email} .$size;1938}19391940# Insert an avatar for the given $email at the given $size if the feature1941# is enabled.1942sub git_get_avatar {1943my($email,%opts) =@_;1944my$pre_white= ($opts{-pad_before} ?" ":"");1945my$post_white= ($opts{-pad_after} ?" ":"");1946$opts{-size} ||='default';1947my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1948my$url="";1949if($git_avatareq'gravatar') {1950$url= gravatar_url($email,$size);1951}elsif($git_avatareq'picon') {1952$url= picon_url($email);1953}1954# Other providers can be added by extending the if chain, defining $url1955# as needed. If no variant puts something in $url, we assume avatars1956# are completely disabled/unavailable.1957if($url) {1958return$pre_white.1959"<img width=\"$size\"".1960"class=\"avatar\"".1961"src=\"".esc_url($url)."\"".1962"alt=\"\"".1963"/>".$post_white;1964}else{1965return"";1966}1967}19681969sub format_search_author {1970my($author,$searchtype,$displaytext) =@_;1971my$have_search= gitweb_check_feature('search');19721973if($have_search) {1974my$performed="";1975if($searchtypeeq'author') {1976$performed="authored";1977}elsif($searchtypeeq'committer') {1978$performed="committed";1979}19801981return$cgi->a({-href => href(action=>"search", hash=>$hash,1982 searchtext=>$author,1983 searchtype=>$searchtype),class=>"list",1984 title=>"Search for commits$performedby$author"},1985$displaytext);19861987}else{1988return$displaytext;1989}1990}19911992# format the author name of the given commit with the given tag1993# the author name is chopped and escaped according to the other1994# optional parameters (see chop_str).1995sub format_author_html {1996my$tag=shift;1997my$co=shift;1998my$author= chop_and_escape_str($co->{'author_name'},@_);1999return"<$tagclass=\"author\">".2000 format_search_author($co->{'author_name'},"author",2001 git_get_avatar($co->{'author_email'}, -pad_after =>1) .2002$author) .2003"</$tag>";2004}20052006# format git diff header line, i.e. "diff --(git|combined|cc) ..."2007sub format_git_diff_header_line {2008my$line=shift;2009my$diffinfo=shift;2010my($from,$to) =@_;20112012if($diffinfo->{'nparents'}) {2013# combined diff2014$line=~s!^(diff (.*?) )"?.*$!$1!;2015if($to->{'href'}) {2016$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2017 esc_path($to->{'file'}));2018}else{# file was deleted (no href)2019$line.= esc_path($to->{'file'});2020}2021}else{2022# "ordinary" diff2023$line=~s!^(diff (.*?) )"?a/.*$!$1!;2024if($from->{'href'}) {2025$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},2026'a/'. esc_path($from->{'file'}));2027}else{# file was added (no href)2028$line.='a/'. esc_path($from->{'file'});2029}2030$line.=' ';2031if($to->{'href'}) {2032$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2033'b/'. esc_path($to->{'file'}));2034}else{# file was deleted2035$line.='b/'. esc_path($to->{'file'});2036}2037}20382039return"<div class=\"diff header\">$line</div>\n";2040}20412042# format extended diff header line, before patch itself2043sub format_extended_diff_header_line {2044my$line=shift;2045my$diffinfo=shift;2046my($from,$to) =@_;20472048# match <path>2049if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {2050$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},2051 esc_path($from->{'file'}));2052}2053if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {2054$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},2055 esc_path($to->{'file'}));2056}2057# match single <mode>2058if($line=~m/\s(\d{6})$/) {2059$line.='<span class="info"> ('.2060 file_type_long($1) .2061')</span>';2062}2063# match <hash>2064if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {2065# can match only for combined diff2066$line='index ';2067for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2068if($from->{'href'}[$i]) {2069$line.=$cgi->a({-href=>$from->{'href'}[$i],2070-class=>"hash"},2071substr($diffinfo->{'from_id'}[$i],0,7));2072}else{2073$line.='0' x 7;2074}2075# separator2076$line.=','if($i<$diffinfo->{'nparents'} -1);2077}2078$line.='..';2079if($to->{'href'}) {2080$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2081substr($diffinfo->{'to_id'},0,7));2082}else{2083$line.='0' x 7;2084}20852086}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {2087# can match only for ordinary diff2088my($from_link,$to_link);2089if($from->{'href'}) {2090$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},2091substr($diffinfo->{'from_id'},0,7));2092}else{2093$from_link='0' x 7;2094}2095if($to->{'href'}) {2096$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2097substr($diffinfo->{'to_id'},0,7));2098}else{2099$to_link='0' x 7;2100}2101my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});2102$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;2103}21042105return$line."<br/>\n";2106}21072108# format from-file/to-file diff header2109sub format_diff_from_to_header {2110my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2111my$line;2112my$result='';21132114$line=$from_line;2115#assert($line =~ m/^---/) if DEBUG;2116# no extra formatting for "^--- /dev/null"2117if(!$diffinfo->{'nparents'}) {2118# ordinary (single parent) diff2119if($line=~m!^--- "?a/!) {2120if($from->{'href'}) {2121$line='--- a/'.2122$cgi->a({-href=>$from->{'href'}, -class=>"path"},2123 esc_path($from->{'file'}));2124}else{2125$line='--- a/'.2126 esc_path($from->{'file'});2127}2128}2129$result.= qq!<div class="diff from_file">$line</div>\n!;21302131}else{2132# combined diff (merge commit)2133for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2134if($from->{'href'}[$i]) {2135$line='--- '.2136$cgi->a({-href=>href(action=>"blobdiff",2137 hash_parent=>$diffinfo->{'from_id'}[$i],2138 hash_parent_base=>$parents[$i],2139 file_parent=>$from->{'file'}[$i],2140 hash=>$diffinfo->{'to_id'},2141 hash_base=>$hash,2142 file_name=>$to->{'file'}),2143-class=>"path",2144-title=>"diff". ($i+1)},2145$i+1) .2146'/'.2147$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2148 esc_path($from->{'file'}[$i]));2149}else{2150$line='--- /dev/null';2151}2152$result.= qq!<div class="diff from_file">$line</div>\n!;2153}2154}21552156$line=$to_line;2157#assert($line =~ m/^\+\+\+/) if DEBUG;2158# no extra formatting for "^+++ /dev/null"2159if($line=~m!^\+\+\+ "?b/!) {2160if($to->{'href'}) {2161$line='+++ b/'.2162$cgi->a({-href=>$to->{'href'}, -class=>"path"},2163 esc_path($to->{'file'}));2164}else{2165$line='+++ b/'.2166 esc_path($to->{'file'});2167}2168}2169$result.= qq!<div class="diff to_file">$line</div>\n!;21702171return$result;2172}21732174# create note for patch simplified by combined diff2175sub format_diff_cc_simplified {2176my($diffinfo,@parents) =@_;2177my$result='';21782179$result.="<div class=\"diff header\">".2180"diff --cc ";2181if(!is_deleted($diffinfo)) {2182$result.=$cgi->a({-href => href(action=>"blob",2183 hash_base=>$hash,2184 hash=>$diffinfo->{'to_id'},2185 file_name=>$diffinfo->{'to_file'}),2186-class=>"path"},2187 esc_path($diffinfo->{'to_file'}));2188}else{2189$result.= esc_path($diffinfo->{'to_file'});2190}2191$result.="</div>\n".# class="diff header"2192"<div class=\"diff nodifferences\">".2193"Simple merge".2194"</div>\n";# class="diff nodifferences"21952196return$result;2197}21982199# format patch (diff) line (not to be used for diff headers)2200sub format_diff_line {2201my$line=shift;2202my($from,$to) =@_;2203my$diff_class="";22042205chomp$line;22062207if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2208# combined diff2209my$prefix=substr($line,0,scalar@{$from->{'href'}});2210if($line=~m/^\@{3}/) {2211$diff_class=" chunk_header";2212}elsif($line=~m/^\\/) {2213$diff_class=" incomplete";2214}elsif($prefix=~tr/+/+/) {2215$diff_class=" add";2216}elsif($prefix=~tr/-/-/) {2217$diff_class=" rem";2218}2219}else{2220# assume ordinary diff2221my$char=substr($line,0,1);2222if($chareq'+') {2223$diff_class=" add";2224}elsif($chareq'-') {2225$diff_class=" rem";2226}elsif($chareq'@') {2227$diff_class=" chunk_header";2228}elsif($chareq"\\") {2229$diff_class=" incomplete";2230}2231}2232$line= untabify($line);2233if($from&&$to&&$line=~m/^\@{2} /) {2234my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2235$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;22362237$from_lines=0unlessdefined$from_lines;2238$to_lines=0unlessdefined$to_lines;22392240if($from->{'href'}) {2241$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2242-class=>"list"},$from_text);2243}2244if($to->{'href'}) {2245$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2246-class=>"list"},$to_text);2247}2248$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2249"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2250return"<div class=\"diff$diff_class\">$line</div>\n";2251}elsif($from&&$to&&$line=~m/^\@{3}/) {2252my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2253my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);22542255@from_text=split(' ',$ranges);2256for(my$i=0;$i<@from_text; ++$i) {2257($from_start[$i],$from_nlines[$i]) =2258(split(',',substr($from_text[$i],1)),0);2259}22602261$to_text=pop@from_text;2262$to_start=pop@from_start;2263$to_nlines=pop@from_nlines;22642265$line="<span class=\"chunk_info\">$prefix";2266for(my$i=0;$i<@from_text; ++$i) {2267if($from->{'href'}[$i]) {2268$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2269-class=>"list"},$from_text[$i]);2270}else{2271$line.=$from_text[$i];2272}2273$line.=" ";2274}2275if($to->{'href'}) {2276$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2277-class=>"list"},$to_text);2278}else{2279$line.=$to_text;2280}2281$line.="$prefix</span>".2282"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2283return"<div class=\"diff$diff_class\">$line</div>\n";2284}2285return"<div class=\"diff$diff_class\">". esc_html($line, -nbsp=>1) ."</div>\n";2286}22872288# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2289# linked. Pass the hash of the tree/commit to snapshot.2290sub format_snapshot_links {2291my($hash) =@_;2292my$num_fmts=@snapshot_fmts;2293if($num_fmts>1) {2294# A parenthesized list of links bearing format names.2295# e.g. "snapshot (_tar.gz_ _zip_)"2296return"snapshot (".join(' ',map2297$cgi->a({2298-href => href(2299 action=>"snapshot",2300 hash=>$hash,2301 snapshot_format=>$_2302)2303},$known_snapshot_formats{$_}{'display'})2304,@snapshot_fmts) .")";2305}elsif($num_fmts==1) {2306# A single "snapshot" link whose tooltip bears the format name.2307# i.e. "_snapshot_"2308my($fmt) =@snapshot_fmts;2309return2310$cgi->a({2311-href => href(2312 action=>"snapshot",2313 hash=>$hash,2314 snapshot_format=>$fmt2315),2316-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2317},"snapshot");2318}else{# $num_fmts == 02319returnundef;2320}2321}23222323## ......................................................................2324## functions returning values to be passed, perhaps after some2325## transformation, to other functions; e.g. returning arguments to href()23262327# returns hash to be passed to href to generate gitweb URL2328# in -title key it returns description of link2329sub get_feed_info {2330my$format=shift||'Atom';2331my%res= (action =>lc($format));23322333# feed links are possible only for project views2334return unless(defined$project);2335# some views should link to OPML, or to generic project feed,2336# or don't have specific feed yet (so they should use generic)2337return if($action=~/^(?:tags|heads|forks|tag|search)$/x);23382339my$branch;2340# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2341# from tag links; this also makes possible to detect branch links2342if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2343(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2344$branch=$1;2345}2346# find log type for feed description (title)2347my$type='log';2348if(defined$file_name) {2349$type="history of$file_name";2350$type.="/"if($actioneq'tree');2351$type.=" on '$branch'"if(defined$branch);2352}else{2353$type="log of$branch"if(defined$branch);2354}23552356$res{-title} =$type;2357$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2358$res{'file_name'} =$file_name;23592360return%res;2361}23622363## ----------------------------------------------------------------------2364## git utility subroutines, invoking git commands23652366# returns path to the core git executable and the --git-dir parameter as list2367sub git_cmd {2368$number_of_git_cmds++;2369return$GIT,'--git-dir='.$git_dir;2370}23712372# quote the given arguments for passing them to the shell2373# quote_command("command", "arg 1", "arg with ' and ! characters")2374# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2375# Try to avoid using this function wherever possible.2376sub quote_command {2377returnjoin(' ',2378map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2379}23802381# get HEAD ref of given project as hash2382sub git_get_head_hash {2383return git_get_full_hash(shift,'HEAD');2384}23852386sub git_get_full_hash {2387return git_get_hash(@_);2388}23892390sub git_get_short_hash {2391return git_get_hash(@_,'--short=7');2392}23932394sub git_get_hash {2395my($project,$hash,@options) =@_;2396my$o_git_dir=$git_dir;2397my$retval=undef;2398$git_dir="$projectroot/$project";2399if(open my$fd,'-|', git_cmd(),'rev-parse',2400'--verify','-q',@options,$hash) {2401$retval= <$fd>;2402chomp$retvalifdefined$retval;2403close$fd;2404}2405if(defined$o_git_dir) {2406$git_dir=$o_git_dir;2407}2408return$retval;2409}24102411# get type of given object2412sub git_get_type {2413my$hash=shift;24142415open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2416my$type= <$fd>;2417close$fdorreturn;2418chomp$type;2419return$type;2420}24212422# repository configuration2423our$config_file='';2424our%config;24252426# store multiple values for single key as anonymous array reference2427# single values stored directly in the hash, not as [ <value> ]2428sub hash_set_multi {2429my($hash,$key,$value) =@_;24302431if(!exists$hash->{$key}) {2432$hash->{$key} =$value;2433}elsif(!ref$hash->{$key}) {2434$hash->{$key} = [$hash->{$key},$value];2435}else{2436push@{$hash->{$key}},$value;2437}2438}24392440# return hash of git project configuration2441# optionally limited to some section, e.g. 'gitweb'2442sub git_parse_project_config {2443my$section_regexp=shift;2444my%config;24452446local$/="\0";24472448open my$fh,"-|", git_cmd(),"config",'-z','-l',2449orreturn;24502451while(my$keyval= <$fh>) {2452chomp$keyval;2453my($key,$value) =split(/\n/,$keyval,2);24542455 hash_set_multi(\%config,$key,$value)2456if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2457}2458close$fh;24592460return%config;2461}24622463# convert config value to boolean: 'true' or 'false'2464# no value, number > 0, 'true' and 'yes' values are true2465# rest of values are treated as false (never as error)2466sub config_to_bool {2467my$val=shift;24682469return1if!defined$val;# section.key24702471# strip leading and trailing whitespace2472$val=~s/^\s+//;2473$val=~s/\s+$//;24742475return(($val=~/^\d+$/&&$val) ||# section.key = 12476($val=~/^(?:true|yes)$/i));# section.key = true2477}24782479# convert config value to simple decimal number2480# an optional value suffix of 'k', 'm', or 'g' will cause the value2481# to be multiplied by 1024, 1048576, or 10737418242482sub config_to_int {2483my$val=shift;24842485# strip leading and trailing whitespace2486$val=~s/^\s+//;2487$val=~s/\s+$//;24882489if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2490$unit=lc($unit);2491# unknown unit is treated as 12492return$num* ($uniteq'g'?1073741824:2493$uniteq'm'?1048576:2494$uniteq'k'?1024:1);2495}2496return$val;2497}24982499# convert config value to array reference, if needed2500sub config_to_multi {2501my$val=shift;25022503returnref($val) ?$val: (defined($val) ? [$val] : []);2504}25052506sub git_get_project_config {2507my($key,$type) =@_;25082509return unlessdefined$git_dir;25102511# key sanity check2512return unless($key);2513$key=~s/^gitweb\.//;2514return if($key=~m/\W/);25152516# type sanity check2517if(defined$type) {2518$type=~s/^--//;2519$type=undef2520unless($typeeq'bool'||$typeeq'int');2521}25222523# get config2524if(!defined$config_file||2525$config_filene"$git_dir/config") {2526%config= git_parse_project_config('gitweb');2527$config_file="$git_dir/config";2528}25292530# check if config variable (key) exists2531return unlessexists$config{"gitweb.$key"};25322533# ensure given type2534if(!defined$type) {2535return$config{"gitweb.$key"};2536}elsif($typeeq'bool') {2537# backward compatibility: 'git config --bool' returns true/false2538return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2539}elsif($typeeq'int') {2540return config_to_int($config{"gitweb.$key"});2541}2542return$config{"gitweb.$key"};2543}25442545# get hash of given path at given ref2546sub git_get_hash_by_path {2547my$base=shift;2548my$path=shift||returnundef;2549my$type=shift;25502551$path=~ s,/+$,,;25522553open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2554or die_error(500,"Open git-ls-tree failed");2555my$line= <$fd>;2556close$fdorreturnundef;25572558if(!defined$line) {2559# there is no tree or hash given by $path at $base2560returnundef;2561}25622563#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2564$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2565if(defined$type&&$typene$2) {2566# type doesn't match2567returnundef;2568}2569return$3;2570}25712572# get path of entry with given hash at given tree-ish (ref)2573# used to get 'from' filename for combined diff (merge commit) for renames2574sub git_get_path_by_hash {2575my$base=shift||return;2576my$hash=shift||return;25772578local$/="\0";25792580open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2581orreturnundef;2582while(my$line= <$fd>) {2583chomp$line;25842585#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2586#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2587if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2588close$fd;2589return$1;2590}2591}2592close$fd;2593returnundef;2594}25952596## ......................................................................2597## git utility functions, directly accessing git repository25982599# get the value of config variable either from file named as the variable2600# itself in the repository ($GIT_DIR/$name file), or from gitweb.$name2601# configuration variable in the repository config file.2602sub git_get_file_or_project_config {2603my($path,$name) =@_;26042605$git_dir="$projectroot/$path";2606open my$fd,'<',"$git_dir/$name"2607orreturn git_get_project_config($name);2608my$conf= <$fd>;2609close$fd;2610if(defined$conf) {2611chomp$conf;2612}2613return$conf;2614}26152616sub git_get_project_description {2617my$path=shift;2618return git_get_file_or_project_config($path,'description');2619}26202621sub git_get_project_category {2622my$path=shift;2623return git_get_file_or_project_config($path,'category');2624}262526262627# supported formats:2628# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2629# - if its contents is a number, use it as tag weight,2630# - otherwise add a tag with weight 12631# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2632# the same value multiple times increases tag weight2633# * `gitweb.ctag' multi-valued repo config variable2634sub git_get_project_ctags {2635my$project=shift;2636my$ctags= {};26372638$git_dir="$projectroot/$project";2639if(opendir my$dh,"$git_dir/ctags") {2640my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2641foreachmy$tagfile(@files) {2642open my$ct,'<',$tagfile2643ornext;2644my$val= <$ct>;2645chomp$valif$val;2646close$ct;26472648(my$ctag=$tagfile) =~ s#.*/##;2649if($val=~/^\d+$/) {2650$ctags->{$ctag} =$val;2651}else{2652$ctags->{$ctag} =1;2653}2654}2655closedir$dh;26562657}elsif(open my$fh,'<',"$git_dir/ctags") {2658while(my$line= <$fh>) {2659chomp$line;2660$ctags->{$line}++if$line;2661}2662close$fh;26632664}else{2665my$taglist= config_to_multi(git_get_project_config('ctag'));2666foreachmy$tag(@$taglist) {2667$ctags->{$tag}++;2668}2669}26702671return$ctags;2672}26732674# return hash, where keys are content tags ('ctags'),2675# and values are sum of weights of given tag in every project2676sub git_gather_all_ctags {2677my$projects=shift;2678my$ctags= {};26792680foreachmy$p(@$projects) {2681foreachmy$ct(keys%{$p->{'ctags'}}) {2682$ctags->{$ct} +=$p->{'ctags'}->{$ct};2683}2684}26852686return$ctags;2687}26882689sub git_populate_project_tagcloud {2690my$ctags=shift;26912692# First, merge different-cased tags; tags vote on casing2693my%ctags_lc;2694foreach(keys%$ctags) {2695$ctags_lc{lc$_}->{count} +=$ctags->{$_};2696if(not$ctags_lc{lc$_}->{topcount}2697or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2698$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2699$ctags_lc{lc$_}->{topname} =$_;2700}2701}27022703my$cloud;2704my$matched=$cgi->param('by_tag');2705if(eval{require HTML::TagCloud;1; }) {2706$cloud= HTML::TagCloud->new;2707foreachmy$ctag(sort keys%ctags_lc) {2708# Pad the title with spaces so that the cloud looks2709# less crammed.2710my$title= esc_html($ctags_lc{$ctag}->{topname});2711$title=~s/ / /g;2712$title=~s/^/ /g;2713$title=~s/$/ /g;2714if(defined$matched&&$matchedeq$ctag) {2715$title=qq(<span class="match">$title</span>);2716}2717$cloud->add($title, href(project=>undef, ctag=>$ctag),2718$ctags_lc{$ctag}->{count});2719}2720}else{2721$cloud= {};2722foreachmy$ctag(keys%ctags_lc) {2723my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2724if(defined$matched&&$matchedeq$ctag) {2725$title=qq(<span class="match">$title</span>);2726}2727$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};2728$cloud->{$ctag}{ctag} =2729$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);2730}2731}2732return$cloud;2733}27342735sub git_show_project_tagcloud {2736my($cloud,$count) =@_;2737if(ref$cloudeq'HTML::TagCloud') {2738return$cloud->html_and_css($count);2739}else{2740my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;2741return2742'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.2743join(', ',map{2744$cloud->{$_}->{'ctag'}2745}splice(@tags,0,$count)) .2746'</div>';2747}2748}27492750sub git_get_project_url_list {2751my$path=shift;27522753$git_dir="$projectroot/$path";2754open my$fd,'<',"$git_dir/cloneurl"2755orreturnwantarray?2756@{ config_to_multi(git_get_project_config('url')) } :2757 config_to_multi(git_get_project_config('url'));2758my@git_project_url_list=map{chomp;$_} <$fd>;2759close$fd;27602761returnwantarray?@git_project_url_list: \@git_project_url_list;2762}27632764sub git_get_projects_list {2765my$filter=shift||'';2766my@list;27672768$filter=~s/\.git$//;27692770if(-d $projects_list) {2771# search in directory2772my$dir=$projects_list;2773# remove the trailing "/"2774$dir=~s!/+$!!;2775my$pfxlen=length("$projects_list");2776my$pfxdepth= ($projects_list=~tr!/!!);2777# when filtering, search only given subdirectory2778if($filter) {2779$dir.="/$filter";2780$dir=~s!/+$!!;2781}27822783 File::Find::find({2784 follow_fast =>1,# follow symbolic links2785 follow_skip =>2,# ignore duplicates2786 dangling_symlinks =>0,# ignore dangling symlinks, silently2787 wanted =>sub{2788# global variables2789our$project_maxdepth;2790our$projectroot;2791# skip project-list toplevel, if we get it.2792return if(m!^[/.]$!);2793# only directories can be git repositories2794return unless(-d $_);2795# don't traverse too deep (Find is super slow on os x)2796# $project_maxdepth excludes depth of $projectroot2797if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2798$File::Find::prune =1;2799return;2800}28012802my$path=substr($File::Find::name,$pfxlen+1);2803# we check related file in $projectroot2804if(check_export_ok("$projectroot/$path")) {2805push@list, { path =>$path};2806$File::Find::prune =1;2807}2808},2809},"$dir");28102811}elsif(-f $projects_list) {2812# read from file(url-encoded):2813# 'git%2Fgit.git Linus+Torvalds'2814# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2815# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2816open my$fd,'<',$projects_listorreturn;2817 PROJECT:2818while(my$line= <$fd>) {2819chomp$line;2820my($path,$owner) =split' ',$line;2821$path= unescape($path);2822$owner= unescape($owner);2823if(!defined$path) {2824next;2825}2826# if $filter is rpovided, check if $path begins with $filter2827if($filter&&$path!~m!^\Q$filter\E/!) {2828next;2829}2830if(check_export_ok("$projectroot/$path")) {2831my$pr= {2832 path =>$path,2833 owner => to_utf8($owner),2834};2835push@list,$pr;2836}2837}2838close$fd;2839}2840return@list;2841}28422843# written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)2844# as side effects it sets 'forks' field to list of forks for forked projects2845sub filter_forks_from_projects_list {2846my$projects=shift;28472848my%trie;# prefix tree of directories (path components)2849# generate trie out of those directories that might contain forks2850foreachmy$pr(@$projects) {2851my$path=$pr->{'path'};2852$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory2853next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'2854next unless($path);# skip '.git' repository: tests, git-instaweb2855next unless(-d $path);# containing directory exists2856$pr->{'forks'} = [];# there can be 0 or more forks of project28572858# add to trie2859my@dirs=split('/',$path);2860# walk the trie, until either runs out of components or out of trie2861my$ref= \%trie;2862while(scalar@dirs&&2863exists($ref->{$dirs[0]})) {2864$ref=$ref->{shift@dirs};2865}2866# create rest of trie structure from rest of components2867foreachmy$dir(@dirs) {2868$ref=$ref->{$dir} = {};2869}2870# create end marker, store $pr as a data2871$ref->{''} =$prif(!exists$ref->{''});2872}28732874# filter out forks, by finding shortest prefix match for paths2875my@filtered;2876 PROJECT:2877foreachmy$pr(@$projects) {2878# trie lookup2879my$ref= \%trie;2880 DIR:2881foreachmy$dir(split('/',$pr->{'path'})) {2882if(exists$ref->{''}) {2883# found [shortest] prefix, is a fork - skip it2884push@{$ref->{''}{'forks'}},$pr;2885next PROJECT;2886}2887if(!exists$ref->{$dir}) {2888# not in trie, cannot have prefix, not a fork2889push@filtered,$pr;2890next PROJECT;2891}2892# If the dir is there, we just walk one step down the trie.2893$ref=$ref->{$dir};2894}2895# we ran out of trie2896# (shouldn't happen: it's either no match, or end marker)2897push@filtered,$pr;2898}28992900return@filtered;2901}29022903# note: fill_project_list_info must be run first,2904# for 'descr_long' and 'ctags' to be filled2905sub search_projects_list {2906my($projlist,%opts) =@_;2907my$tagfilter=$opts{'tagfilter'};2908my$searchtext=$opts{'searchtext'};29092910return@$projlist2911unless($tagfilter||$searchtext);29122913my@projects;2914 PROJECT:2915foreachmy$pr(@$projlist) {29162917if($tagfilter) {2918next unlessref($pr->{'ctags'})eq'HASH';2919next unless2920grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};2921}29222923if($searchtext) {2924next unless2925$pr->{'path'} =~/$searchtext/||2926$pr->{'descr_long'} =~/$searchtext/;2927}29282929push@projects,$pr;2930}29312932return@projects;2933}29342935our$gitweb_project_owner=undef;2936sub git_get_project_list_from_file {29372938return if(defined$gitweb_project_owner);29392940$gitweb_project_owner= {};2941# read from file (url-encoded):2942# 'git%2Fgit.git Linus+Torvalds'2943# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2944# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2945if(-f $projects_list) {2946open(my$fd,'<',$projects_list);2947while(my$line= <$fd>) {2948chomp$line;2949my($pr,$ow) =split' ',$line;2950$pr= unescape($pr);2951$ow= unescape($ow);2952$gitweb_project_owner->{$pr} = to_utf8($ow);2953}2954close$fd;2955}2956}29572958sub git_get_project_owner {2959my$project=shift;2960my$owner;29612962returnundefunless$project;2963$git_dir="$projectroot/$project";29642965if(!defined$gitweb_project_owner) {2966 git_get_project_list_from_file();2967}29682969if(exists$gitweb_project_owner->{$project}) {2970$owner=$gitweb_project_owner->{$project};2971}2972if(!defined$owner){2973$owner= git_get_project_config('owner');2974}2975if(!defined$owner) {2976$owner= get_file_owner("$git_dir");2977}29782979return$owner;2980}29812982sub git_get_last_activity {2983my($path) =@_;2984my$fd;29852986$git_dir="$projectroot/$path";2987open($fd,"-|", git_cmd(),'for-each-ref',2988'--format=%(committer)',2989'--sort=-committerdate',2990'--count=1',2991'refs/heads')orreturn;2992my$most_recent= <$fd>;2993close$fdorreturn;2994if(defined$most_recent&&2995$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {2996my$timestamp=$1;2997my$age=time-$timestamp;2998return($age, age_string($age));2999}3000return(undef,undef);3001}30023003# Implementation note: when a single remote is wanted, we cannot use 'git3004# remote show -n' because that command always work (assuming it's a remote URL3005# if it's not defined), and we cannot use 'git remote show' because that would3006# try to make a network roundtrip. So the only way to find if that particular3007# remote is defined is to walk the list provided by 'git remote -v' and stop if3008# and when we find what we want.3009sub git_get_remotes_list {3010my$wanted=shift;3011my%remotes= ();30123013open my$fd,'-|', git_cmd(),'remote','-v';3014return unless$fd;3015while(my$remote= <$fd>) {3016chomp$remote;3017$remote=~s!\t(.*?)\s+\((\w+)\)$!!;3018next if$wantedand not$remoteeq$wanted;3019my($url,$key) = ($1,$2);30203021$remotes{$remote} ||= {'heads'=> () };3022$remotes{$remote}{$key} =$url;3023}3024close$fdorreturn;3025returnwantarray?%remotes: \%remotes;3026}30273028# Takes a hash of remotes as first parameter and fills it by adding the3029# available remote heads for each of the indicated remotes.3030sub fill_remote_heads {3031my$remotes=shift;3032my@heads=map{"remotes/$_"}keys%$remotes;3033my@remoteheads= git_get_heads_list(undef,@heads);3034foreachmy$remote(keys%$remotes) {3035$remotes->{$remote}{'heads'} = [grep{3036$_->{'name'} =~s!^$remote/!!3037}@remoteheads];3038}3039}30403041sub git_get_references {3042my$type=shift||"";3043my%refs;3044# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113045# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3046open my$fd,"-|", git_cmd(),"show-ref","--dereference",3047($type? ("--","refs/$type") : ())# use -- <pattern> if $type3048orreturn;30493050while(my$line= <$fd>) {3051chomp$line;3052if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3053if(defined$refs{$1}) {3054push@{$refs{$1}},$2;3055}else{3056$refs{$1} = [$2];3057}3058}3059}3060close$fdorreturn;3061return \%refs;3062}30633064sub git_get_rev_name_tags {3065my$hash=shift||returnundef;30663067open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3068orreturn;3069my$name_rev= <$fd>;3070close$fd;30713072if($name_rev=~ m|^$hash tags/(.*)$|) {3073return$1;3074}else{3075# catches also '$hash undefined' output3076returnundef;3077}3078}30793080## ----------------------------------------------------------------------3081## parse to hash functions30823083sub parse_date {3084my$epoch=shift;3085my$tz=shift||"-0000";30863087my%date;3088my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3089my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3090my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3091$date{'hour'} =$hour;3092$date{'minute'} =$min;3093$date{'mday'} =$mday;3094$date{'day'} =$days[$wday];3095$date{'month'} =$months[$mon];3096$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3097$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3098$date{'mday-time'} =sprintf"%d%s%02d:%02d",3099$mday,$months[$mon],$hour,$min;3100$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",31011900+$year,1+$mon,$mday,$hour,$min,$sec;31023103my($tz_sign,$tz_hour,$tz_min) =3104($tz=~m/^([-+])(\d\d)(\d\d)$/);3105$tz_sign= ($tz_signeq'-'? -1: +1);3106my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3107($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3108$date{'hour_local'} =$hour;3109$date{'minute_local'} =$min;3110$date{'tz_local'} =$tz;3111$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",31121900+$year,$mon+1,$mday,3113$hour,$min,$sec,$tz);3114return%date;3115}31163117sub parse_tag {3118my$tag_id=shift;3119my%tag;3120my@comment;31213122open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3123$tag{'id'} =$tag_id;3124while(my$line= <$fd>) {3125chomp$line;3126if($line=~m/^object ([0-9a-fA-F]{40})$/) {3127$tag{'object'} =$1;3128}elsif($line=~m/^type (.+)$/) {3129$tag{'type'} =$1;3130}elsif($line=~m/^tag (.+)$/) {3131$tag{'name'} =$1;3132}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3133$tag{'author'} =$1;3134$tag{'author_epoch'} =$2;3135$tag{'author_tz'} =$3;3136if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3137$tag{'author_name'} =$1;3138$tag{'author_email'} =$2;3139}else{3140$tag{'author_name'} =$tag{'author'};3141}3142}elsif($line=~m/--BEGIN/) {3143push@comment,$line;3144last;3145}elsif($lineeq"") {3146last;3147}3148}3149push@comment, <$fd>;3150$tag{'comment'} = \@comment;3151close$fdorreturn;3152if(!defined$tag{'name'}) {3153return3154};3155return%tag3156}31573158sub parse_commit_text {3159my($commit_text,$withparents) =@_;3160my@commit_lines=split'\n',$commit_text;3161my%co;31623163pop@commit_lines;# Remove '\0'31643165if(!@commit_lines) {3166return;3167}31683169my$header=shift@commit_lines;3170if($header!~m/^[0-9a-fA-F]{40}/) {3171return;3172}3173($co{'id'},my@parents) =split' ',$header;3174while(my$line=shift@commit_lines) {3175last if$lineeq"\n";3176if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3177$co{'tree'} =$1;3178}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3179push@parents,$1;3180}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3181$co{'author'} = to_utf8($1);3182$co{'author_epoch'} =$2;3183$co{'author_tz'} =$3;3184if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3185$co{'author_name'} =$1;3186$co{'author_email'} =$2;3187}else{3188$co{'author_name'} =$co{'author'};3189}3190}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3191$co{'committer'} = to_utf8($1);3192$co{'committer_epoch'} =$2;3193$co{'committer_tz'} =$3;3194if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3195$co{'committer_name'} =$1;3196$co{'committer_email'} =$2;3197}else{3198$co{'committer_name'} =$co{'committer'};3199}3200}3201}3202if(!defined$co{'tree'}) {3203return;3204};3205$co{'parents'} = \@parents;3206$co{'parent'} =$parents[0];32073208foreachmy$title(@commit_lines) {3209$title=~s/^ //;3210if($titlene"") {3211$co{'title'} = chop_str($title,80,5);3212# remove leading stuff of merges to make the interesting part visible3213if(length($title) >50) {3214$title=~s/^Automatic //;3215$title=~s/^merge (of|with) /Merge ... /i;3216if(length($title) >50) {3217$title=~s/(http|rsync):\/\///;3218}3219if(length($title) >50) {3220$title=~s/(master|www|rsync)\.//;3221}3222if(length($title) >50) {3223$title=~s/kernel.org:?//;3224}3225if(length($title) >50) {3226$title=~s/\/pub\/scm//;3227}3228}3229$co{'title_short'} = chop_str($title,50,5);3230last;3231}3232}3233if(!defined$co{'title'} ||$co{'title'}eq"") {3234$co{'title'} =$co{'title_short'} ='(no commit message)';3235}3236# remove added spaces3237foreachmy$line(@commit_lines) {3238$line=~s/^ //;3239}3240$co{'comment'} = \@commit_lines;32413242my$age=time-$co{'committer_epoch'};3243$co{'age'} =$age;3244$co{'age_string'} = age_string($age);3245my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3246if($age>60*60*24*7*2) {3247$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3248$co{'age_string_age'} =$co{'age_string'};3249}else{3250$co{'age_string_date'} =$co{'age_string'};3251$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3252}3253return%co;3254}32553256sub parse_commit {3257my($commit_id) =@_;3258my%co;32593260local$/="\0";32613262open my$fd,"-|", git_cmd(),"rev-list",3263"--parents",3264"--header",3265"--max-count=1",3266$commit_id,3267"--",3268or die_error(500,"Open git-rev-list failed");3269%co= parse_commit_text(<$fd>,1);3270close$fd;32713272return%co;3273}32743275sub parse_commits {3276my($commit_id,$maxcount,$skip,$filename,@args) =@_;3277my@cos;32783279$maxcount||=1;3280$skip||=0;32813282local$/="\0";32833284open my$fd,"-|", git_cmd(),"rev-list",3285"--header",3286@args,3287("--max-count=".$maxcount),3288("--skip=".$skip),3289@extra_options,3290$commit_id,3291"--",3292($filename? ($filename) : ())3293or die_error(500,"Open git-rev-list failed");3294while(my$line= <$fd>) {3295my%co= parse_commit_text($line);3296push@cos, \%co;3297}3298close$fd;32993300returnwantarray?@cos: \@cos;3301}33023303# parse line of git-diff-tree "raw" output3304sub parse_difftree_raw_line {3305my$line=shift;3306my%res;33073308# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3309# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3310if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3311$res{'from_mode'} =$1;3312$res{'to_mode'} =$2;3313$res{'from_id'} =$3;3314$res{'to_id'} =$4;3315$res{'status'} =$5;3316$res{'similarity'} =$6;3317if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3318($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3319}else{3320$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3321}3322}3323# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3324# combined diff (for merge commit)3325elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3326$res{'nparents'} =length($1);3327$res{'from_mode'} = [split(' ',$2) ];3328$res{'to_mode'} =pop@{$res{'from_mode'}};3329$res{'from_id'} = [split(' ',$3) ];3330$res{'to_id'} =pop@{$res{'from_id'}};3331$res{'status'} = [split('',$4) ];3332$res{'to_file'} = unquote($5);3333}3334# 'c512b523472485aef4fff9e57b229d9d243c967f'3335elsif($line=~m/^([0-9a-fA-F]{40})$/) {3336$res{'commit'} =$1;3337}33383339returnwantarray?%res: \%res;3340}33413342# wrapper: return parsed line of git-diff-tree "raw" output3343# (the argument might be raw line, or parsed info)3344sub parsed_difftree_line {3345my$line_or_ref=shift;33463347if(ref($line_or_ref)eq"HASH") {3348# pre-parsed (or generated by hand)3349return$line_or_ref;3350}else{3351return parse_difftree_raw_line($line_or_ref);3352}3353}33543355# parse line of git-ls-tree output3356sub parse_ls_tree_line {3357my$line=shift;3358my%opts=@_;3359my%res;33603361if($opts{'-l'}) {3362#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3363$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;33643365$res{'mode'} =$1;3366$res{'type'} =$2;3367$res{'hash'} =$3;3368$res{'size'} =$4;3369if($opts{'-z'}) {3370$res{'name'} =$5;3371}else{3372$res{'name'} = unquote($5);3373}3374}else{3375#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3376$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;33773378$res{'mode'} =$1;3379$res{'type'} =$2;3380$res{'hash'} =$3;3381if($opts{'-z'}) {3382$res{'name'} =$4;3383}else{3384$res{'name'} = unquote($4);3385}3386}33873388returnwantarray?%res: \%res;3389}33903391# generates _two_ hashes, references to which are passed as 2 and 3 argument3392sub parse_from_to_diffinfo {3393my($diffinfo,$from,$to,@parents) =@_;33943395if($diffinfo->{'nparents'}) {3396# combined diff3397$from->{'file'} = [];3398$from->{'href'} = [];3399 fill_from_file_info($diffinfo,@parents)3400unlessexists$diffinfo->{'from_file'};3401for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3402$from->{'file'}[$i] =3403defined$diffinfo->{'from_file'}[$i] ?3404$diffinfo->{'from_file'}[$i] :3405$diffinfo->{'to_file'};3406if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3407$from->{'href'}[$i] = href(action=>"blob",3408 hash_base=>$parents[$i],3409 hash=>$diffinfo->{'from_id'}[$i],3410 file_name=>$from->{'file'}[$i]);3411}else{3412$from->{'href'}[$i] =undef;3413}3414}3415}else{3416# ordinary (not combined) diff3417$from->{'file'} =$diffinfo->{'from_file'};3418if($diffinfo->{'status'}ne"A") {# not new (added) file3419$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3420 hash=>$diffinfo->{'from_id'},3421 file_name=>$from->{'file'});3422}else{3423delete$from->{'href'};3424}3425}34263427$to->{'file'} =$diffinfo->{'to_file'};3428if(!is_deleted($diffinfo)) {# file exists in result3429$to->{'href'} = href(action=>"blob", hash_base=>$hash,3430 hash=>$diffinfo->{'to_id'},3431 file_name=>$to->{'file'});3432}else{3433delete$to->{'href'};3434}3435}34363437## ......................................................................3438## parse to array of hashes functions34393440sub git_get_heads_list {3441my($limit,@classes) =@_;3442@classes= ('heads')unless@classes;3443my@patterns=map{"refs/$_"}@classes;3444my@headslist;34453446open my$fd,'-|', git_cmd(),'for-each-ref',3447($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3448'--format=%(objectname) %(refname) %(subject)%00%(committer)',3449@patterns3450orreturn;3451while(my$line= <$fd>) {3452my%ref_item;34533454chomp$line;3455my($refinfo,$committerinfo) =split(/\0/,$line);3456my($hash,$name,$title) =split(' ',$refinfo,3);3457my($committer,$epoch,$tz) =3458($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3459$ref_item{'fullname'} =$name;3460$name=~s!^refs/(?:head|remote)s/!!;34613462$ref_item{'name'} =$name;3463$ref_item{'id'} =$hash;3464$ref_item{'title'} =$title||'(no commit message)';3465$ref_item{'epoch'} =$epoch;3466if($epoch) {3467$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3468}else{3469$ref_item{'age'} ="unknown";3470}34713472push@headslist, \%ref_item;3473}3474close$fd;34753476returnwantarray?@headslist: \@headslist;3477}34783479sub git_get_tags_list {3480my$limit=shift;3481my@tagslist;34823483open my$fd,'-|', git_cmd(),'for-each-ref',3484($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3485'--format=%(objectname) %(objecttype) %(refname) '.3486'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3487'refs/tags'3488orreturn;3489while(my$line= <$fd>) {3490my%ref_item;34913492chomp$line;3493my($refinfo,$creatorinfo) =split(/\0/,$line);3494my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3495my($creator,$epoch,$tz) =3496($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3497$ref_item{'fullname'} =$name;3498$name=~s!^refs/tags/!!;34993500$ref_item{'type'} =$type;3501$ref_item{'id'} =$id;3502$ref_item{'name'} =$name;3503if($typeeq"tag") {3504$ref_item{'subject'} =$title;3505$ref_item{'reftype'} =$reftype;3506$ref_item{'refid'} =$refid;3507}else{3508$ref_item{'reftype'} =$type;3509$ref_item{'refid'} =$id;3510}35113512if($typeeq"tag"||$typeeq"commit") {3513$ref_item{'epoch'} =$epoch;3514if($epoch) {3515$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3516}else{3517$ref_item{'age'} ="unknown";3518}3519}35203521push@tagslist, \%ref_item;3522}3523close$fd;35243525returnwantarray?@tagslist: \@tagslist;3526}35273528## ----------------------------------------------------------------------3529## filesystem-related functions35303531sub get_file_owner {3532my$path=shift;35333534my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3535my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3536if(!defined$gcos) {3537returnundef;3538}3539my$owner=$gcos;3540$owner=~s/[,;].*$//;3541return to_utf8($owner);3542}35433544# assume that file exists3545sub insert_file {3546my$filename=shift;35473548open my$fd,'<',$filename;3549print map{ to_utf8($_) } <$fd>;3550close$fd;3551}35523553## ......................................................................3554## mimetype related functions35553556sub mimetype_guess_file {3557my$filename=shift;3558my$mimemap=shift;3559-r $mimemaporreturnundef;35603561my%mimemap;3562open(my$mh,'<',$mimemap)orreturnundef;3563while(<$mh>) {3564next ifm/^#/;# skip comments3565my($mimetype,@exts) =split(/\s+/);3566foreachmy$ext(@exts) {3567$mimemap{$ext} =$mimetype;3568}3569}3570close($mh);35713572$filename=~/\.([^.]*)$/;3573return$mimemap{$1};3574}35753576sub mimetype_guess {3577my$filename=shift;3578my$mime;3579$filename=~/\./orreturnundef;35803581if($mimetypes_file) {3582my$file=$mimetypes_file;3583if($file!~m!^/!) {# if it is relative path3584# it is relative to project3585$file="$projectroot/$project/$file";3586}3587$mime= mimetype_guess_file($filename,$file);3588}3589$mime||= mimetype_guess_file($filename,'/etc/mime.types');3590return$mime;3591}35923593sub blob_mimetype {3594my$fd=shift;3595my$filename=shift;35963597if($filename) {3598my$mime= mimetype_guess($filename);3599$mimeandreturn$mime;3600}36013602# just in case3603return$default_blob_plain_mimetypeunless$fd;36043605if(-T $fd) {3606return'text/plain';3607}elsif(!$filename) {3608return'application/octet-stream';3609}elsif($filename=~m/\.png$/i) {3610return'image/png';3611}elsif($filename=~m/\.gif$/i) {3612return'image/gif';3613}elsif($filename=~m/\.jpe?g$/i) {3614return'image/jpeg';3615}else{3616return'application/octet-stream';3617}3618}36193620sub blob_contenttype {3621my($fd,$file_name,$type) =@_;36223623$type||= blob_mimetype($fd,$file_name);3624if($typeeq'text/plain'&&defined$default_text_plain_charset) {3625$type.="; charset=$default_text_plain_charset";3626}36273628return$type;3629}36303631# guess file syntax for syntax highlighting; return undef if no highlighting3632# the name of syntax can (in the future) depend on syntax highlighter used3633sub guess_file_syntax {3634my($highlight,$mimetype,$file_name) =@_;3635returnundefunless($highlight&&defined$file_name);3636my$basename= basename($file_name,'.in');3637return$highlight_basename{$basename}3638ifexists$highlight_basename{$basename};36393640$basename=~/\.([^.]*)$/;3641my$ext=$1orreturnundef;3642return$highlight_ext{$ext}3643ifexists$highlight_ext{$ext};36443645returnundef;3646}36473648# run highlighter and return FD of its output,3649# or return original FD if no highlighting3650sub run_highlighter {3651my($fd,$highlight,$syntax) =@_;3652return$fdunless($highlight&&defined$syntax);36533654close$fd;3655open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3656 quote_command($highlight_bin).3657" --replace-tabs=8 --fragment --syntax$syntax|"3658or die_error(500,"Couldn't open file or run syntax highlighter");3659return$fd;3660}36613662## ======================================================================3663## functions printing HTML: header, footer, error page36643665sub get_page_title {3666my$title= to_utf8($site_name);36673668return$titleunless(defined$project);3669$title.=" - ". to_utf8($project);36703671return$titleunless(defined$action);3672$title.="/$action";# $action is US-ASCII (7bit ASCII)36733674return$titleunless(defined$file_name);3675$title.=" - ". esc_path($file_name);3676if($actioneq"tree"&&$file_name!~ m|/$|) {3677$title.="/";3678}36793680return$title;3681}36823683sub get_content_type_html {3684# require explicit support from the UA if we are to send the page as3685# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3686# we have to do this because MSIE sometimes globs '*/*', pretending to3687# support xhtml+xml but choking when it gets what it asked for.3688if(defined$cgi->http('HTTP_ACCEPT') &&3689$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3690$cgi->Accept('application/xhtml+xml') !=0) {3691return'application/xhtml+xml';3692}else{3693return'text/html';3694}3695}36963697sub print_feed_meta {3698if(defined$project) {3699my%href_params= get_feed_info();3700if(!exists$href_params{'-title'}) {3701$href_params{'-title'} ='log';3702}37033704foreachmy$format(qw(RSS Atom)) {3705my$type=lc($format);3706my%link_attr= (3707'-rel'=>'alternate',3708'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3709'-type'=>"application/$type+xml"3710);37113712$href_params{'action'} =$type;3713$link_attr{'-href'} = href(%href_params);3714print"<link ".3715"rel=\"$link_attr{'-rel'}\"".3716"title=\"$link_attr{'-title'}\"".3717"href=\"$link_attr{'-href'}\"".3718"type=\"$link_attr{'-type'}\"".3719"/>\n";37203721$href_params{'extra_options'} ='--no-merges';3722$link_attr{'-href'} = href(%href_params);3723$link_attr{'-title'} .=' (no merges)';3724print"<link ".3725"rel=\"$link_attr{'-rel'}\"".3726"title=\"$link_attr{'-title'}\"".3727"href=\"$link_attr{'-href'}\"".3728"type=\"$link_attr{'-type'}\"".3729"/>\n";3730}37313732}else{3733printf('<link rel="alternate" title="%sprojects list" '.3734'href="%s" type="text/plain; charset=utf-8" />'."\n",3735 esc_attr($site_name), href(project=>undef, action=>"project_index"));3736printf('<link rel="alternate" title="%sprojects feeds" '.3737'href="%s" type="text/x-opml" />'."\n",3738 esc_attr($site_name), href(project=>undef, action=>"opml"));3739}3740}37413742sub print_header_links {3743my$status=shift;37443745# print out each stylesheet that exist, providing backwards capability3746# for those people who defined $stylesheet in a config file3747if(defined$stylesheet) {3748print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3749}else{3750foreachmy$stylesheet(@stylesheets) {3751next unless$stylesheet;3752print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3753}3754}3755 print_feed_meta()3756if($statuseq'200 OK');3757if(defined$favicon) {3758printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);3759}3760}37613762sub print_nav_breadcrumbs {3763my%opts=@_;37643765print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3766if(defined$project) {3767print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3768if(defined$action) {3769my$action_print=$action;3770if(defined$opts{-action_extra}) {3771$action_print=$cgi->a({-href => href(action=>$action)},3772$action);3773}3774print" /$action_print";3775}3776if(defined$opts{-action_extra}) {3777print" /$opts{-action_extra}";3778}3779print"\n";3780}3781}37823783sub print_search_form {3784if(!defined$searchtext) {3785$searchtext="";3786}3787my$search_hash;3788if(defined$hash_base) {3789$search_hash=$hash_base;3790}elsif(defined$hash) {3791$search_hash=$hash;3792}else{3793$search_hash="HEAD";3794}3795my$action=$my_uri;3796my$use_pathinfo= gitweb_check_feature('pathinfo');3797if($use_pathinfo) {3798$action.="/".esc_url($project);3799}3800print$cgi->startform(-method=>"get", -action =>$action) .3801"<div class=\"search\">\n".3802(!$use_pathinfo&&3803$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3804$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3805$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3806$cgi->popup_menu(-name =>'st', -default=>'commit',3807-values=> ['commit','grep','author','committer','pickaxe']) .3808$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3809" search:\n",3810$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3811"<span title=\"Extended regular expression\">".3812$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3813-checked =>$search_use_regexp) .3814"</span>".3815"</div>".3816$cgi->end_form() ."\n";3817}38183819sub git_header_html {3820my$status=shift||"200 OK";3821my$expires=shift;3822my%opts=@_;38233824my$title= get_page_title();3825my$content_type= get_content_type_html();3826print$cgi->header(-type=>$content_type, -charset =>'utf-8',3827-status=>$status, -expires =>$expires)3828unless($opts{'-no_http_header'});3829my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3830print<<EOF;3831<?xml version="1.0" encoding="utf-8"?>3832<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3833<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3834<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3835<!-- git core binaries version$git_version-->3836<head>3837<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3838<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3839<meta name="robots" content="index, nofollow"/>3840<title>$title</title>3841EOF3842# the stylesheet, favicon etc urls won't work correctly with path_info3843# unless we set the appropriate base URL3844if($ENV{'PATH_INFO'}) {3845print"<base href=\"".esc_url($base_url)."\"/>\n";3846}3847 print_header_links($status);3848print"</head>\n".3849"<body>\n";38503851if(defined$site_header&& -f $site_header) {3852 insert_file($site_header);3853}38543855print"<div class=\"page_header\">\n";3856if(defined$logo) {3857print$cgi->a({-href => esc_url($logo_url),3858-title =>$logo_label},3859$cgi->img({-src => esc_url($logo),3860-width =>72, -height =>27,3861-alt =>"git",3862-class=>"logo"}));3863}3864 print_nav_breadcrumbs(%opts);3865print"</div>\n";38663867my$have_search= gitweb_check_feature('search');3868if(defined$project&&$have_search) {3869 print_search_form();3870}3871}38723873sub git_footer_html {3874my$feed_class='rss_logo';38753876print"<div class=\"page_footer\">\n";3877if(defined$project) {3878my$descr= git_get_project_description($project);3879if(defined$descr) {3880print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3881}38823883my%href_params= get_feed_info();3884if(!%href_params) {3885$feed_class.=' generic';3886}3887$href_params{'-title'} ||='log';38883889foreachmy$format(qw(RSS Atom)) {3890$href_params{'action'} =lc($format);3891print$cgi->a({-href => href(%href_params),3892-title =>"$href_params{'-title'}$formatfeed",3893-class=>$feed_class},$format)."\n";3894}38953896}else{3897print$cgi->a({-href => href(project=>undef, action=>"opml"),3898-class=>$feed_class},"OPML") ." ";3899print$cgi->a({-href => href(project=>undef, action=>"project_index"),3900-class=>$feed_class},"TXT") ."\n";3901}3902print"</div>\n";# class="page_footer"39033904if(defined$t0&& gitweb_check_feature('timed')) {3905print"<div id=\"generating_info\">\n";3906print'This page took '.3907'<span id="generating_time" class="time_span">'.3908 tv_interval($t0, [ gettimeofday() ]).3909' seconds </span>'.3910' and '.3911'<span id="generating_cmd">'.3912$number_of_git_cmds.3913'</span> git commands '.3914" to generate.\n";3915print"</div>\n";# class="page_footer"3916}39173918if(defined$site_footer&& -f $site_footer) {3919 insert_file($site_footer);3920}39213922print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;3923if(defined$action&&3924$actioneq'blame_incremental') {3925print qq!<script type="text/javascript">\n!.3926 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.3927 qq!"!. href() .qq!");\n!.3928 qq!</script>\n!;3929}else{3930my($jstimezone,$tz_cookie,$datetime_class) =3931 gitweb_get_feature('javascript-timezone');39323933print qq!<script type="text/javascript">\n!.3934 qq!window.onload = function () {\n!;3935if(gitweb_check_feature('javascript-actions')) {3936print qq! fixLinks();\n!;3937}3938if($jstimezone&&$tz_cookie&&$datetime_class) {3939print qq! var tz_cookie = { name:'$tz_cookie', expires:14, path:'/'};\n!.# in days3940 qq! onloadTZSetup('$jstimezone', tz_cookie,'$datetime_class');\n!;3941}3942print qq!};\n!.3943 qq!</script>\n!;3944}39453946print"</body>\n".3947"</html>";3948}39493950# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])3951# Example: die_error(404, 'Hash not found')3952# By convention, use the following status codes (as defined in RFC 2616):3953# 400: Invalid or missing CGI parameters, or3954# requested object exists but has wrong type.3955# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3956# this server or project.3957# 404: Requested object/revision/project doesn't exist.3958# 500: The server isn't configured properly, or3959# an internal error occurred (e.g. failed assertions caused by bugs), or3960# an unknown error occurred (e.g. the git binary died unexpectedly).3961# 503: The server is currently unavailable (because it is overloaded,3962# or down for maintenance). Generally, this is a temporary state.3963sub die_error {3964my$status=shift||500;3965my$error= esc_html(shift) ||"Internal Server Error";3966my$extra=shift;3967my%opts=@_;39683969my%http_responses= (3970400=>'400 Bad Request',3971403=>'403 Forbidden',3972404=>'404 Not Found',3973500=>'500 Internal Server Error',3974503=>'503 Service Unavailable',3975);3976 git_header_html($http_responses{$status},undef,%opts);3977print<<EOF;3978<div class="page_body">3979<br /><br />3980$status-$error3981<br />3982EOF3983if(defined$extra) {3984print"<hr />\n".3985"$extra\n";3986}3987print"</div>\n";39883989 git_footer_html();3990goto DONE_GITWEB3991unless($opts{'-error_handler'});3992}39933994## ----------------------------------------------------------------------3995## functions printing or outputting HTML: navigation39963997sub git_print_page_nav {3998my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;3999$extra=''if!defined$extra;# pager or formats40004001my@navs=qw(summary shortlog log commit commitdiff tree);4002if($suppress) {4003@navs=grep{$_ne$suppress}@navs;4004}40054006my%arg=map{$_=> {action=>$_} }@navs;4007if(defined$head) {4008for(qw(commit commitdiff)) {4009$arg{$_}{'hash'} =$head;4010}4011if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {4012for(qw(shortlog log)) {4013$arg{$_}{'hash'} =$head;4014}4015}4016}40174018$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;4019$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;40204021my@actions= gitweb_get_feature('actions');4022my%repl= (4023'%'=>'%',4024'n'=>$project,# project name4025'f'=>$git_dir,# project path within filesystem4026'h'=>$treehead||'',# current hash ('h' parameter)4027'b'=>$treebase||'',# hash base ('hb' parameter)4028);4029while(@actions) {4030my($label,$link,$pos) =splice(@actions,0,3);4031# insert4032@navs=map{$_eq$pos? ($_,$label) :$_}@navs;4033# munch munch4034$link=~s/%([%nfhb])/$repl{$1}/g;4035$arg{$label}{'_href'} =$link;4036}40374038print"<div class=\"page_nav\">\n".4039(join" | ",4040map{$_eq$current?4041$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4042}@navs);4043print"<br/>\n$extra<br/>\n".4044"</div>\n";4045}40464047# returns a submenu for the nagivation of the refs views (tags, heads,4048# remotes) with the current view disabled and the remotes view only4049# available if the feature is enabled4050sub format_ref_views {4051my($current) =@_;4052my@ref_views=qw{tags heads};4053push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4054returnjoin" | ",map{4055$_eq$current?$_:4056$cgi->a({-href => href(action=>$_)},$_)4057}@ref_views4058}40594060sub format_paging_nav {4061my($action,$page,$has_next_link) =@_;4062my$paging_nav;406340644065if($page>0) {4066$paging_nav.=4067$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4068" ⋅ ".4069$cgi->a({-href => href(-replay=>1, page=>$page-1),4070-accesskey =>"p", -title =>"Alt-p"},"prev");4071}else{4072$paging_nav.="first ⋅ prev";4073}40744075if($has_next_link) {4076$paging_nav.=" ⋅ ".4077$cgi->a({-href => href(-replay=>1, page=>$page+1),4078-accesskey =>"n", -title =>"Alt-n"},"next");4079}else{4080$paging_nav.=" ⋅ next";4081}40824083return$paging_nav;4084}40854086## ......................................................................4087## functions printing or outputting HTML: div40884089sub git_print_header_div {4090my($action,$title,$hash,$hash_base) =@_;4091my%args= ();40924093$args{'action'} =$action;4094$args{'hash'} =$hashif$hash;4095$args{'hash_base'} =$hash_baseif$hash_base;40964097print"<div class=\"header\">\n".4098$cgi->a({-href => href(%args), -class=>"title"},4099$title?$title:$action) .4100"\n</div>\n";4101}41024103sub format_repo_url {4104my($name,$url) =@_;4105return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4106}41074108# Group output by placing it in a DIV element and adding a header.4109# Options for start_div() can be provided by passing a hash reference as the4110# first parameter to the function.4111# Options to git_print_header_div() can be provided by passing an array4112# reference. This must follow the options to start_div if they are present.4113# The content can be a scalar, which is output as-is, a scalar reference, which4114# is output after html escaping, an IO handle passed either as *handle or4115# *handle{IO}, or a function reference. In the latter case all following4116# parameters will be taken as argument to the content function call.4117sub git_print_section {4118my($div_args,$header_args,$content);4119my$arg=shift;4120if(ref($arg)eq'HASH') {4121$div_args=$arg;4122$arg=shift;4123}4124if(ref($arg)eq'ARRAY') {4125$header_args=$arg;4126$arg=shift;4127}4128$content=$arg;41294130print$cgi->start_div($div_args);4131 git_print_header_div(@$header_args);41324133if(ref($content)eq'CODE') {4134$content->(@_);4135}elsif(ref($content)eq'SCALAR') {4136print esc_html($$content);4137}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4138print<$content>;4139}elsif(!ref($content) &&defined($content)) {4140print$content;4141}41424143print$cgi->end_div;4144}41454146sub format_timestamp_html {4147my$date=shift;4148my$strtime=$date->{'rfc2822'};41494150my(undef,undef,$datetime_class) =4151 gitweb_get_feature('javascript-timezone');4152if($datetime_class) {4153$strtime= qq!<span class="$datetime_class">$strtime</span>!;4154}41554156my$localtime_format='(%02d:%02d%s)';4157if($date->{'hour_local'} <6) {4158$localtime_format='(<span class="atnight">%02d:%02d</span>%s)';4159}4160$strtime.=' '.4161sprintf($localtime_format,4162$date->{'hour_local'},$date->{'minute_local'},$date->{'tz_local'});41634164return$strtime;4165}41664167# Outputs the author name and date in long form4168sub git_print_authorship {4169my$co=shift;4170my%opts=@_;4171my$tag=$opts{-tag} ||'div';4172my$author=$co->{'author_name'};41734174my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4175print"<$tagclass=\"author_date\">".4176 format_search_author($author,"author", esc_html($author)) .4177" [".format_timestamp_html(\%ad)."]".4178 git_get_avatar($co->{'author_email'}, -pad_before =>1) .4179"</$tag>\n";4180}41814182# Outputs table rows containing the full author or committer information,4183# in the format expected for 'commit' view (& similar).4184# Parameters are a commit hash reference, followed by the list of people4185# to output information for. If the list is empty it defaults to both4186# author and committer.4187sub git_print_authorship_rows {4188my$co=shift;4189# too bad we can't use @people = @_ || ('author', 'committer')4190my@people=@_;4191@people= ('author','committer')unless@people;4192foreachmy$who(@people) {4193my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4194print"<tr><td>$who</td><td>".4195 format_search_author($co->{"${who}_name"},$who,4196 esc_html($co->{"${who}_name"})) ." ".4197 format_search_author($co->{"${who}_email"},$who,4198 esc_html("<".$co->{"${who}_email"} .">")) .4199"</td><td rowspan=\"2\">".4200 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4201"</td></tr>\n".4202"<tr>".4203"<td></td><td>".4204 format_timestamp_html(\%wd) .4205"</td>".4206"</tr>\n";4207}4208}42094210sub git_print_page_path {4211my$name=shift;4212my$type=shift;4213my$hb=shift;421442154216print"<div class=\"page_path\">";4217print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4218-title =>'tree root'}, to_utf8("[$project]"));4219print" / ";4220if(defined$name) {4221my@dirname=split'/',$name;4222my$basename=pop@dirname;4223my$fullname='';42244225foreachmy$dir(@dirname) {4226$fullname.= ($fullname?'/':'') .$dir;4227print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4228 hash_base=>$hb),4229-title =>$fullname}, esc_path($dir));4230print" / ";4231}4232if(defined$type&&$typeeq'blob') {4233print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4234 hash_base=>$hb),4235-title =>$name}, esc_path($basename));4236}elsif(defined$type&&$typeeq'tree') {4237print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4238 hash_base=>$hb),4239-title =>$name}, esc_path($basename));4240print" / ";4241}else{4242print esc_path($basename);4243}4244}4245print"<br/></div>\n";4246}42474248sub git_print_log {4249my$log=shift;4250my%opts=@_;42514252if($opts{'-remove_title'}) {4253# remove title, i.e. first line of log4254shift@$log;4255}4256# remove leading empty lines4257while(defined$log->[0] &&$log->[0]eq"") {4258shift@$log;4259}42604261# print log4262my$signoff=0;4263my$empty=0;4264foreachmy$line(@$log) {4265if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {4266$signoff=1;4267$empty=0;4268if(!$opts{'-remove_signoff'}) {4269print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4270next;4271}else{4272# remove signoff lines4273next;4274}4275}else{4276$signoff=0;4277}42784279# print only one empty line4280# do not print empty line after signoff4281if($lineeq"") {4282next if($empty||$signoff);4283$empty=1;4284}else{4285$empty=0;4286}42874288print format_log_line_html($line) ."<br/>\n";4289}42904291if($opts{'-final_empty_line'}) {4292# end with single empty line4293print"<br/>\n"unless$empty;4294}4295}42964297# return link target (what link points to)4298sub git_get_link_target {4299my$hash=shift;4300my$link_target;43014302# read link4303open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4304orreturn;4305{4306local$/=undef;4307$link_target= <$fd>;4308}4309close$fd4310orreturn;43114312return$link_target;4313}43144315# given link target, and the directory (basedir) the link is in,4316# return target of link relative to top directory (top tree);4317# return undef if it is not possible (including absolute links).4318sub normalize_link_target {4319my($link_target,$basedir) =@_;43204321# absolute symlinks (beginning with '/') cannot be normalized4322return if(substr($link_target,0,1)eq'/');43234324# normalize link target to path from top (root) tree (dir)4325my$path;4326if($basedir) {4327$path=$basedir.'/'.$link_target;4328}else{4329# we are in top (root) tree (dir)4330$path=$link_target;4331}43324333# remove //, /./, and /../4334my@path_parts;4335foreachmy$part(split('/',$path)) {4336# discard '.' and ''4337next if(!$part||$parteq'.');4338# handle '..'4339if($parteq'..') {4340if(@path_parts) {4341pop@path_parts;4342}else{4343# link leads outside repository (outside top dir)4344return;4345}4346}else{4347push@path_parts,$part;4348}4349}4350$path=join('/',@path_parts);43514352return$path;4353}43544355# print tree entry (row of git_tree), but without encompassing <tr> element4356sub git_print_tree_entry {4357my($t,$basedir,$hash_base,$have_blame) =@_;43584359my%base_key= ();4360$base_key{'hash_base'} =$hash_baseifdefined$hash_base;43614362# The format of a table row is: mode list link. Where mode is4363# the mode of the entry, list is the name of the entry, an href,4364# and link is the action links of the entry.43654366print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4367if(exists$t->{'size'}) {4368print"<td class=\"size\">$t->{'size'}</td>\n";4369}4370if($t->{'type'}eq"blob") {4371print"<td class=\"list\">".4372$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4373 file_name=>"$basedir$t->{'name'}",%base_key),4374-class=>"list"}, esc_path($t->{'name'}));4375if(S_ISLNK(oct$t->{'mode'})) {4376my$link_target= git_get_link_target($t->{'hash'});4377if($link_target) {4378my$norm_target= normalize_link_target($link_target,$basedir);4379if(defined$norm_target) {4380print" -> ".4381$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4382 file_name=>$norm_target),4383-title =>$norm_target}, esc_path($link_target));4384}else{4385print" -> ". esc_path($link_target);4386}4387}4388}4389print"</td>\n";4390print"<td class=\"link\">";4391print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4392 file_name=>"$basedir$t->{'name'}",%base_key)},4393"blob");4394if($have_blame) {4395print" | ".4396$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4397 file_name=>"$basedir$t->{'name'}",%base_key)},4398"blame");4399}4400if(defined$hash_base) {4401print" | ".4402$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4403 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4404"history");4405}4406print" | ".4407$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4408 file_name=>"$basedir$t->{'name'}")},4409"raw");4410print"</td>\n";44114412}elsif($t->{'type'}eq"tree") {4413print"<td class=\"list\">";4414print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4415 file_name=>"$basedir$t->{'name'}",4416%base_key)},4417 esc_path($t->{'name'}));4418print"</td>\n";4419print"<td class=\"link\">";4420print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4421 file_name=>"$basedir$t->{'name'}",4422%base_key)},4423"tree");4424if(defined$hash_base) {4425print" | ".4426$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4427 file_name=>"$basedir$t->{'name'}")},4428"history");4429}4430print"</td>\n";4431}else{4432# unknown object: we can only present history for it4433# (this includes 'commit' object, i.e. submodule support)4434print"<td class=\"list\">".4435 esc_path($t->{'name'}) .4436"</td>\n";4437print"<td class=\"link\">";4438if(defined$hash_base) {4439print$cgi->a({-href => href(action=>"history",4440 hash_base=>$hash_base,4441 file_name=>"$basedir$t->{'name'}")},4442"history");4443}4444print"</td>\n";4445}4446}44474448## ......................................................................4449## functions printing large fragments of HTML44504451# get pre-image filenames for merge (combined) diff4452sub fill_from_file_info {4453my($diff,@parents) =@_;44544455$diff->{'from_file'} = [ ];4456$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4457for(my$i=0;$i<$diff->{'nparents'};$i++) {4458if($diff->{'status'}[$i]eq'R'||4459$diff->{'status'}[$i]eq'C') {4460$diff->{'from_file'}[$i] =4461 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4462}4463}44644465return$diff;4466}44674468# is current raw difftree line of file deletion4469sub is_deleted {4470my$diffinfo=shift;44714472return$diffinfo->{'to_id'}eq('0' x 40);4473}44744475# does patch correspond to [previous] difftree raw line4476# $diffinfo - hashref of parsed raw diff format4477# $patchinfo - hashref of parsed patch diff format4478# (the same keys as in $diffinfo)4479sub is_patch_split {4480my($diffinfo,$patchinfo) =@_;44814482returndefined$diffinfo&&defined$patchinfo4483&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4484}448544864487sub git_difftree_body {4488my($difftree,$hash,@parents) =@_;4489my($parent) =$parents[0];4490my$have_blame= gitweb_check_feature('blame');4491print"<div class=\"list_head\">\n";4492if($#{$difftree} >10) {4493print(($#{$difftree} +1) ." files changed:\n");4494}4495print"</div>\n";44964497print"<table class=\"".4498(@parents>1?"combined ":"") .4499"diff_tree\">\n";45004501# header only for combined diff in 'commitdiff' view4502my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4503if($has_header) {4504# table header4505print"<thead><tr>\n".4506"<th></th><th></th>\n";# filename, patchN link4507for(my$i=0;$i<@parents;$i++) {4508my$par=$parents[$i];4509print"<th>".4510$cgi->a({-href => href(action=>"commitdiff",4511 hash=>$hash, hash_parent=>$par),4512-title =>'commitdiff to parent number '.4513($i+1) .': '.substr($par,0,7)},4514$i+1) .4515" </th>\n";4516}4517print"</tr></thead>\n<tbody>\n";4518}45194520my$alternate=1;4521my$patchno=0;4522foreachmy$line(@{$difftree}) {4523my$diff= parsed_difftree_line($line);45244525if($alternate) {4526print"<tr class=\"dark\">\n";4527}else{4528print"<tr class=\"light\">\n";4529}4530$alternate^=1;45314532if(exists$diff->{'nparents'}) {# combined diff45334534 fill_from_file_info($diff,@parents)4535unlessexists$diff->{'from_file'};45364537if(!is_deleted($diff)) {4538# file exists in the result (child) commit4539print"<td>".4540$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4541 file_name=>$diff->{'to_file'},4542 hash_base=>$hash),4543-class=>"list"}, esc_path($diff->{'to_file'})) .4544"</td>\n";4545}else{4546print"<td>".4547 esc_path($diff->{'to_file'}) .4548"</td>\n";4549}45504551if($actioneq'commitdiff') {4552# link to patch4553$patchno++;4554print"<td class=\"link\">".4555$cgi->a({-href => href(-anchor=>"patch$patchno")},4556"patch") .4557" | ".4558"</td>\n";4559}45604561my$has_history=0;4562my$not_deleted=0;4563for(my$i=0;$i<$diff->{'nparents'};$i++) {4564my$hash_parent=$parents[$i];4565my$from_hash=$diff->{'from_id'}[$i];4566my$from_path=$diff->{'from_file'}[$i];4567my$status=$diff->{'status'}[$i];45684569$has_history||= ($statusne'A');4570$not_deleted||= ($statusne'D');45714572if($statuseq'A') {4573print"<td class=\"link\"align=\"right\"> | </td>\n";4574}elsif($statuseq'D') {4575print"<td class=\"link\">".4576$cgi->a({-href => href(action=>"blob",4577 hash_base=>$hash,4578 hash=>$from_hash,4579 file_name=>$from_path)},4580"blob". ($i+1)) .4581" | </td>\n";4582}else{4583if($diff->{'to_id'}eq$from_hash) {4584print"<td class=\"link nochange\">";4585}else{4586print"<td class=\"link\">";4587}4588print$cgi->a({-href => href(action=>"blobdiff",4589 hash=>$diff->{'to_id'},4590 hash_parent=>$from_hash,4591 hash_base=>$hash,4592 hash_parent_base=>$hash_parent,4593 file_name=>$diff->{'to_file'},4594 file_parent=>$from_path)},4595"diff". ($i+1)) .4596" | </td>\n";4597}4598}45994600print"<td class=\"link\">";4601if($not_deleted) {4602print$cgi->a({-href => href(action=>"blob",4603 hash=>$diff->{'to_id'},4604 file_name=>$diff->{'to_file'},4605 hash_base=>$hash)},4606"blob");4607print" | "if($has_history);4608}4609if($has_history) {4610print$cgi->a({-href => href(action=>"history",4611 file_name=>$diff->{'to_file'},4612 hash_base=>$hash)},4613"history");4614}4615print"</td>\n";46164617print"</tr>\n";4618next;# instead of 'else' clause, to avoid extra indent4619}4620# else ordinary diff46214622my($to_mode_oct,$to_mode_str,$to_file_type);4623my($from_mode_oct,$from_mode_str,$from_file_type);4624if($diff->{'to_mode'}ne('0' x 6)) {4625$to_mode_oct=oct$diff->{'to_mode'};4626if(S_ISREG($to_mode_oct)) {# only for regular file4627$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4628}4629$to_file_type= file_type($diff->{'to_mode'});4630}4631if($diff->{'from_mode'}ne('0' x 6)) {4632$from_mode_oct=oct$diff->{'from_mode'};4633if(S_ISREG($from_mode_oct)) {# only for regular file4634$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4635}4636$from_file_type= file_type($diff->{'from_mode'});4637}46384639if($diff->{'status'}eq"A") {# created4640my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4641$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4642$mode_chng.="]</span>";4643print"<td>";4644print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4645 hash_base=>$hash, file_name=>$diff->{'file'}),4646-class=>"list"}, esc_path($diff->{'file'}));4647print"</td>\n";4648print"<td>$mode_chng</td>\n";4649print"<td class=\"link\">";4650if($actioneq'commitdiff') {4651# link to patch4652$patchno++;4653print$cgi->a({-href => href(-anchor=>"patch$patchno")},4654"patch") .4655" | ";4656}4657print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4658 hash_base=>$hash, file_name=>$diff->{'file'})},4659"blob");4660print"</td>\n";46614662}elsif($diff->{'status'}eq"D") {# deleted4663my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4664print"<td>";4665print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4666 hash_base=>$parent, file_name=>$diff->{'file'}),4667-class=>"list"}, esc_path($diff->{'file'}));4668print"</td>\n";4669print"<td>$mode_chng</td>\n";4670print"<td class=\"link\">";4671if($actioneq'commitdiff') {4672# link to patch4673$patchno++;4674print$cgi->a({-href => href(-anchor=>"patch$patchno")},4675"patch") .4676" | ";4677}4678print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4679 hash_base=>$parent, file_name=>$diff->{'file'})},4680"blob") ." | ";4681if($have_blame) {4682print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4683 file_name=>$diff->{'file'})},4684"blame") ." | ";4685}4686print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4687 file_name=>$diff->{'file'})},4688"history");4689print"</td>\n";46904691}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4692my$mode_chnge="";4693if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4694$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4695if($from_file_typene$to_file_type) {4696$mode_chnge.=" from$from_file_typeto$to_file_type";4697}4698if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4699if($from_mode_str&&$to_mode_str) {4700$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4701}elsif($to_mode_str) {4702$mode_chnge.=" mode:$to_mode_str";4703}4704}4705$mode_chnge.="]</span>\n";4706}4707print"<td>";4708print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4709 hash_base=>$hash, file_name=>$diff->{'file'}),4710-class=>"list"}, esc_path($diff->{'file'}));4711print"</td>\n";4712print"<td>$mode_chnge</td>\n";4713print"<td class=\"link\">";4714if($actioneq'commitdiff') {4715# link to patch4716$patchno++;4717print$cgi->a({-href => href(-anchor=>"patch$patchno")},4718"patch") .4719" | ";4720}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4721# "commit" view and modified file (not onlu mode changed)4722print$cgi->a({-href => href(action=>"blobdiff",4723 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4724 hash_base=>$hash, hash_parent_base=>$parent,4725 file_name=>$diff->{'file'})},4726"diff") .4727" | ";4728}4729print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4730 hash_base=>$hash, file_name=>$diff->{'file'})},4731"blob") ." | ";4732if($have_blame) {4733print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4734 file_name=>$diff->{'file'})},4735"blame") ." | ";4736}4737print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4738 file_name=>$diff->{'file'})},4739"history");4740print"</td>\n";47414742}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4743my%status_name= ('R'=>'moved','C'=>'copied');4744my$nstatus=$status_name{$diff->{'status'}};4745my$mode_chng="";4746if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4747# mode also for directories, so we cannot use $to_mode_str4748$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4749}4750print"<td>".4751$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4752 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4753-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4754"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4755$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4756 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4757-class=>"list"}, esc_path($diff->{'from_file'})) .4758" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4759"<td class=\"link\">";4760if($actioneq'commitdiff') {4761# link to patch4762$patchno++;4763print$cgi->a({-href => href(-anchor=>"patch$patchno")},4764"patch") .4765" | ";4766}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4767# "commit" view and modified file (not only pure rename or copy)4768print$cgi->a({-href => href(action=>"blobdiff",4769 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4770 hash_base=>$hash, hash_parent_base=>$parent,4771 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4772"diff") .4773" | ";4774}4775print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4776 hash_base=>$parent, file_name=>$diff->{'to_file'})},4777"blob") ." | ";4778if($have_blame) {4779print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4780 file_name=>$diff->{'to_file'})},4781"blame") ." | ";4782}4783print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4784 file_name=>$diff->{'to_file'})},4785"history");4786print"</td>\n";47874788}# we should not encounter Unmerged (U) or Unknown (X) status4789print"</tr>\n";4790}4791print"</tbody>"if$has_header;4792print"</table>\n";4793}47944795sub git_patchset_body {4796my($fd,$difftree,$hash,@hash_parents) =@_;4797my($hash_parent) =$hash_parents[0];47984799my$is_combined= (@hash_parents>1);4800my$patch_idx=0;4801my$patch_number=0;4802my$patch_line;4803my$diffinfo;4804my$to_name;4805my(%from,%to);48064807print"<div class=\"patchset\">\n";48084809# skip to first patch4810while($patch_line= <$fd>) {4811chomp$patch_line;48124813last if($patch_line=~m/^diff /);4814}48154816 PATCH:4817while($patch_line) {48184819# parse "git diff" header line4820if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4821# $1 is from_name, which we do not use4822$to_name= unquote($2);4823$to_name=~s!^b/!!;4824}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4825# $1 is 'cc' or 'combined', which we do not use4826$to_name= unquote($2);4827}else{4828$to_name=undef;4829}48304831# check if current patch belong to current raw line4832# and parse raw git-diff line if needed4833if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4834# this is continuation of a split patch4835print"<div class=\"patch cont\">\n";4836}else{4837# advance raw git-diff output if needed4838$patch_idx++ifdefined$diffinfo;48394840# read and prepare patch information4841$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);48424843# compact combined diff output can have some patches skipped4844# find which patch (using pathname of result) we are at now;4845if($is_combined) {4846while($to_namene$diffinfo->{'to_file'}) {4847print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4848 format_diff_cc_simplified($diffinfo,@hash_parents) .4849"</div>\n";# class="patch"48504851$patch_idx++;4852$patch_number++;48534854last if$patch_idx>$#$difftree;4855$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4856}4857}48584859# modifies %from, %to hashes4860 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);48614862# this is first patch for raw difftree line with $patch_idx index4863# we index @$difftree array from 0, but number patches from 14864print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4865}48664867# git diff header4868#assert($patch_line =~ m/^diff /) if DEBUG;4869#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4870$patch_number++;4871# print "git diff" header4872print format_git_diff_header_line($patch_line,$diffinfo,4873 \%from, \%to);48744875# print extended diff header4876print"<div class=\"diff extended_header\">\n";4877 EXTENDED_HEADER:4878while($patch_line= <$fd>) {4879chomp$patch_line;48804881last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);48824883print format_extended_diff_header_line($patch_line,$diffinfo,4884 \%from, \%to);4885}4886print"</div>\n";# class="diff extended_header"48874888# from-file/to-file diff header4889if(!$patch_line) {4890print"</div>\n";# class="patch"4891last PATCH;4892}4893next PATCH if($patch_line=~m/^diff /);4894#assert($patch_line =~ m/^---/) if DEBUG;48954896my$last_patch_line=$patch_line;4897$patch_line= <$fd>;4898chomp$patch_line;4899#assert($patch_line =~ m/^\+\+\+/) if DEBUG;49004901print format_diff_from_to_header($last_patch_line,$patch_line,4902$diffinfo, \%from, \%to,4903@hash_parents);49044905# the patch itself4906 LINE:4907while($patch_line= <$fd>) {4908chomp$patch_line;49094910next PATCH if($patch_line=~m/^diff /);49114912print format_diff_line($patch_line, \%from, \%to);4913}49144915}continue{4916print"</div>\n";# class="patch"4917}49184919# for compact combined (--cc) format, with chunk and patch simplification4920# the patchset might be empty, but there might be unprocessed raw lines4921for(++$patch_idxif$patch_number>0;4922$patch_idx<@$difftree;4923++$patch_idx) {4924# read and prepare patch information4925$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);49264927# generate anchor for "patch" links in difftree / whatchanged part4928print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4929 format_diff_cc_simplified($diffinfo,@hash_parents) .4930"</div>\n";# class="patch"49314932$patch_number++;4933}49344935if($patch_number==0) {4936if(@hash_parents>1) {4937print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4938}else{4939print"<div class=\"diff nodifferences\">No differences found</div>\n";4940}4941}49424943print"</div>\n";# class="patchset"4944}49454946# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49474948# fills project list info (age, description, owner, category, forks)4949# for each project in the list, removing invalid projects from4950# returned list4951# NOTE: modifies $projlist, but does not remove entries from it4952sub fill_project_list_info {4953my$projlist=shift;4954my@projects;49554956my$show_ctags= gitweb_check_feature('ctags');4957 PROJECT:4958foreachmy$pr(@$projlist) {4959my(@activity) = git_get_last_activity($pr->{'path'});4960unless(@activity) {4961next PROJECT;4962}4963($pr->{'age'},$pr->{'age_string'}) =@activity;4964if(!defined$pr->{'descr'}) {4965my$descr= git_get_project_description($pr->{'path'}) ||"";4966$descr= to_utf8($descr);4967$pr->{'descr_long'} =$descr;4968$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);4969}4970if(!defined$pr->{'owner'}) {4971$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";4972}4973if($show_ctags) {4974$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});4975}4976if($projects_list_group_categories&& !defined$pr->{'category'}) {4977my$cat= git_get_project_category($pr->{'path'}) ||4978$project_list_default_category;4979$pr->{'category'} = to_utf8($cat);4980}49814982push@projects,$pr;4983}49844985return@projects;4986}49874988sub sort_projects_list {4989my($projlist,$order) =@_;4990my@projects;49914992my%order_info= (4993 project => { key =>'path', type =>'str'},4994 descr => { key =>'descr_long', type =>'str'},4995 owner => { key =>'owner', type =>'str'},4996 age => { key =>'age', type =>'num'}4997);4998my$oi=$order_info{$order};4999return@$projlistunlessdefined$oi;5000if($oi->{'type'}eq'str') {5001@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@$projlist;5002}else{5003@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@$projlist;5004}50055006return@projects;5007}50085009# returns a hash of categories, containing the list of project5010# belonging to each category5011sub build_projlist_by_category {5012my($projlist,$from,$to) =@_;5013my%categories;50145015$from=0unlessdefined$from;5016$to=$#$projlistif(!defined$to||$#$projlist<$to);50175018for(my$i=$from;$i<=$to;$i++) {5019my$pr=$projlist->[$i];5020push@{$categories{$pr->{'category'} }},$pr;5021}50225023returnwantarray?%categories: \%categories;5024}50255026# print 'sort by' <th> element, generating 'sort by $name' replay link5027# if that order is not selected5028sub print_sort_th {5029print format_sort_th(@_);5030}50315032sub format_sort_th {5033my($name,$order,$header) =@_;5034my$sort_th="";5035$header||=ucfirst($name);50365037if($ordereq$name) {5038$sort_th.="<th>$header</th>\n";5039}else{5040$sort_th.="<th>".5041$cgi->a({-href => href(-replay=>1, order=>$name),5042-class=>"header"},$header) .5043"</th>\n";5044}50455046return$sort_th;5047}50485049sub git_project_list_rows {5050my($projlist,$from,$to,$check_forks) =@_;50515052$from=0unlessdefined$from;5053$to=$#$projlistif(!defined$to||$#$projlist<$to);50545055my$alternate=1;5056for(my$i=$from;$i<=$to;$i++) {5057my$pr=$projlist->[$i];50585059if($alternate) {5060print"<tr class=\"dark\">\n";5061}else{5062print"<tr class=\"light\">\n";5063}5064$alternate^=1;50655066if($check_forks) {5067print"<td>";5068if($pr->{'forks'}) {5069my$nforks=scalar@{$pr->{'forks'}};5070if($nforks>0) {5071print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5072-title =>"$nforksforks"},"+");5073}else{5074print$cgi->span({-title =>"$nforksforks"},"+");5075}5076}5077print"</td>\n";5078}5079print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5080-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".5081"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5082-class=>"list", -title =>$pr->{'descr_long'}},5083 esc_html($pr->{'descr'})) ."</td>\n".5084"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5085print"<td class=\"". age_class($pr->{'age'}) ."\">".5086(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".5087"<td class=\"link\">".5088$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5089$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5090$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5091$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5092($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5093"</td>\n".5094"</tr>\n";5095}5096}50975098sub git_project_list_body {5099# actually uses global variable $project5100my($projlist,$order,$from,$to,$extra,$no_header) =@_;5101my@projects=@$projlist;51025103my$check_forks= gitweb_check_feature('forks');5104my$show_ctags= gitweb_check_feature('ctags');5105my$tagfilter=$show_ctags?$cgi->param('by_tag') :undef;5106$check_forks=undef5107if($tagfilter||$searchtext);51085109# filtering out forks before filling info allows to do less work5110@projects= filter_forks_from_projects_list(\@projects)5111if($check_forks);5112@projects= fill_project_list_info(\@projects);5113# searching projects require filling to be run before it5114@projects= search_projects_list(\@projects,5115'searchtext'=>$searchtext,5116'tagfilter'=>$tagfilter)5117if($tagfilter||$searchtext);51185119$order||=$default_projects_order;5120$from=0unlessdefined$from;5121$to=$#projectsif(!defined$to||$#projects<$to);51225123# short circuit5124if($from>$to) {5125print"<center>\n".5126"<b>No such projects found</b><br />\n".5127"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5128"</center>\n<br />\n";5129return;5130}51315132@projects= sort_projects_list(\@projects,$order);51335134if($show_ctags) {5135my$ctags= git_gather_all_ctags(\@projects);5136my$cloud= git_populate_project_tagcloud($ctags);5137print git_show_project_tagcloud($cloud,64);5138}51395140print"<table class=\"project_list\">\n";5141unless($no_header) {5142print"<tr>\n";5143if($check_forks) {5144print"<th></th>\n";5145}5146 print_sort_th('project',$order,'Project');5147 print_sort_th('descr',$order,'Description');5148 print_sort_th('owner',$order,'Owner');5149 print_sort_th('age',$order,'Last Change');5150print"<th></th>\n".# for links5151"</tr>\n";5152}51535154if($projects_list_group_categories) {5155# only display categories with projects in the $from-$to window5156@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5157my%categories= build_projlist_by_category(\@projects,$from,$to);5158foreachmy$cat(sort keys%categories) {5159unless($cateq"") {5160print"<tr>\n";5161if($check_forks) {5162print"<td></td>\n";5163}5164print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5165print"</tr>\n";5166}51675168 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5169}5170}else{5171 git_project_list_rows(\@projects,$from,$to,$check_forks);5172}51735174if(defined$extra) {5175print"<tr>\n";5176if($check_forks) {5177print"<td></td>\n";5178}5179print"<td colspan=\"5\">$extra</td>\n".5180"</tr>\n";5181}5182print"</table>\n";5183}51845185sub git_log_body {5186# uses global variable $project5187my($commitlist,$from,$to,$refs,$extra) =@_;51885189$from=0unlessdefined$from;5190$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);51915192for(my$i=0;$i<=$to;$i++) {5193my%co= %{$commitlist->[$i]};5194next if!%co;5195my$commit=$co{'id'};5196my$ref= format_ref_marker($refs,$commit);5197 git_print_header_div('commit',5198"<span class=\"age\">$co{'age_string'}</span>".5199 esc_html($co{'title'}) .$ref,5200$commit);5201print"<div class=\"title_text\">\n".5202"<div class=\"log_link\">\n".5203$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5204" | ".5205$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5206" | ".5207$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5208"<br/>\n".5209"</div>\n";5210 git_print_authorship(\%co, -tag =>'span');5211print"<br/>\n</div>\n";52125213print"<div class=\"log_body\">\n";5214 git_print_log($co{'comment'}, -final_empty_line=>1);5215print"</div>\n";5216}5217if($extra) {5218print"<div class=\"page_nav\">\n";5219print"$extra\n";5220print"</div>\n";5221}5222}52235224sub git_shortlog_body {5225# uses global variable $project5226my($commitlist,$from,$to,$refs,$extra) =@_;52275228$from=0unlessdefined$from;5229$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);52305231print"<table class=\"shortlog\">\n";5232my$alternate=1;5233for(my$i=$from;$i<=$to;$i++) {5234my%co= %{$commitlist->[$i]};5235my$commit=$co{'id'};5236my$ref= format_ref_marker($refs,$commit);5237if($alternate) {5238print"<tr class=\"dark\">\n";5239}else{5240print"<tr class=\"light\">\n";5241}5242$alternate^=1;5243# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5244print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5245 format_author_html('td', \%co,10) ."<td>";5246print format_subject_html($co{'title'},$co{'title_short'},5247 href(action=>"commit", hash=>$commit),$ref);5248print"</td>\n".5249"<td class=\"link\">".5250$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5251$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5252$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5253my$snapshot_links= format_snapshot_links($commit);5254if(defined$snapshot_links) {5255print" | ".$snapshot_links;5256}5257print"</td>\n".5258"</tr>\n";5259}5260if(defined$extra) {5261print"<tr>\n".5262"<td colspan=\"4\">$extra</td>\n".5263"</tr>\n";5264}5265print"</table>\n";5266}52675268sub git_history_body {5269# Warning: assumes constant type (blob or tree) during history5270my($commitlist,$from,$to,$refs,$extra,5271$file_name,$file_hash,$ftype) =@_;52725273$from=0unlessdefined$from;5274$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});52755276print"<table class=\"history\">\n";5277my$alternate=1;5278for(my$i=$from;$i<=$to;$i++) {5279my%co= %{$commitlist->[$i]};5280if(!%co) {5281next;5282}5283my$commit=$co{'id'};52845285my$ref= format_ref_marker($refs,$commit);52865287if($alternate) {5288print"<tr class=\"dark\">\n";5289}else{5290print"<tr class=\"light\">\n";5291}5292$alternate^=1;5293print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5294# shortlog: format_author_html('td', \%co, 10)5295 format_author_html('td', \%co,15,3) ."<td>";5296# originally git_history used chop_str($co{'title'}, 50)5297print format_subject_html($co{'title'},$co{'title_short'},5298 href(action=>"commit", hash=>$commit),$ref);5299print"</td>\n".5300"<td class=\"link\">".5301$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5302$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");53035304if($ftypeeq'blob') {5305my$blob_current=$file_hash;5306my$blob_parent= git_get_hash_by_path($commit,$file_name);5307if(defined$blob_current&&defined$blob_parent&&5308$blob_currentne$blob_parent) {5309print" | ".5310$cgi->a({-href => href(action=>"blobdiff",5311 hash=>$blob_current, hash_parent=>$blob_parent,5312 hash_base=>$hash_base, hash_parent_base=>$commit,5313 file_name=>$file_name)},5314"diff to current");5315}5316}5317print"</td>\n".5318"</tr>\n";5319}5320if(defined$extra) {5321print"<tr>\n".5322"<td colspan=\"4\">$extra</td>\n".5323"</tr>\n";5324}5325print"</table>\n";5326}53275328sub git_tags_body {5329# uses global variable $project5330my($taglist,$from,$to,$extra) =@_;5331$from=0unlessdefined$from;5332$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);53335334print"<table class=\"tags\">\n";5335my$alternate=1;5336for(my$i=$from;$i<=$to;$i++) {5337my$entry=$taglist->[$i];5338my%tag=%$entry;5339my$comment=$tag{'subject'};5340my$comment_short;5341if(defined$comment) {5342$comment_short= chop_str($comment,30,5);5343}5344if($alternate) {5345print"<tr class=\"dark\">\n";5346}else{5347print"<tr class=\"light\">\n";5348}5349$alternate^=1;5350if(defined$tag{'age'}) {5351print"<td><i>$tag{'age'}</i></td>\n";5352}else{5353print"<td></td>\n";5354}5355print"<td>".5356$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5357-class=>"list name"}, esc_html($tag{'name'})) .5358"</td>\n".5359"<td>";5360if(defined$comment) {5361print format_subject_html($comment,$comment_short,5362 href(action=>"tag", hash=>$tag{'id'}));5363}5364print"</td>\n".5365"<td class=\"selflink\">";5366if($tag{'type'}eq"tag") {5367print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");5368}else{5369print" ";5370}5371print"</td>\n".5372"<td class=\"link\">"." | ".5373$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});5374if($tag{'reftype'}eq"commit") {5375print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .5376" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");5377}elsif($tag{'reftype'}eq"blob") {5378print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");5379}5380print"</td>\n".5381"</tr>";5382}5383if(defined$extra) {5384print"<tr>\n".5385"<td colspan=\"5\">$extra</td>\n".5386"</tr>\n";5387}5388print"</table>\n";5389}53905391sub git_heads_body {5392# uses global variable $project5393my($headlist,$head,$from,$to,$extra) =@_;5394$from=0unlessdefined$from;5395$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);53965397print"<table class=\"heads\">\n";5398my$alternate=1;5399for(my$i=$from;$i<=$to;$i++) {5400my$entry=$headlist->[$i];5401my%ref=%$entry;5402my$curr=$ref{'id'}eq$head;5403if($alternate) {5404print"<tr class=\"dark\">\n";5405}else{5406print"<tr class=\"light\">\n";5407}5408$alternate^=1;5409print"<td><i>$ref{'age'}</i></td>\n".5410($curr?"<td class=\"current_head\">":"<td>") .5411$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),5412-class=>"list name"},esc_html($ref{'name'})) .5413"</td>\n".5414"<td class=\"link\">".5415$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".5416$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".5417$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .5418"</td>\n".5419"</tr>";5420}5421if(defined$extra) {5422print"<tr>\n".5423"<td colspan=\"3\">$extra</td>\n".5424"</tr>\n";5425}5426print"</table>\n";5427}54285429# Display a single remote block5430sub git_remote_block {5431my($remote,$rdata,$limit,$head) =@_;54325433my$heads=$rdata->{'heads'};5434my$fetch=$rdata->{'fetch'};5435my$push=$rdata->{'push'};54365437my$urls_table="<table class=\"projects_list\">\n";54385439if(defined$fetch) {5440if($fetcheq$push) {5441$urls_table.= format_repo_url("URL",$fetch);5442}else{5443$urls_table.= format_repo_url("Fetch URL",$fetch);5444$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;5445}5446}elsif(defined$push) {5447$urls_table.= format_repo_url("Push URL",$push);5448}else{5449$urls_table.= format_repo_url("","No remote URL");5450}54515452$urls_table.="</table>\n";54535454my$dots;5455if(defined$limit&&$limit<@$heads) {5456$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");5457}54585459print$urls_table;5460 git_heads_body($heads,$head,0,$limit,$dots);5461}54625463# Display a list of remote names with the respective fetch and push URLs5464sub git_remotes_list {5465my($remotedata,$limit) =@_;5466print"<table class=\"heads\">\n";5467my$alternate=1;5468my@remotes=sort keys%$remotedata;54695470my$limited=$limit&&$limit<@remotes;54715472$#remotes=$limit-1if$limited;54735474while(my$remote=shift@remotes) {5475my$rdata=$remotedata->{$remote};5476my$fetch=$rdata->{'fetch'};5477my$push=$rdata->{'push'};5478if($alternate) {5479print"<tr class=\"dark\">\n";5480}else{5481print"<tr class=\"light\">\n";5482}5483$alternate^=1;5484print"<td>".5485$cgi->a({-href=> href(action=>'remotes', hash=>$remote),5486-class=>"list name"},esc_html($remote)) .5487"</td>";5488print"<td class=\"link\">".5489(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .5490" | ".5491(defined$push?$cgi->a({-href=>$push},"push") :"push") .5492"</td>";54935494print"</tr>\n";5495}54965497if($limited) {5498print"<tr>\n".5499"<td colspan=\"3\">".5500$cgi->a({-href => href(action=>"remotes")},"...") .5501"</td>\n"."</tr>\n";5502}55035504print"</table>";5505}55065507# Display remote heads grouped by remote, unless there are too many5508# remotes, in which case we only display the remote names5509sub git_remotes_body {5510my($remotedata,$limit,$head) =@_;5511if($limitand$limit<keys%$remotedata) {5512 git_remotes_list($remotedata,$limit);5513}else{5514 fill_remote_heads($remotedata);5515while(my($remote,$rdata) =each%$remotedata) {5516 git_print_section({-class=>"remote", -id=>$remote},5517["remotes",$remote,$remote],sub{5518 git_remote_block($remote,$rdata,$limit,$head);5519});5520}5521}5522}55235524sub git_search_grep_body {5525my($commitlist,$from,$to,$extra) =@_;5526$from=0unlessdefined$from;5527$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);55285529print"<table class=\"commit_search\">\n";5530my$alternate=1;5531for(my$i=$from;$i<=$to;$i++) {5532my%co= %{$commitlist->[$i]};5533if(!%co) {5534next;5535}5536my$commit=$co{'id'};5537if($alternate) {5538print"<tr class=\"dark\">\n";5539}else{5540print"<tr class=\"light\">\n";5541}5542$alternate^=1;5543print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5544 format_author_html('td', \%co,15,5) .5545"<td>".5546$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5547-class=>"list subject"},5548 chop_and_escape_str($co{'title'},50) ."<br/>");5549my$comment=$co{'comment'};5550foreachmy$line(@$comment) {5551if($line=~m/^(.*?)($search_regexp)(.*)$/i) {5552my($lead,$match,$trail) = ($1,$2,$3);5553$match= chop_str($match,70,5,'center');5554my$contextlen=int((80-length($match))/2);5555$contextlen=30if($contextlen>30);5556$lead= chop_str($lead,$contextlen,10,'left');5557$trail= chop_str($trail,$contextlen,10,'right');55585559$lead= esc_html($lead);5560$match= esc_html($match);5561$trail= esc_html($trail);55625563print"$lead<span class=\"match\">$match</span>$trail<br />";5564}5565}5566print"</td>\n".5567"<td class=\"link\">".5568$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .5569" | ".5570$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .5571" | ".5572$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");5573print"</td>\n".5574"</tr>\n";5575}5576if(defined$extra) {5577print"<tr>\n".5578"<td colspan=\"3\">$extra</td>\n".5579"</tr>\n";5580}5581print"</table>\n";5582}55835584## ======================================================================5585## ======================================================================5586## actions55875588sub git_project_list {5589my$order=$input_params{'order'};5590if(defined$order&&$order!~m/none|project|descr|owner|age/) {5591 die_error(400,"Unknown order parameter");5592}55935594my@list= git_get_projects_list();5595if(!@list) {5596 die_error(404,"No projects found");5597}55985599 git_header_html();5600if(defined$home_text&& -f $home_text) {5601print"<div class=\"index_include\">\n";5602 insert_file($home_text);5603print"</div>\n";5604}5605print$cgi->startform(-method=>"get") .5606"<p class=\"projsearch\">Search:\n".5607$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".5608"</p>".5609$cgi->end_form() ."\n";5610 git_project_list_body(\@list,$order);5611 git_footer_html();5612}56135614sub git_forks {5615my$order=$input_params{'order'};5616if(defined$order&&$order!~m/none|project|descr|owner|age/) {5617 die_error(400,"Unknown order parameter");5618}56195620my@list= git_get_projects_list($project);5621if(!@list) {5622 die_error(404,"No forks found");5623}56245625 git_header_html();5626 git_print_page_nav('','');5627 git_print_header_div('summary',"$projectforks");5628 git_project_list_body(\@list,$order);5629 git_footer_html();5630}56315632sub git_project_index {5633my@projects= git_get_projects_list();5634if(!@projects) {5635 die_error(404,"No projects found");5636}56375638print$cgi->header(5639-type =>'text/plain',5640-charset =>'utf-8',5641-content_disposition =>'inline; filename="index.aux"');56425643foreachmy$pr(@projects) {5644if(!exists$pr->{'owner'}) {5645$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");5646}56475648my($path,$owner) = ($pr->{'path'},$pr->{'owner'});5649# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '5650$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5651$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5652$path=~s/ /\+/g;5653$owner=~s/ /\+/g;56545655print"$path$owner\n";5656}5657}56585659sub git_summary {5660my$descr= git_get_project_description($project) ||"none";5661my%co= parse_commit("HEAD");5662my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();5663my$head=$co{'id'};5664my$remote_heads= gitweb_check_feature('remote_heads');56655666my$owner= git_get_project_owner($project);56675668my$refs= git_get_references();5669# These get_*_list functions return one more to allow us to see if5670# there are more ...5671my@taglist= git_get_tags_list(16);5672my@headlist= git_get_heads_list(16);5673my%remotedata=$remote_heads? git_get_remotes_list() : ();5674my@forklist;5675my$check_forks= gitweb_check_feature('forks');56765677if($check_forks) {5678# find forks of a project5679@forklist= git_get_projects_list($project);5680# filter out forks of forks5681@forklist= filter_forks_from_projects_list(\@forklist)5682if(@forklist);5683}56845685 git_header_html();5686 git_print_page_nav('summary','',$head);56875688print"<div class=\"title\"> </div>\n";5689print"<table class=\"projects_list\">\n".5690"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".5691"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";5692if(defined$cd{'rfc2822'}) {5693print"<tr id=\"metadata_lchange\"><td>last change</td>".5694"<td>".format_timestamp_html(\%cd)."</td></tr>\n";5695}56965697# use per project git URL list in $projectroot/$project/cloneurl5698# or make project git URL from git base URL and project name5699my$url_tag="URL";5700my@url_list= git_get_project_url_list($project);5701@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;5702foreachmy$git_url(@url_list) {5703next unless$git_url;5704print format_repo_url($url_tag,$git_url);5705$url_tag="";5706}57075708# Tag cloud5709my$show_ctags= gitweb_check_feature('ctags');5710if($show_ctags) {5711my$ctags= git_get_project_ctags($project);5712if(%$ctags) {5713# without ability to add tags, don't show if there are none5714my$cloud= git_populate_project_tagcloud($ctags);5715print"<tr id=\"metadata_ctags\">".5716"<td>content tags</td>".5717"<td>".git_show_project_tagcloud($cloud,48)."</td>".5718"</tr>\n";5719}5720}57215722print"</table>\n";57235724# If XSS prevention is on, we don't include README.html.5725# TODO: Allow a readme in some safe format.5726if(!$prevent_xss&& -s "$projectroot/$project/README.html") {5727print"<div class=\"title\">readme</div>\n".5728"<div class=\"readme\">\n";5729 insert_file("$projectroot/$project/README.html");5730print"\n</div>\n";# class="readme"5731}57325733# we need to request one more than 16 (0..15) to check if5734# those 16 are all5735my@commitlist=$head? parse_commits($head,17) : ();5736if(@commitlist) {5737 git_print_header_div('shortlog');5738 git_shortlog_body(\@commitlist,0,15,$refs,5739$#commitlist<=15?undef:5740$cgi->a({-href => href(action=>"shortlog")},"..."));5741}57425743if(@taglist) {5744 git_print_header_div('tags');5745 git_tags_body(\@taglist,0,15,5746$#taglist<=15?undef:5747$cgi->a({-href => href(action=>"tags")},"..."));5748}57495750if(@headlist) {5751 git_print_header_div('heads');5752 git_heads_body(\@headlist,$head,0,15,5753$#headlist<=15?undef:5754$cgi->a({-href => href(action=>"heads")},"..."));5755}57565757if(%remotedata) {5758 git_print_header_div('remotes');5759 git_remotes_body(\%remotedata,15,$head);5760}57615762if(@forklist) {5763 git_print_header_div('forks');5764 git_project_list_body(\@forklist,'age',0,15,5765$#forklist<=15?undef:5766$cgi->a({-href => href(action=>"forks")},"..."),5767'no_header');5768}57695770 git_footer_html();5771}57725773sub git_tag {5774my%tag= parse_tag($hash);57755776if(!%tag) {5777 die_error(404,"Unknown tag object");5778}57795780my$head= git_get_head_hash($project);5781 git_header_html();5782 git_print_page_nav('','',$head,undef,$head);5783 git_print_header_div('commit', esc_html($tag{'name'}),$hash);5784print"<div class=\"title_text\">\n".5785"<table class=\"object_header\">\n".5786"<tr>\n".5787"<td>object</td>\n".5788"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5789$tag{'object'}) ."</td>\n".5790"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5791$tag{'type'}) ."</td>\n".5792"</tr>\n";5793if(defined($tag{'author'})) {5794 git_print_authorship_rows(\%tag,'author');5795}5796print"</table>\n\n".5797"</div>\n";5798print"<div class=\"page_body\">";5799my$comment=$tag{'comment'};5800foreachmy$line(@$comment) {5801chomp$line;5802print esc_html($line, -nbsp=>1) ."<br/>\n";5803}5804print"</div>\n";5805 git_footer_html();5806}58075808sub git_blame_common {5809my$format=shift||'porcelain';5810if($formateq'porcelain'&&$cgi->param('js')) {5811$format='incremental';5812$action='blame_incremental';# for page title etc5813}58145815# permissions5816 gitweb_check_feature('blame')5817or die_error(403,"Blame view not allowed");58185819# error checking5820 die_error(400,"No file name given")unless$file_name;5821$hash_base||= git_get_head_hash($project);5822 die_error(404,"Couldn't find base commit")unless$hash_base;5823my%co= parse_commit($hash_base)5824or die_error(404,"Commit not found");5825my$ftype="blob";5826if(!defined$hash) {5827$hash= git_get_hash_by_path($hash_base,$file_name,"blob")5828or die_error(404,"Error looking up file");5829}else{5830$ftype= git_get_type($hash);5831if($ftype!~"blob") {5832 die_error(400,"Object is not a blob");5833}5834}58355836my$fd;5837if($formateq'incremental') {5838# get file contents (as base)5839open$fd,"-|", git_cmd(),'cat-file','blob',$hash5840or die_error(500,"Open git-cat-file failed");5841}elsif($formateq'data') {5842# run git-blame --incremental5843open$fd,"-|", git_cmd(),"blame","--incremental",5844$hash_base,"--",$file_name5845or die_error(500,"Open git-blame --incremental failed");5846}else{5847# run git-blame --porcelain5848open$fd,"-|", git_cmd(),"blame",'-p',5849$hash_base,'--',$file_name5850or die_error(500,"Open git-blame --porcelain failed");5851}58525853# incremental blame data returns early5854if($formateq'data') {5855print$cgi->header(5856-type=>"text/plain", -charset =>"utf-8",5857-status=>"200 OK");5858local$| =1;# output autoflush5859printwhile<$fd>;5860close$fd5861or print"ERROR$!\n";58625863print'END';5864if(defined$t0&& gitweb_check_feature('timed')) {5865print' '.5866 tv_interval($t0, [ gettimeofday() ]).5867' '.$number_of_git_cmds;5868}5869print"\n";58705871return;5872}58735874# page header5875 git_header_html();5876my$formats_nav=5877$cgi->a({-href => href(action=>"blob", -replay=>1)},5878"blob") .5879" | ";5880if($formateq'incremental') {5881$formats_nav.=5882$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},5883"blame") ." (non-incremental)";5884}else{5885$formats_nav.=5886$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},5887"blame") ." (incremental)";5888}5889$formats_nav.=5890" | ".5891$cgi->a({-href => href(action=>"history", -replay=>1)},5892"history") .5893" | ".5894$cgi->a({-href => href(action=>$action, file_name=>$file_name)},5895"HEAD");5896 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5897 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5898 git_print_page_path($file_name,$ftype,$hash_base);58995900# page body5901if($formateq'incremental') {5902print"<noscript>\n<div class=\"error\"><center><b>\n".5903"This page requires JavaScript to run.\nUse ".5904$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},5905'this page').5906" instead.\n".5907"</b></center></div>\n</noscript>\n";59085909print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;5910}59115912print qq!<div class="page_body">\n!;5913print qq!<div id="progress_info">.../ ...</div>\n!5914if($formateq'incremental');5915print qq!<table id="blame_table"class="blame" width="100%">\n!.5916#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.5917 qq!<thead>\n!.5918 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.5919 qq!</thead>\n!.5920 qq!<tbody>\n!;59215922my@rev_color=qw(light dark);5923my$num_colors=scalar(@rev_color);5924my$current_color=0;59255926if($formateq'incremental') {5927my$color_class=$rev_color[$current_color];59285929#contents of a file5930my$linenr=0;5931 LINE:5932while(my$line= <$fd>) {5933chomp$line;5934$linenr++;59355936print qq!<tr id="l$linenr"class="$color_class">!.5937 qq!<td class="sha1"><a href=""> </a></td>!.5938 qq!<td class="linenr">!.5939 qq!<a class="linenr" href="">$linenr</a></td>!;5940print qq!<td class="pre">! . esc_html($line) ."</td>\n";5941print qq!</tr>\n!;5942}59435944}else{# porcelain, i.e. ordinary blame5945my%metainfo= ();# saves information about commits59465947# blame data5948 LINE:5949while(my$line= <$fd>) {5950chomp$line;5951# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]5952# no <lines in group> for subsequent lines in group of lines5953my($full_rev,$orig_lineno,$lineno,$group_size) =5954($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);5955if(!exists$metainfo{$full_rev}) {5956$metainfo{$full_rev} = {'nprevious'=>0};5957}5958my$meta=$metainfo{$full_rev};5959my$data;5960while($data= <$fd>) {5961chomp$data;5962last if($data=~s/^\t//);# contents of line5963if($data=~/^(\S+)(?: (.*))?$/) {5964$meta->{$1} =$2unlessexists$meta->{$1};5965}5966if($data=~/^previous /) {5967$meta->{'nprevious'}++;5968}5969}5970my$short_rev=substr($full_rev,0,8);5971my$author=$meta->{'author'};5972my%date=5973 parse_date($meta->{'author-time'},$meta->{'author-tz'});5974my$date=$date{'iso-tz'};5975if($group_size) {5976$current_color= ($current_color+1) %$num_colors;5977}5978my$tr_class=$rev_color[$current_color];5979$tr_class.=' boundary'if(exists$meta->{'boundary'});5980$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);5981$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);5982print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";5983if($group_size) {5984print"<td class=\"sha1\"";5985print" title=\"". esc_html($author) .",$date\"";5986print" rowspan=\"$group_size\""if($group_size>1);5987print">";5988print$cgi->a({-href => href(action=>"commit",5989 hash=>$full_rev,5990 file_name=>$file_name)},5991 esc_html($short_rev));5992if($group_size>=2) {5993my@author_initials= ($author=~/\b([[:upper:]])\B/g);5994if(@author_initials) {5995print"<br />".5996 esc_html(join('',@author_initials));5997# or join('.', ...)5998}5999}6000print"</td>\n";6001}6002# 'previous' <sha1 of parent commit> <filename at commit>6003if(exists$meta->{'previous'} &&6004$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {6005$meta->{'parent'} =$1;6006$meta->{'file_parent'} = unquote($2);6007}6008my$linenr_commit=6009exists($meta->{'parent'}) ?6010$meta->{'parent'} :$full_rev;6011my$linenr_filename=6012exists($meta->{'file_parent'}) ?6013$meta->{'file_parent'} : unquote($meta->{'filename'});6014my$blamed= href(action =>'blame',6015 file_name =>$linenr_filename,6016 hash_base =>$linenr_commit);6017print"<td class=\"linenr\">";6018print$cgi->a({ -href =>"$blamed#l$orig_lineno",6019-class=>"linenr"},6020 esc_html($lineno));6021print"</td>";6022print"<td class=\"pre\">". esc_html($data) ."</td>\n";6023print"</tr>\n";6024}# end while60256026}60276028# footer6029print"</tbody>\n".6030"</table>\n";# class="blame"6031print"</div>\n";# class="blame_body"6032close$fd6033or print"Reading blob failed\n";60346035 git_footer_html();6036}60376038sub git_blame {6039 git_blame_common();6040}60416042sub git_blame_incremental {6043 git_blame_common('incremental');6044}60456046sub git_blame_data {6047 git_blame_common('data');6048}60496050sub git_tags {6051my$head= git_get_head_hash($project);6052 git_header_html();6053 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6054 git_print_header_div('summary',$project);60556056my@tagslist= git_get_tags_list();6057if(@tagslist) {6058 git_tags_body(\@tagslist);6059}6060 git_footer_html();6061}60626063sub git_heads {6064my$head= git_get_head_hash($project);6065 git_header_html();6066 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6067 git_print_header_div('summary',$project);60686069my@headslist= git_get_heads_list();6070if(@headslist) {6071 git_heads_body(\@headslist,$head);6072}6073 git_footer_html();6074}60756076# used both for single remote view and for list of all the remotes6077sub git_remotes {6078 gitweb_check_feature('remote_heads')6079or die_error(403,"Remote heads view is disabled");60806081my$head= git_get_head_hash($project);6082my$remote=$input_params{'hash'};60836084my$remotedata= git_get_remotes_list($remote);6085 die_error(500,"Unable to get remote information")unlessdefined$remotedata;60866087unless(%$remotedata) {6088 die_error(404,defined$remote?6089"Remote$remotenot found":6090"No remotes found");6091}60926093 git_header_html(undef,undef, -action_extra =>$remote);6094 git_print_page_nav('','',$head,undef,$head,6095 format_ref_views($remote?'':'remotes'));60966097 fill_remote_heads($remotedata);6098if(defined$remote) {6099 git_print_header_div('remotes',"$remoteremote for$project");6100 git_remote_block($remote,$remotedata->{$remote},undef,$head);6101}else{6102 git_print_header_div('summary',"$projectremotes");6103 git_remotes_body($remotedata,undef,$head);6104}61056106 git_footer_html();6107}61086109sub git_blob_plain {6110my$type=shift;6111my$expires;61126113if(!defined$hash) {6114if(defined$file_name) {6115my$base=$hash_base|| git_get_head_hash($project);6116$hash= git_get_hash_by_path($base,$file_name,"blob")6117or die_error(404,"Cannot find file");6118}else{6119 die_error(400,"No file name defined");6120}6121}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6122# blobs defined by non-textual hash id's can be cached6123$expires="+1d";6124}61256126open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6127or die_error(500,"Open git-cat-file blob '$hash' failed");61286129# content-type (can include charset)6130$type= blob_contenttype($fd,$file_name,$type);61316132# "save as" filename, even when no $file_name is given6133my$save_as="$hash";6134if(defined$file_name) {6135$save_as=$file_name;6136}elsif($type=~m/^text\//) {6137$save_as.='.txt';6138}61396140# With XSS prevention on, blobs of all types except a few known safe6141# ones are served with "Content-Disposition: attachment" to make sure6142# they don't run in our security domain. For certain image types,6143# blob view writes an <img> tag referring to blob_plain view, and we6144# want to be sure not to break that by serving the image as an6145# attachment (though Firefox 3 doesn't seem to care).6146my$sandbox=$prevent_xss&&6147$type!~m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;61486149# serve text/* as text/plain6150if($prevent_xss&&6151($type=~m!^text/[a-z]+\b(.*)$!||6152($type=~m!^[a-z]+/[a-z]\+xml\b(.*)$!&& -T $fd))) {6153my$rest=$1;6154$rest=defined$rest?$rest:'';6155$type="text/plain$rest";6156}61576158print$cgi->header(6159-type =>$type,6160-expires =>$expires,6161-content_disposition =>6162($sandbox?'attachment':'inline')6163.'; filename="'.$save_as.'"');6164local$/=undef;6165binmode STDOUT,':raw';6166print<$fd>;6167binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6168close$fd;6169}61706171sub git_blob {6172my$expires;61736174if(!defined$hash) {6175if(defined$file_name) {6176my$base=$hash_base|| git_get_head_hash($project);6177$hash= git_get_hash_by_path($base,$file_name,"blob")6178or die_error(404,"Cannot find file");6179}else{6180 die_error(400,"No file name defined");6181}6182}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6183# blobs defined by non-textual hash id's can be cached6184$expires="+1d";6185}61866187my$have_blame= gitweb_check_feature('blame');6188open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6189or die_error(500,"Couldn't cat$file_name,$hash");6190my$mimetype= blob_mimetype($fd,$file_name);6191# use 'blob_plain' (aka 'raw') view for files that cannot be displayed6192if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {6193close$fd;6194return git_blob_plain($mimetype);6195}6196# we can have blame only for text/* mimetype6197$have_blame&&= ($mimetype=~m!^text/!);61986199my$highlight= gitweb_check_feature('highlight');6200my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);6201$fd= run_highlighter($fd,$highlight,$syntax)6202if$syntax;62036204 git_header_html(undef,$expires);6205my$formats_nav='';6206if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6207if(defined$file_name) {6208if($have_blame) {6209$formats_nav.=6210$cgi->a({-href => href(action=>"blame", -replay=>1)},6211"blame") .6212" | ";6213}6214$formats_nav.=6215$cgi->a({-href => href(action=>"history", -replay=>1)},6216"history") .6217" | ".6218$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6219"raw") .6220" | ".6221$cgi->a({-href => href(action=>"blob",6222 hash_base=>"HEAD", file_name=>$file_name)},6223"HEAD");6224}else{6225$formats_nav.=6226$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6227"raw");6228}6229 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6230 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6231}else{6232print"<div class=\"page_nav\">\n".6233"<br/><br/></div>\n".6234"<div class=\"title\">".esc_html($hash)."</div>\n";6235}6236 git_print_page_path($file_name,"blob",$hash_base);6237print"<div class=\"page_body\">\n";6238if($mimetype=~m!^image/!) {6239print qq!<img type="!.esc_attr($mimetype).qq!"!;6240if($file_name) {6241print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;6242}6243print qq! src="! .6244 href(action=>"blob_plain", hash=>$hash,6245 hash_base=>$hash_base, file_name=>$file_name) .6246 qq!"/>\n!;6247}else{6248my$nr;6249while(my$line= <$fd>) {6250chomp$line;6251$nr++;6252$line= untabify($line);6253printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,6254$nr, esc_attr(href(-replay =>1)),$nr,$nr,$syntax?$line: esc_html($line, -nbsp=>1);6255}6256}6257close$fd6258or print"Reading blob failed.\n";6259print"</div>";6260 git_footer_html();6261}62626263sub git_tree {6264if(!defined$hash_base) {6265$hash_base="HEAD";6266}6267if(!defined$hash) {6268if(defined$file_name) {6269$hash= git_get_hash_by_path($hash_base,$file_name,"tree");6270}else{6271$hash=$hash_base;6272}6273}6274 die_error(404,"No such tree")unlessdefined($hash);62756276my$show_sizes= gitweb_check_feature('show-sizes');6277my$have_blame= gitweb_check_feature('blame');62786279my@entries= ();6280{6281local$/="\0";6282open my$fd,"-|", git_cmd(),"ls-tree",'-z',6283($show_sizes?'-l': ()),@extra_options,$hash6284or die_error(500,"Open git-ls-tree failed");6285@entries=map{chomp;$_} <$fd>;6286close$fd6287or die_error(404,"Reading tree failed");6288}62896290my$refs= git_get_references();6291my$ref= format_ref_marker($refs,$hash_base);6292 git_header_html();6293my$basedir='';6294if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6295my@views_nav= ();6296if(defined$file_name) {6297push@views_nav,6298$cgi->a({-href => href(action=>"history", -replay=>1)},6299"history"),6300$cgi->a({-href => href(action=>"tree",6301 hash_base=>"HEAD", file_name=>$file_name)},6302"HEAD"),6303}6304my$snapshot_links= format_snapshot_links($hash);6305if(defined$snapshot_links) {6306# FIXME: Should be available when we have no hash base as well.6307push@views_nav,$snapshot_links;6308}6309 git_print_page_nav('tree','',$hash_base,undef,undef,6310join(' | ',@views_nav));6311 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);6312}else{6313undef$hash_base;6314print"<div class=\"page_nav\">\n";6315print"<br/><br/></div>\n";6316print"<div class=\"title\">".esc_html($hash)."</div>\n";6317}6318if(defined$file_name) {6319$basedir=$file_name;6320if($basedirne''&&substr($basedir, -1)ne'/') {6321$basedir.='/';6322}6323 git_print_page_path($file_name,'tree',$hash_base);6324}6325print"<div class=\"page_body\">\n";6326print"<table class=\"tree\">\n";6327my$alternate=1;6328# '..' (top directory) link if possible6329if(defined$hash_base&&6330defined$file_name&&$file_name=~m![^/]+$!) {6331if($alternate) {6332print"<tr class=\"dark\">\n";6333}else{6334print"<tr class=\"light\">\n";6335}6336$alternate^=1;63376338my$up=$file_name;6339$up=~s!/?[^/]+$!!;6340undef$upunless$up;6341# based on git_print_tree_entry6342print'<td class="mode">'. mode_str('040000') ."</td>\n";6343print'<td class="size"> </td>'."\n"if$show_sizes;6344print'<td class="list">';6345print$cgi->a({-href => href(action=>"tree",6346 hash_base=>$hash_base,6347 file_name=>$up)},6348"..");6349print"</td>\n";6350print"<td class=\"link\"></td>\n";63516352print"</tr>\n";6353}6354foreachmy$line(@entries) {6355my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);63566357if($alternate) {6358print"<tr class=\"dark\">\n";6359}else{6360print"<tr class=\"light\">\n";6361}6362$alternate^=1;63636364 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);63656366print"</tr>\n";6367}6368print"</table>\n".6369"</div>";6370 git_footer_html();6371}63726373sub snapshot_name {6374my($project,$hash) =@_;63756376# path/to/project.git -> project6377# path/to/project/.git -> project6378my$name= to_utf8($project);6379$name=~ s,([^/])/*\.git$,$1,;6380$name= basename($name);6381# sanitize name6382$name=~s/[[:cntrl:]]/?/g;63836384my$ver=$hash;6385if($hash=~/^[0-9a-fA-F]+$/) {6386# shorten SHA-1 hash6387my$full_hash= git_get_full_hash($project,$hash);6388if($full_hash=~/^$hash/&&length($hash) >7) {6389$ver= git_get_short_hash($project,$hash);6390}6391}elsif($hash=~m!^refs/tags/(.*)$!) {6392# tags don't need shortened SHA-1 hash6393$ver=$1;6394}else{6395# branches and other need shortened SHA-1 hash6396if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {6397$ver=$1;6398}6399$ver.='-'. git_get_short_hash($project,$hash);6400}6401# in case of hierarchical branch names6402$ver=~s!/!.!g;64036404# name = project-version_string6405$name="$name-$ver";64066407returnwantarray? ($name,$name) :$name;6408}64096410sub git_snapshot {6411my$format=$input_params{'snapshot_format'};6412if(!@snapshot_fmts) {6413 die_error(403,"Snapshots not allowed");6414}6415# default to first supported snapshot format6416$format||=$snapshot_fmts[0];6417if($format!~m/^[a-z0-9]+$/) {6418 die_error(400,"Invalid snapshot format parameter");6419}elsif(!exists($known_snapshot_formats{$format})) {6420 die_error(400,"Unknown snapshot format");6421}elsif($known_snapshot_formats{$format}{'disabled'}) {6422 die_error(403,"Snapshot format not allowed");6423}elsif(!grep($_eq$format,@snapshot_fmts)) {6424 die_error(403,"Unsupported snapshot format");6425}64266427my$type= git_get_type("$hash^{}");6428if(!$type) {6429 die_error(404,'Object does not exist');6430}elsif($typeeq'blob') {6431 die_error(400,'Object is not a tree-ish');6432}64336434my($name,$prefix) = snapshot_name($project,$hash);6435my$filename="$name$known_snapshot_formats{$format}{'suffix'}";6436my$cmd= quote_command(6437 git_cmd(),'archive',6438"--format=$known_snapshot_formats{$format}{'format'}",6439"--prefix=$prefix/",$hash);6440if(exists$known_snapshot_formats{$format}{'compressor'}) {6441$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});6442}64436444$filename=~s/(["\\])/\\$1/g;6445print$cgi->header(6446-type =>$known_snapshot_formats{$format}{'type'},6447-content_disposition =>'inline; filename="'.$filename.'"',6448-status =>'200 OK');64496450open my$fd,"-|",$cmd6451or die_error(500,"Execute git-archive failed");6452binmode STDOUT,':raw';6453print<$fd>;6454binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6455close$fd;6456}64576458sub git_log_generic {6459my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;64606461my$head= git_get_head_hash($project);6462if(!defined$base) {6463$base=$head;6464}6465if(!defined$page) {6466$page=0;6467}6468my$refs= git_get_references();64696470my$commit_hash=$base;6471if(defined$parent) {6472$commit_hash="$parent..$base";6473}6474my@commitlist=6475 parse_commits($commit_hash,101, (100*$page),6476defined$file_name? ($file_name,"--full-history") : ());64776478my$ftype;6479if(!defined$file_hash&&defined$file_name) {6480# some commits could have deleted file in question,6481# and not have it in tree, but one of them has to have it6482for(my$i=0;$i<@commitlist;$i++) {6483$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);6484last ifdefined$file_hash;6485}6486}6487if(defined$file_hash) {6488$ftype= git_get_type($file_hash);6489}6490if(defined$file_name&& !defined$ftype) {6491 die_error(500,"Unknown type of object");6492}6493my%co;6494if(defined$file_name) {6495%co= parse_commit($base)6496or die_error(404,"Unknown commit object");6497}649864996500my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);6501my$next_link='';6502if($#commitlist>=100) {6503$next_link=6504$cgi->a({-href => href(-replay=>1, page=>$page+1),6505-accesskey =>"n", -title =>"Alt-n"},"next");6506}6507my$patch_max= gitweb_get_feature('patches');6508if($patch_max&& !defined$file_name) {6509if($patch_max<0||@commitlist<=$patch_max) {6510$paging_nav.=" ⋅ ".6511$cgi->a({-href => href(action=>"patches", -replay=>1)},6512"patches");6513}6514}65156516 git_header_html();6517 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);6518if(defined$file_name) {6519 git_print_header_div('commit', esc_html($co{'title'}),$base);6520}else{6521 git_print_header_div('summary',$project)6522}6523 git_print_page_path($file_name,$ftype,$hash_base)6524if(defined$file_name);65256526$body_subr->(\@commitlist,0,99,$refs,$next_link,6527$file_name,$file_hash,$ftype);65286529 git_footer_html();6530}65316532sub git_log {6533 git_log_generic('log', \&git_log_body,6534$hash,$hash_parent);6535}65366537sub git_commit {6538$hash||=$hash_base||"HEAD";6539my%co= parse_commit($hash)6540or die_error(404,"Unknown commit object");65416542my$parent=$co{'parent'};6543my$parents=$co{'parents'};# listref65446545# we need to prepare $formats_nav before any parameter munging6546my$formats_nav;6547if(!defined$parent) {6548# --root commitdiff6549$formats_nav.='(initial)';6550}elsif(@$parents==1) {6551# single parent commit6552$formats_nav.=6553'(parent: '.6554$cgi->a({-href => href(action=>"commit",6555 hash=>$parent)},6556 esc_html(substr($parent,0,7))) .6557')';6558}else{6559# merge commit6560$formats_nav.=6561'(merge: '.6562join(' ',map{6563$cgi->a({-href => href(action=>"commit",6564 hash=>$_)},6565 esc_html(substr($_,0,7)));6566}@$parents) .6567')';6568}6569if(gitweb_check_feature('patches') &&@$parents<=1) {6570$formats_nav.=" | ".6571$cgi->a({-href => href(action=>"patch", -replay=>1)},6572"patch");6573}65746575if(!defined$parent) {6576$parent="--root";6577}6578my@difftree;6579open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",6580@diff_opts,6581(@$parents<=1?$parent:'-c'),6582$hash,"--"6583or die_error(500,"Open git-diff-tree failed");6584@difftree=map{chomp;$_} <$fd>;6585close$fdor die_error(404,"Reading git-diff-tree failed");65866587# non-textual hash id's can be cached6588my$expires;6589if($hash=~m/^[0-9a-fA-F]{40}$/) {6590$expires="+1d";6591}6592my$refs= git_get_references();6593my$ref= format_ref_marker($refs,$co{'id'});65946595 git_header_html(undef,$expires);6596 git_print_page_nav('commit','',6597$hash,$co{'tree'},$hash,6598$formats_nav);65996600if(defined$co{'parent'}) {6601 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);6602}else{6603 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);6604}6605print"<div class=\"title_text\">\n".6606"<table class=\"object_header\">\n";6607 git_print_authorship_rows(\%co);6608print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";6609print"<tr>".6610"<td>tree</td>".6611"<td class=\"sha1\">".6612$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),6613class=>"list"},$co{'tree'}) .6614"</td>".6615"<td class=\"link\">".6616$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},6617"tree");6618my$snapshot_links= format_snapshot_links($hash);6619if(defined$snapshot_links) {6620print" | ".$snapshot_links;6621}6622print"</td>".6623"</tr>\n";66246625foreachmy$par(@$parents) {6626print"<tr>".6627"<td>parent</td>".6628"<td class=\"sha1\">".6629$cgi->a({-href => href(action=>"commit", hash=>$par),6630class=>"list"},$par) .6631"</td>".6632"<td class=\"link\">".6633$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .6634" | ".6635$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .6636"</td>".6637"</tr>\n";6638}6639print"</table>".6640"</div>\n";66416642print"<div class=\"page_body\">\n";6643 git_print_log($co{'comment'});6644print"</div>\n";66456646 git_difftree_body(\@difftree,$hash,@$parents);66476648 git_footer_html();6649}66506651sub git_object {6652# object is defined by:6653# - hash or hash_base alone6654# - hash_base and file_name6655my$type;66566657# - hash or hash_base alone6658if($hash|| ($hash_base&& !defined$file_name)) {6659my$object_id=$hash||$hash_base;66606661open my$fd,"-|", quote_command(6662 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'6663or die_error(404,"Object does not exist");6664$type= <$fd>;6665chomp$type;6666close$fd6667or die_error(404,"Object does not exist");66686669# - hash_base and file_name6670}elsif($hash_base&&defined$file_name) {6671$file_name=~ s,/+$,,;66726673system(git_cmd(),"cat-file",'-e',$hash_base) ==06674or die_error(404,"Base object does not exist");66756676# here errors should not hapen6677open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name6678or die_error(500,"Open git-ls-tree failed");6679my$line= <$fd>;6680close$fd;66816682#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'6683unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {6684 die_error(404,"File or directory for given base does not exist");6685}6686$type=$2;6687$hash=$3;6688}else{6689 die_error(400,"Not enough information to find object");6690}66916692print$cgi->redirect(-uri => href(action=>$type, -full=>1,6693 hash=>$hash, hash_base=>$hash_base,6694 file_name=>$file_name),6695-status =>'302 Found');6696}66976698sub git_blobdiff {6699my$format=shift||'html';67006701my$fd;6702my@difftree;6703my%diffinfo;6704my$expires;67056706# preparing $fd and %diffinfo for git_patchset_body6707# new style URI6708if(defined$hash_base&&defined$hash_parent_base) {6709if(defined$file_name) {6710# read raw output6711open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6712$hash_parent_base,$hash_base,6713"--", (defined$file_parent?$file_parent: ()),$file_name6714or die_error(500,"Open git-diff-tree failed");6715@difftree=map{chomp;$_} <$fd>;6716close$fd6717or die_error(404,"Reading git-diff-tree failed");6718@difftree6719or die_error(404,"Blob diff not found");67206721}elsif(defined$hash&&6722$hash=~/[0-9a-fA-F]{40}/) {6723# try to find filename from $hash67246725# read filtered raw output6726open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6727$hash_parent_base,$hash_base,"--"6728or die_error(500,"Open git-diff-tree failed");6729@difftree=6730# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'6731# $hash == to_id6732grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}6733map{chomp;$_} <$fd>;6734close$fd6735or die_error(404,"Reading git-diff-tree failed");6736@difftree6737or die_error(404,"Blob diff not found");67386739}else{6740 die_error(400,"Missing one of the blob diff parameters");6741}67426743if(@difftree>1) {6744 die_error(400,"Ambiguous blob diff specification");6745}67466747%diffinfo= parse_difftree_raw_line($difftree[0]);6748$file_parent||=$diffinfo{'from_file'} ||$file_name;6749$file_name||=$diffinfo{'to_file'};67506751$hash_parent||=$diffinfo{'from_id'};6752$hash||=$diffinfo{'to_id'};67536754# non-textual hash id's can be cached6755if($hash_base=~m/^[0-9a-fA-F]{40}$/&&6756$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {6757$expires='+1d';6758}67596760# open patch output6761open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6762'-p', ($formateq'html'?"--full-index": ()),6763$hash_parent_base,$hash_base,6764"--", (defined$file_parent?$file_parent: ()),$file_name6765or die_error(500,"Open git-diff-tree failed");6766}67676768# old/legacy style URI -- not generated anymore since 1.4.3.6769if(!%diffinfo) {6770 die_error('404 Not Found',"Missing one of the blob diff parameters")6771}67726773# header6774if($formateq'html') {6775my$formats_nav=6776$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},6777"raw");6778 git_header_html(undef,$expires);6779if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6780 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6781 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6782}else{6783print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";6784print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";6785}6786if(defined$file_name) {6787 git_print_page_path($file_name,"blob",$hash_base);6788}else{6789print"<div class=\"page_path\"></div>\n";6790}67916792}elsif($formateq'plain') {6793print$cgi->header(6794-type =>'text/plain',6795-charset =>'utf-8',6796-expires =>$expires,6797-content_disposition =>'inline; filename="'."$file_name".'.patch"');67986799print"X-Git-Url: ".$cgi->self_url() ."\n\n";68006801}else{6802 die_error(400,"Unknown blobdiff format");6803}68046805# patch6806if($formateq'html') {6807print"<div class=\"page_body\">\n";68086809 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);6810close$fd;68116812print"</div>\n";# class="page_body"6813 git_footer_html();68146815}else{6816while(my$line= <$fd>) {6817$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;6818$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;68196820print$line;68216822last if$line=~m!^\+\+\+!;6823}6824local$/=undef;6825print<$fd>;6826close$fd;6827}6828}68296830sub git_blobdiff_plain {6831 git_blobdiff('plain');6832}68336834sub git_commitdiff {6835my%params=@_;6836my$format=$params{-format} ||'html';68376838my($patch_max) = gitweb_get_feature('patches');6839if($formateq'patch') {6840 die_error(403,"Patch view not allowed")unless$patch_max;6841}68426843$hash||=$hash_base||"HEAD";6844my%co= parse_commit($hash)6845or die_error(404,"Unknown commit object");68466847# choose format for commitdiff for merge6848if(!defined$hash_parent&& @{$co{'parents'}} >1) {6849$hash_parent='--cc';6850}6851# we need to prepare $formats_nav before almost any parameter munging6852my$formats_nav;6853if($formateq'html') {6854$formats_nav=6855$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},6856"raw");6857if($patch_max&& @{$co{'parents'}} <=1) {6858$formats_nav.=" | ".6859$cgi->a({-href => href(action=>"patch", -replay=>1)},6860"patch");6861}68626863if(defined$hash_parent&&6864$hash_parentne'-c'&&$hash_parentne'--cc') {6865# commitdiff with two commits given6866my$hash_parent_short=$hash_parent;6867if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {6868$hash_parent_short=substr($hash_parent,0,7);6869}6870$formats_nav.=6871' (from';6872for(my$i=0;$i< @{$co{'parents'}};$i++) {6873if($co{'parents'}[$i]eq$hash_parent) {6874$formats_nav.=' parent '. ($i+1);6875last;6876}6877}6878$formats_nav.=': '.6879$cgi->a({-href => href(action=>"commitdiff",6880 hash=>$hash_parent)},6881 esc_html($hash_parent_short)) .6882')';6883}elsif(!$co{'parent'}) {6884# --root commitdiff6885$formats_nav.=' (initial)';6886}elsif(scalar@{$co{'parents'}} ==1) {6887# single parent commit6888$formats_nav.=6889' (parent: '.6890$cgi->a({-href => href(action=>"commitdiff",6891 hash=>$co{'parent'})},6892 esc_html(substr($co{'parent'},0,7))) .6893')';6894}else{6895# merge commit6896if($hash_parenteq'--cc') {6897$formats_nav.=' | '.6898$cgi->a({-href => href(action=>"commitdiff",6899 hash=>$hash, hash_parent=>'-c')},6900'combined');6901}else{# $hash_parent eq '-c'6902$formats_nav.=' | '.6903$cgi->a({-href => href(action=>"commitdiff",6904 hash=>$hash, hash_parent=>'--cc')},6905'compact');6906}6907$formats_nav.=6908' (merge: '.6909join(' ',map{6910$cgi->a({-href => href(action=>"commitdiff",6911 hash=>$_)},6912 esc_html(substr($_,0,7)));6913} @{$co{'parents'}} ) .6914')';6915}6916}69176918my$hash_parent_param=$hash_parent;6919if(!defined$hash_parent_param) {6920# --cc for multiple parents, --root for parentless6921$hash_parent_param=6922@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';6923}69246925# read commitdiff6926my$fd;6927my@difftree;6928if($formateq'html') {6929open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6930"--no-commit-id","--patch-with-raw","--full-index",6931$hash_parent_param,$hash,"--"6932or die_error(500,"Open git-diff-tree failed");69336934while(my$line= <$fd>) {6935chomp$line;6936# empty line ends raw part of diff-tree output6937last unless$line;6938push@difftree,scalar parse_difftree_raw_line($line);6939}69406941}elsif($formateq'plain') {6942open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6943'-p',$hash_parent_param,$hash,"--"6944or die_error(500,"Open git-diff-tree failed");6945}elsif($formateq'patch') {6946# For commit ranges, we limit the output to the number of6947# patches specified in the 'patches' feature.6948# For single commits, we limit the output to a single patch,6949# diverging from the git-format-patch default.6950my@commit_spec= ();6951if($hash_parent) {6952if($patch_max>0) {6953push@commit_spec,"-$patch_max";6954}6955push@commit_spec,'-n',"$hash_parent..$hash";6956}else{6957if($params{-single}) {6958push@commit_spec,'-1';6959}else{6960if($patch_max>0) {6961push@commit_spec,"-$patch_max";6962}6963push@commit_spec,"-n";6964}6965push@commit_spec,'--root',$hash;6966}6967open$fd,"-|", git_cmd(),"format-patch",@diff_opts,6968'--encoding=utf8','--stdout',@commit_spec6969or die_error(500,"Open git-format-patch failed");6970}else{6971 die_error(400,"Unknown commitdiff format");6972}69736974# non-textual hash id's can be cached6975my$expires;6976if($hash=~m/^[0-9a-fA-F]{40}$/) {6977$expires="+1d";6978}69796980# write commit message6981if($formateq'html') {6982my$refs= git_get_references();6983my$ref= format_ref_marker($refs,$co{'id'});69846985 git_header_html(undef,$expires);6986 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);6987 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);6988print"<div class=\"title_text\">\n".6989"<table class=\"object_header\">\n";6990 git_print_authorship_rows(\%co);6991print"</table>".6992"</div>\n";6993print"<div class=\"page_body\">\n";6994if(@{$co{'comment'}} >1) {6995print"<div class=\"log\">\n";6996 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);6997print"</div>\n";# class="log"6998}69997000}elsif($formateq'plain') {7001my$refs= git_get_references("tags");7002my$tagname= git_get_rev_name_tags($hash);7003my$filename= basename($project) ."-$hash.patch";70047005print$cgi->header(7006-type =>'text/plain',7007-charset =>'utf-8',7008-expires =>$expires,7009-content_disposition =>'inline; filename="'."$filename".'"');7010my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});7011print"From: ". to_utf8($co{'author'}) ."\n";7012print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";7013print"Subject: ". to_utf8($co{'title'}) ."\n";70147015print"X-Git-Tag:$tagname\n"if$tagname;7016print"X-Git-Url: ".$cgi->self_url() ."\n\n";70177018foreachmy$line(@{$co{'comment'}}) {7019print to_utf8($line) ."\n";7020}7021print"---\n\n";7022}elsif($formateq'patch') {7023my$filename= basename($project) ."-$hash.patch";70247025print$cgi->header(7026-type =>'text/plain',7027-charset =>'utf-8',7028-expires =>$expires,7029-content_disposition =>'inline; filename="'."$filename".'"');7030}70317032# write patch7033if($formateq'html') {7034my$use_parents= !defined$hash_parent||7035$hash_parenteq'-c'||$hash_parenteq'--cc';7036 git_difftree_body(\@difftree,$hash,7037$use_parents? @{$co{'parents'}} :$hash_parent);7038print"<br/>\n";70397040 git_patchset_body($fd, \@difftree,$hash,7041$use_parents? @{$co{'parents'}} :$hash_parent);7042close$fd;7043print"</div>\n";# class="page_body"7044 git_footer_html();70457046}elsif($formateq'plain') {7047local$/=undef;7048print<$fd>;7049close$fd7050or print"Reading git-diff-tree failed\n";7051}elsif($formateq'patch') {7052local$/=undef;7053print<$fd>;7054close$fd7055or print"Reading git-format-patch failed\n";7056}7057}70587059sub git_commitdiff_plain {7060 git_commitdiff(-format =>'plain');7061}70627063# format-patch-style patches7064sub git_patch {7065 git_commitdiff(-format =>'patch', -single =>1);7066}70677068sub git_patches {7069 git_commitdiff(-format =>'patch');7070}70717072sub git_history {7073 git_log_generic('history', \&git_history_body,7074$hash_base,$hash_parent_base,7075$file_name,$hash);7076}70777078sub git_search {7079 gitweb_check_feature('search')or die_error(403,"Search is disabled");7080if(!defined$searchtext) {7081 die_error(400,"Text field is empty");7082}7083if(!defined$hash) {7084$hash= git_get_head_hash($project);7085}7086my%co= parse_commit($hash);7087if(!%co) {7088 die_error(404,"Unknown commit object");7089}7090if(!defined$page) {7091$page=0;7092}70937094$searchtype||='commit';7095if($searchtypeeq'pickaxe') {7096# pickaxe may take all resources of your box and run for several minutes7097# with every query - so decide by yourself how public you make this feature7098 gitweb_check_feature('pickaxe')7099or die_error(403,"Pickaxe is disabled");7100}7101if($searchtypeeq'grep') {7102 gitweb_check_feature('grep')7103or die_error(403,"Grep is disabled");7104}71057106 git_header_html();71077108if($searchtypeeq'commit'or$searchtypeeq'author'or$searchtypeeq'committer') {7109my$greptype;7110if($searchtypeeq'commit') {7111$greptype="--grep=";7112}elsif($searchtypeeq'author') {7113$greptype="--author=";7114}elsif($searchtypeeq'committer') {7115$greptype="--committer=";7116}7117$greptype.=$searchtext;7118my@commitlist= parse_commits($hash,101, (100*$page),undef,7119$greptype,'--regexp-ignore-case',7120$search_use_regexp?'--extended-regexp':'--fixed-strings');71217122my$paging_nav='';7123if($page>0) {7124$paging_nav.=7125$cgi->a({-href => href(action=>"search", hash=>$hash,7126 searchtext=>$searchtext,7127 searchtype=>$searchtype)},7128"first");7129$paging_nav.=" ⋅ ".7130$cgi->a({-href => href(-replay=>1, page=>$page-1),7131-accesskey =>"p", -title =>"Alt-p"},"prev");7132}else{7133$paging_nav.="first";7134$paging_nav.=" ⋅ prev";7135}7136my$next_link='';7137if($#commitlist>=100) {7138$next_link=7139$cgi->a({-href => href(-replay=>1, page=>$page+1),7140-accesskey =>"n", -title =>"Alt-n"},"next");7141$paging_nav.=" ⋅$next_link";7142}else{7143$paging_nav.=" ⋅ next";7144}71457146 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);7147 git_print_header_div('commit', esc_html($co{'title'}),$hash);7148if($page==0&& !@commitlist) {7149print"<p>No match.</p>\n";7150}else{7151 git_search_grep_body(\@commitlist,0,99,$next_link);7152}7153}71547155if($searchtypeeq'pickaxe') {7156 git_print_page_nav('','',$hash,$co{'tree'},$hash);7157 git_print_header_div('commit', esc_html($co{'title'}),$hash);71587159print"<table class=\"pickaxe search\">\n";7160my$alternate=1;7161local$/="\n";7162open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,7163'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",7164($search_use_regexp?'--pickaxe-regex': ());7165undef%co;7166my@files;7167while(my$line= <$fd>) {7168chomp$line;7169next unless$line;71707171my%set= parse_difftree_raw_line($line);7172if(defined$set{'commit'}) {7173# finish previous commit7174if(%co) {7175print"</td>\n".7176"<td class=\"link\">".7177$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .7178" | ".7179$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");7180print"</td>\n".7181"</tr>\n";7182}71837184if($alternate) {7185print"<tr class=\"dark\">\n";7186}else{7187print"<tr class=\"light\">\n";7188}7189$alternate^=1;7190%co= parse_commit($set{'commit'});7191my$author= chop_and_escape_str($co{'author_name'},15,5);7192print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".7193"<td><i>$author</i></td>\n".7194"<td>".7195$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),7196-class=>"list subject"},7197 chop_and_escape_str($co{'title'},50) ."<br/>");7198}elsif(defined$set{'to_id'}) {7199next if($set{'to_id'} =~m/^0{40}$/);72007201print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},7202 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),7203-class=>"list"},7204"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .7205"<br/>\n";7206}7207}7208close$fd;72097210# finish last commit (warning: repetition!)7211if(%co) {7212print"</td>\n".7213"<td class=\"link\">".7214$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .7215" | ".7216$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");7217print"</td>\n".7218"</tr>\n";7219}72207221print"</table>\n";7222}72237224if($searchtypeeq'grep') {7225 git_print_page_nav('','',$hash,$co{'tree'},$hash);7226 git_print_header_div('commit', esc_html($co{'title'}),$hash);72277228print"<table class=\"grep_search\">\n";7229my$alternate=1;7230my$matches=0;7231local$/="\n";7232open my$fd,"-|", git_cmd(),'grep','-n',7233$search_use_regexp? ('-E','-i') :'-F',7234$searchtext,$co{'tree'};7235my$lastfile='';7236while(my$line= <$fd>) {7237chomp$line;7238my($file,$lno,$ltext,$binary);7239last if($matches++>1000);7240if($line=~/^Binary file (.+) matches$/) {7241$file=$1;7242$binary=1;7243}else{7244(undef,$file,$lno,$ltext) =split(/:/,$line,4);7245}7246if($filene$lastfile) {7247$lastfileand print"</td></tr>\n";7248if($alternate++) {7249print"<tr class=\"dark\">\n";7250}else{7251print"<tr class=\"light\">\n";7252}7253print"<td class=\"list\">".7254$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},7255 file_name=>"$file"),7256-class=>"list"}, esc_path($file));7257print"</td><td>\n";7258$lastfile=$file;7259}7260if($binary) {7261print"<div class=\"binary\">Binary file</div>\n";7262}else{7263$ltext= untabify($ltext);7264if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {7265$ltext= esc_html($1, -nbsp=>1);7266$ltext.='<span class="match">';7267$ltext.= esc_html($2, -nbsp=>1);7268$ltext.='</span>';7269$ltext.= esc_html($3, -nbsp=>1);7270}else{7271$ltext= esc_html($ltext, -nbsp=>1);7272}7273print"<div class=\"pre\">".7274$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},7275 file_name=>"$file").'#l'.$lno,7276-class=>"linenr"},sprintf('%4i',$lno))7277.' '.$ltext."</div>\n";7278}7279}7280if($lastfile) {7281print"</td></tr>\n";7282if($matches>1000) {7283print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";7284}7285}else{7286print"<div class=\"diff nodifferences\">No matches found</div>\n";7287}7288close$fd;72897290print"</table>\n";7291}7292 git_footer_html();7293}72947295sub git_search_help {7296 git_header_html();7297 git_print_page_nav('','',$hash,$hash,$hash);7298print<<EOT;7299<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without7300regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,7301the pattern entered is recognized as the POSIX extended7302<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case7303insensitive).</p>7304<dl>7305<dt><b>commit</b></dt>7306<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>7307EOT7308my$have_grep= gitweb_check_feature('grep');7309if($have_grep) {7310print<<EOT;7311<dt><b>grep</b></dt>7312<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing7313 a different one) are searched for the given pattern. On large trees, this search can take7314a while and put some strain on the server, so please use it with some consideration. Note that7315due to git-grep peculiarity, currently if regexp mode is turned off, the matches are7316case-sensitive.</dd>7317EOT7318}7319print<<EOT;7320<dt><b>author</b></dt>7321<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>7322<dt><b>committer</b></dt>7323<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>7324EOT7325my$have_pickaxe= gitweb_check_feature('pickaxe');7326if($have_pickaxe) {7327print<<EOT;7328<dt><b>pickaxe</b></dt>7329<dd>All commits that caused the string to appear or disappear from any file (changes that7330added, removed or "modified" the string) will be listed. This search can take a while and7331takes a lot of strain on the server, so please use it wisely. Note that since you may be7332interested even in changes just changing the case as well, this search is case sensitive.</dd>7333EOT7334}7335print"</dl>\n";7336 git_footer_html();7337}73387339sub git_shortlog {7340 git_log_generic('shortlog', \&git_shortlog_body,7341$hash,$hash_parent);7342}73437344## ......................................................................7345## feeds (RSS, Atom; OPML)73467347sub git_feed {7348my$format=shift||'atom';7349my$have_blame= gitweb_check_feature('blame');73507351# Atom: http://www.atomenabled.org/developers/syndication/7352# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ7353if($formatne'rss'&&$formatne'atom') {7354 die_error(400,"Unknown web feed format");7355}73567357# log/feed of current (HEAD) branch, log of given branch, history of file/directory7358my$head=$hash||'HEAD';7359my@commitlist= parse_commits($head,150,0,$file_name);73607361my%latest_commit;7362my%latest_date;7363my$content_type="application/$format+xml";7364if(defined$cgi->http('HTTP_ACCEPT') &&7365$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {7366# browser (feed reader) prefers text/xml7367$content_type='text/xml';7368}7369if(defined($commitlist[0])) {7370%latest_commit= %{$commitlist[0]};7371my$latest_epoch=$latest_commit{'committer_epoch'};7372%latest_date= parse_date($latest_epoch,$latest_commit{'comitter_tz'});7373my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7374if(defined$if_modified) {7375my$since;7376if(eval{require HTTP::Date;1; }) {7377$since= HTTP::Date::str2time($if_modified);7378}elsif(eval{require Time::ParseDate;1; }) {7379$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7380}7381if(defined$since&&$latest_epoch<=$since) {7382print$cgi->header(7383-type =>$content_type,7384-charset =>'utf-8',7385-last_modified =>$latest_date{'rfc2822'},7386-status =>'304 Not Modified');7387return;7388}7389}7390print$cgi->header(7391-type =>$content_type,7392-charset =>'utf-8',7393-last_modified =>$latest_date{'rfc2822'});7394}else{7395print$cgi->header(7396-type =>$content_type,7397-charset =>'utf-8');7398}73997400# Optimization: skip generating the body if client asks only7401# for Last-Modified date.7402return if($cgi->request_method()eq'HEAD');74037404# header variables7405my$title="$site_name-$project/$action";7406my$feed_type='log';7407if(defined$hash) {7408$title.=" - '$hash'";7409$feed_type='branch log';7410if(defined$file_name) {7411$title.=" ::$file_name";7412$feed_type='history';7413}7414}elsif(defined$file_name) {7415$title.=" -$file_name";7416$feed_type='history';7417}7418$title.="$feed_type";7419my$descr= git_get_project_description($project);7420if(defined$descr) {7421$descr= esc_html($descr);7422}else{7423$descr="$project".7424($formateq'rss'?'RSS':'Atom') .7425" feed";7426}7427my$owner= git_get_project_owner($project);7428$owner= esc_html($owner);74297430#header7431my$alt_url;7432if(defined$file_name) {7433$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);7434}elsif(defined$hash) {7435$alt_url= href(-full=>1, action=>"log", hash=>$hash);7436}else{7437$alt_url= href(-full=>1, action=>"summary");7438}7439print qq!<?xml version="1.0" encoding="utf-8"?>\n!;7440if($formateq'rss') {7441print<<XML;7442<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">7443<channel>7444XML7445print"<title>$title</title>\n".7446"<link>$alt_url</link>\n".7447"<description>$descr</description>\n".7448"<language>en</language>\n".7449# project owner is responsible for 'editorial' content7450"<managingEditor>$owner</managingEditor>\n";7451if(defined$logo||defined$favicon) {7452# prefer the logo to the favicon, since RSS7453# doesn't allow both7454my$img= esc_url($logo||$favicon);7455print"<image>\n".7456"<url>$img</url>\n".7457"<title>$title</title>\n".7458"<link>$alt_url</link>\n".7459"</image>\n";7460}7461if(%latest_date) {7462print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";7463print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";7464}7465print"<generator>gitweb v.$version/$git_version</generator>\n";7466}elsif($formateq'atom') {7467print<<XML;7468<feed xmlns="http://www.w3.org/2005/Atom">7469XML7470print"<title>$title</title>\n".7471"<subtitle>$descr</subtitle>\n".7472'<link rel="alternate" type="text/html" href="'.7473$alt_url.'" />'."\n".7474'<link rel="self" type="'.$content_type.'" href="'.7475$cgi->self_url() .'" />'."\n".7476"<id>". href(-full=>1) ."</id>\n".7477# use project owner for feed author7478"<author><name>$owner</name></author>\n";7479if(defined$favicon) {7480print"<icon>". esc_url($favicon) ."</icon>\n";7481}7482if(defined$logo) {7483# not twice as wide as tall: 72 x 27 pixels7484print"<logo>". esc_url($logo) ."</logo>\n";7485}7486if(!%latest_date) {7487# dummy date to keep the feed valid until commits trickle in:7488print"<updated>1970-01-01T00:00:00Z</updated>\n";7489}else{7490print"<updated>$latest_date{'iso-8601'}</updated>\n";7491}7492print"<generator version='$version/$git_version'>gitweb</generator>\n";7493}74947495# contents7496for(my$i=0;$i<=$#commitlist;$i++) {7497my%co= %{$commitlist[$i]};7498my$commit=$co{'id'};7499# we read 150, we always show 30 and the ones more recent than 48 hours7500if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {7501last;7502}7503my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});75047505# get list of changed files7506open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7507$co{'parent'} ||"--root",7508$co{'id'},"--", (defined$file_name?$file_name: ())7509ornext;7510my@difftree=map{chomp;$_} <$fd>;7511close$fd7512ornext;75137514# print element (entry, item)7515my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);7516if($formateq'rss') {7517print"<item>\n".7518"<title>". esc_html($co{'title'}) ."</title>\n".7519"<author>". esc_html($co{'author'}) ."</author>\n".7520"<pubDate>$cd{'rfc2822'}</pubDate>\n".7521"<guid isPermaLink=\"true\">$co_url</guid>\n".7522"<link>$co_url</link>\n".7523"<description>". esc_html($co{'title'}) ."</description>\n".7524"<content:encoded>".7525"<![CDATA[\n";7526}elsif($formateq'atom') {7527print"<entry>\n".7528"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".7529"<updated>$cd{'iso-8601'}</updated>\n".7530"<author>\n".7531" <name>". esc_html($co{'author_name'}) ."</name>\n";7532if($co{'author_email'}) {7533print" <email>". esc_html($co{'author_email'}) ."</email>\n";7534}7535print"</author>\n".7536# use committer for contributor7537"<contributor>\n".7538" <name>". esc_html($co{'committer_name'}) ."</name>\n";7539if($co{'committer_email'}) {7540print" <email>". esc_html($co{'committer_email'}) ."</email>\n";7541}7542print"</contributor>\n".7543"<published>$cd{'iso-8601'}</published>\n".7544"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".7545"<id>$co_url</id>\n".7546"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".7547"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";7548}7549my$comment=$co{'comment'};7550print"<pre>\n";7551foreachmy$line(@$comment) {7552$line= esc_html($line);7553print"$line\n";7554}7555print"</pre><ul>\n";7556foreachmy$difftree_line(@difftree) {7557my%difftree= parse_difftree_raw_line($difftree_line);7558next if!$difftree{'from_id'};75597560my$file=$difftree{'file'} ||$difftree{'to_file'};75617562print"<li>".7563"[".7564$cgi->a({-href => href(-full=>1, action=>"blobdiff",7565 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},7566 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},7567 file_name=>$file, file_parent=>$difftree{'from_file'}),7568-title =>"diff"},'D');7569if($have_blame) {7570print$cgi->a({-href => href(-full=>1, action=>"blame",7571 file_name=>$file, hash_base=>$commit),7572-title =>"blame"},'B');7573}7574# if this is not a feed of a file history7575if(!defined$file_name||$file_namene$file) {7576print$cgi->a({-href => href(-full=>1, action=>"history",7577 file_name=>$file, hash=>$commit),7578-title =>"history"},'H');7579}7580$file= esc_path($file);7581print"] ".7582"$file</li>\n";7583}7584if($formateq'rss') {7585print"</ul>]]>\n".7586"</content:encoded>\n".7587"</item>\n";7588}elsif($formateq'atom') {7589print"</ul>\n</div>\n".7590"</content>\n".7591"</entry>\n";7592}7593}75947595# end of feed7596if($formateq'rss') {7597print"</channel>\n</rss>\n";7598}elsif($formateq'atom') {7599print"</feed>\n";7600}7601}76027603sub git_rss {7604 git_feed('rss');7605}76067607sub git_atom {7608 git_feed('atom');7609}76107611sub git_opml {7612my@list= git_get_projects_list();7613if(!@list) {7614 die_error(404,"No projects found");7615}76167617print$cgi->header(7618-type =>'text/xml',7619-charset =>'utf-8',7620-content_disposition =>'inline; filename="opml.xml"');76217622print<<XML;7623<?xml version="1.0" encoding="utf-8"?>7624<opml version="1.0">7625<head>7626 <title>$site_nameOPML Export</title>7627</head>7628<body>7629<outline text="git RSS feeds">7630XML76317632foreachmy$pr(@list) {7633my%proj=%$pr;7634my$head= git_get_head_hash($proj{'path'});7635if(!defined$head) {7636next;7637}7638$git_dir="$projectroot/$proj{'path'}";7639my%co= parse_commit($head);7640if(!%co) {7641next;7642}76437644my$path= esc_html(chop_str($proj{'path'},25,5));7645my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);7646my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);7647print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";7648}7649print<<XML;7650</outline>7651</body>7652</opml>7653XML7654}