1#!/usr/bin/perl 2 3# gitweb - simple web interface to track changes in git repositories 4# 5# (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org> 6# (C) 2005, Christian Gierke 7# 8# This program is licensed under the GPLv2 9 10use5.008; 11use strict; 12use warnings; 13use CGI qw(:standard :escapeHTML -nosticky); 14use CGI::Util qw(unescape); 15use CGI::Carp qw(fatalsToBrowser set_message); 16use Encode; 17use Fcntl ':mode'; 18use File::Find qw(); 19use File::Basename qw(basename); 20use Time::HiRes qw(gettimeofday tv_interval); 21binmode STDOUT,':utf8'; 22 23our$t0= [ gettimeofday() ]; 24our$number_of_git_cmds=0; 25 26BEGIN{ 27 CGI->compile()if$ENV{'MOD_PERL'}; 28} 29 30our$version="++GIT_VERSION++"; 31 32our($my_url,$my_uri,$base_url,$path_info,$home_link); 33sub evaluate_uri { 34our$cgi; 35 36our$my_url=$cgi->url(); 37our$my_uri=$cgi->url(-absolute =>1); 38 39# Base URL for relative URLs in gitweb ($logo, $favicon, ...), 40# needed and used only for URLs with nonempty PATH_INFO 41our$base_url=$my_url; 42 43# When the script is used as DirectoryIndex, the URL does not contain the name 44# of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we 45# have to do it ourselves. We make $path_info global because it's also used 46# later on. 47# 48# Another issue with the script being the DirectoryIndex is that the resulting 49# $my_url data is not the full script URL: this is good, because we want 50# generated links to keep implying the script name if it wasn't explicitly 51# indicated in the URL we're handling, but it means that $my_url cannot be used 52# as base URL. 53# Therefore, if we needed to strip PATH_INFO, then we know that we have 54# to build the base URL ourselves: 55our$path_info= decode_utf8($ENV{"PATH_INFO"}); 56if($path_info) { 57if($my_url=~ s,\Q$path_info\E$,, && 58$my_uri=~ s,\Q$path_info\E$,, && 59defined$ENV{'SCRIPT_NAME'}) { 60$base_url=$cgi->url(-base =>1) .$ENV{'SCRIPT_NAME'}; 61} 62} 63 64# target of the home link on top of all pages 65our$home_link=$my_uri||"/"; 66} 67 68# core git executable to use 69# this can just be "git" if your webserver has a sensible PATH 70our$GIT="++GIT_BINDIR++/git"; 71 72# absolute fs-path which will be prepended to the project path 73#our $projectroot = "/pub/scm"; 74our$projectroot="++GITWEB_PROJECTROOT++"; 75 76# fs traversing limit for getting project list 77# the number is relative to the projectroot 78our$project_maxdepth="++GITWEB_PROJECT_MAXDEPTH++"; 79 80# string of the home link on top of all pages 81our$home_link_str="++GITWEB_HOME_LINK_STR++"; 82 83# name of your site or organization to appear in page titles 84# replace this with something more descriptive for clearer bookmarks 85our$site_name="++GITWEB_SITENAME++" 86|| ($ENV{'SERVER_NAME'} ||"Untitled") ." Git"; 87 88# html snippet to include in the <head> section of each page 89our$site_html_head_string="++GITWEB_SITE_HTML_HEAD_STRING++"; 90# filename of html text to include at top of each page 91our$site_header="++GITWEB_SITE_HEADER++"; 92# html text to include at home page 93our$home_text="++GITWEB_HOMETEXT++"; 94# filename of html text to include at bottom of each page 95our$site_footer="++GITWEB_SITE_FOOTER++"; 96 97# URI of stylesheets 98our@stylesheets= ("++GITWEB_CSS++"); 99# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG. 100our$stylesheet=undef; 101# URI of GIT logo (72x27 size) 102our$logo="++GITWEB_LOGO++"; 103# URI of GIT favicon, assumed to be image/png type 104our$favicon="++GITWEB_FAVICON++"; 105# URI of gitweb.js (JavaScript code for gitweb) 106our$javascript="++GITWEB_JS++"; 107 108# URI and label (title) of GIT logo link 109#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/"; 110#our $logo_label = "git documentation"; 111our$logo_url="http://git-scm.com/"; 112our$logo_label="git homepage"; 113 114# source of projects list 115our$projects_list="++GITWEB_LIST++"; 116 117# the width (in characters) of the projects list "Description" column 118our$projects_list_description_width=25; 119 120# group projects by category on the projects list 121# (enabled if this variable evaluates to true) 122our$projects_list_group_categories=0; 123 124# default category if none specified 125# (leave the empty string for no category) 126our$project_list_default_category=""; 127 128# default order of projects list 129# valid values are none, project, descr, owner, and age 130our$default_projects_order="project"; 131 132# show repository only if this file exists 133# (only effective if this variable evaluates to true) 134our$export_ok="++GITWEB_EXPORT_OK++"; 135 136# don't generate age column on the projects list page 137our$omit_age_column=0; 138 139# don't generate information about owners of repositories 140our$omit_owner=0; 141 142# show repository only if this subroutine returns true 143# when given the path to the project, for example: 144# sub { return -e "$_[0]/git-daemon-export-ok"; } 145our$export_auth_hook=undef; 146 147# only allow viewing of repositories also shown on the overview page 148our$strict_export="++GITWEB_STRICT_EXPORT++"; 149 150# list of git base URLs used for URL to where fetch project from, 151# i.e. full URL is "$git_base_url/$project" 152our@git_base_url_list=grep{$_ne''} ("++GITWEB_BASE_URL++"); 153 154# default blob_plain mimetype and default charset for text/plain blob 155our$default_blob_plain_mimetype='text/plain'; 156our$default_text_plain_charset=undef; 157 158# file to use for guessing MIME types before trying /etc/mime.types 159# (relative to the current git repository) 160our$mimetypes_file=undef; 161 162# assume this charset if line contains non-UTF-8 characters; 163# it should be valid encoding (see Encoding::Supported(3pm) for list), 164# for which encoding all byte sequences are valid, for example 165# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it 166# could be even 'utf-8' for the old behavior) 167our$fallback_encoding='latin1'; 168 169# rename detection options for git-diff and git-diff-tree 170# - default is '-M', with the cost proportional to 171# (number of removed files) * (number of new files). 172# - more costly is '-C' (which implies '-M'), with the cost proportional to 173# (number of changed files + number of removed files) * (number of new files) 174# - even more costly is '-C', '--find-copies-harder' with cost 175# (number of files in the original tree) * (number of new files) 176# - one might want to include '-B' option, e.g. '-B', '-M' 177our@diff_opts= ('-M');# taken from git_commit 178 179# Disables features that would allow repository owners to inject script into 180# the gitweb domain. 181our$prevent_xss=0; 182 183# Path to the highlight executable to use (must be the one from 184# http://www.andre-simon.de due to assumptions about parameters and output). 185# Useful if highlight is not installed on your webserver's PATH. 186# [Default: highlight] 187our$highlight_bin="++HIGHLIGHT_BIN++"; 188 189# information about snapshot formats that gitweb is capable of serving 190our%known_snapshot_formats= ( 191# name => { 192# 'display' => display name, 193# 'type' => mime type, 194# 'suffix' => filename suffix, 195# 'format' => --format for git-archive, 196# 'compressor' => [compressor command and arguments] 197# (array reference, optional) 198# 'disabled' => boolean (optional)} 199# 200'tgz'=> { 201'display'=>'tar.gz', 202'type'=>'application/x-gzip', 203'suffix'=>'.tar.gz', 204'format'=>'tar', 205'compressor'=> ['gzip','-n']}, 206 207'tbz2'=> { 208'display'=>'tar.bz2', 209'type'=>'application/x-bzip2', 210'suffix'=>'.tar.bz2', 211'format'=>'tar', 212'compressor'=> ['bzip2']}, 213 214'txz'=> { 215'display'=>'tar.xz', 216'type'=>'application/x-xz', 217'suffix'=>'.tar.xz', 218'format'=>'tar', 219'compressor'=> ['xz'], 220'disabled'=>1}, 221 222'zip'=> { 223'display'=>'zip', 224'type'=>'application/x-zip', 225'suffix'=>'.zip', 226'format'=>'zip'}, 227); 228 229# Aliases so we understand old gitweb.snapshot values in repository 230# configuration. 231our%known_snapshot_format_aliases= ( 232'gzip'=>'tgz', 233'bzip2'=>'tbz2', 234'xz'=>'txz', 235 236# backward compatibility: legacy gitweb config support 237'x-gzip'=>undef,'gz'=>undef, 238'x-bzip2'=>undef,'bz2'=>undef, 239'x-zip'=>undef,''=>undef, 240); 241 242# Pixel sizes for icons and avatars. If the default font sizes or lineheights 243# are changed, it may be appropriate to change these values too via 244# $GITWEB_CONFIG. 245our%avatar_size= ( 246'default'=>16, 247'double'=>32 248); 249 250# Used to set the maximum load that we will still respond to gitweb queries. 251# If server load exceed this value then return "503 server busy" error. 252# If gitweb cannot determined server load, it is taken to be 0. 253# Leave it undefined (or set to 'undef') to turn off load checking. 254our$maxload=300; 255 256# configuration for 'highlight' (http://www.andre-simon.de/) 257# match by basename 258our%highlight_basename= ( 259#'Program' => 'py', 260#'Library' => 'py', 261'SConstruct'=>'py',# SCons equivalent of Makefile 262'Makefile'=>'make', 263); 264# match by extension 265our%highlight_ext= ( 266# main extensions, defining name of syntax; 267# see files in /usr/share/highlight/langDefs/ directory 268map{$_=>$_} 269qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl sql make), 270# alternate extensions, see /etc/highlight/filetypes.conf 271'h'=>'c', 272map{$_=>'sh'}qw(bash zsh ksh), 273map{$_=>'cpp'}qw(cxx c++ cc), 274map{$_=>'php'}qw(php3 php4 php5 phps), 275map{$_=>'pl'}qw(perl pm),# perhaps also 'cgi' 276map{$_=>'make'}qw(mak mk), 277map{$_=>'xml'}qw(xhtml html htm), 278); 279 280# You define site-wide feature defaults here; override them with 281# $GITWEB_CONFIG as necessary. 282our%feature= ( 283# feature => { 284# 'sub' => feature-sub (subroutine), 285# 'override' => allow-override (boolean), 286# 'default' => [ default options...] (array reference)} 287# 288# if feature is overridable (it means that allow-override has true value), 289# then feature-sub will be called with default options as parameters; 290# return value of feature-sub indicates if to enable specified feature 291# 292# if there is no 'sub' key (no feature-sub), then feature cannot be 293# overridden 294# 295# use gitweb_get_feature(<feature>) to retrieve the <feature> value 296# (an array) or gitweb_check_feature(<feature>) to check if <feature> 297# is enabled 298 299# Enable the 'blame' blob view, showing the last commit that modified 300# each line in the file. This can be very CPU-intensive. 301 302# To enable system wide have in $GITWEB_CONFIG 303# $feature{'blame'}{'default'} = [1]; 304# To have project specific config enable override in $GITWEB_CONFIG 305# $feature{'blame'}{'override'} = 1; 306# and in project config gitweb.blame = 0|1; 307'blame'=> { 308'sub'=>sub{ feature_bool('blame',@_) }, 309'override'=>0, 310'default'=> [0]}, 311 312# Enable the 'snapshot' link, providing a compressed archive of any 313# tree. This can potentially generate high traffic if you have large 314# project. 315 316# Value is a list of formats defined in %known_snapshot_formats that 317# you wish to offer. 318# To disable system wide have in $GITWEB_CONFIG 319# $feature{'snapshot'}{'default'} = []; 320# To have project specific config enable override in $GITWEB_CONFIG 321# $feature{'snapshot'}{'override'} = 1; 322# and in project config, a comma-separated list of formats or "none" 323# to disable. Example: gitweb.snapshot = tbz2,zip; 324'snapshot'=> { 325'sub'=> \&feature_snapshot, 326'override'=>0, 327'default'=> ['tgz']}, 328 329# Enable text search, which will list the commits which match author, 330# committer or commit text to a given string. Enabled by default. 331# Project specific override is not supported. 332# 333# Note that this controls all search features, which means that if 334# it is disabled, then 'grep' and 'pickaxe' search would also be 335# disabled. 336'search'=> { 337'override'=>0, 338'default'=> [1]}, 339 340# Enable grep search, which will list the files in currently selected 341# tree containing the given string. Enabled by default. This can be 342# potentially CPU-intensive, of course. 343# Note that you need to have 'search' feature enabled too. 344 345# To enable system wide have in $GITWEB_CONFIG 346# $feature{'grep'}{'default'} = [1]; 347# To have project specific config enable override in $GITWEB_CONFIG 348# $feature{'grep'}{'override'} = 1; 349# and in project config gitweb.grep = 0|1; 350'grep'=> { 351'sub'=>sub{ feature_bool('grep',@_) }, 352'override'=>0, 353'default'=> [1]}, 354 355# Enable the pickaxe search, which will list the commits that modified 356# a given string in a file. This can be practical and quite faster 357# alternative to 'blame', but still potentially CPU-intensive. 358# Note that you need to have 'search' feature enabled too. 359 360# To enable system wide have in $GITWEB_CONFIG 361# $feature{'pickaxe'}{'default'} = [1]; 362# To have project specific config enable override in $GITWEB_CONFIG 363# $feature{'pickaxe'}{'override'} = 1; 364# and in project config gitweb.pickaxe = 0|1; 365'pickaxe'=> { 366'sub'=>sub{ feature_bool('pickaxe',@_) }, 367'override'=>0, 368'default'=> [1]}, 369 370# Enable showing size of blobs in a 'tree' view, in a separate 371# column, similar to what 'ls -l' does. This cost a bit of IO. 372 373# To disable system wide have in $GITWEB_CONFIG 374# $feature{'show-sizes'}{'default'} = [0]; 375# To have project specific config enable override in $GITWEB_CONFIG 376# $feature{'show-sizes'}{'override'} = 1; 377# and in project config gitweb.showsizes = 0|1; 378'show-sizes'=> { 379'sub'=>sub{ feature_bool('showsizes',@_) }, 380'override'=>0, 381'default'=> [1]}, 382 383# Make gitweb use an alternative format of the URLs which can be 384# more readable and natural-looking: project name is embedded 385# directly in the path and the query string contains other 386# auxiliary information. All gitweb installations recognize 387# URL in either format; this configures in which formats gitweb 388# generates links. 389 390# To enable system wide have in $GITWEB_CONFIG 391# $feature{'pathinfo'}{'default'} = [1]; 392# Project specific override is not supported. 393 394# Note that you will need to change the default location of CSS, 395# favicon, logo and possibly other files to an absolute URL. Also, 396# if gitweb.cgi serves as your indexfile, you will need to force 397# $my_uri to contain the script name in your $GITWEB_CONFIG. 398'pathinfo'=> { 399'override'=>0, 400'default'=> [0]}, 401 402# Make gitweb consider projects in project root subdirectories 403# to be forks of existing projects. Given project $projname.git, 404# projects matching $projname/*.git will not be shown in the main 405# projects list, instead a '+' mark will be added to $projname 406# there and a 'forks' view will be enabled for the project, listing 407# all the forks. If project list is taken from a file, forks have 408# to be listed after the main project. 409 410# To enable system wide have in $GITWEB_CONFIG 411# $feature{'forks'}{'default'} = [1]; 412# Project specific override is not supported. 413'forks'=> { 414'override'=>0, 415'default'=> [0]}, 416 417# Insert custom links to the action bar of all project pages. 418# This enables you mainly to link to third-party scripts integrating 419# into gitweb; e.g. git-browser for graphical history representation 420# or custom web-based repository administration interface. 421 422# The 'default' value consists of a list of triplets in the form 423# (label, link, position) where position is the label after which 424# to insert the link and link is a format string where %n expands 425# to the project name, %f to the project path within the filesystem, 426# %h to the current hash (h gitweb parameter) and %b to the current 427# hash base (hb gitweb parameter); %% expands to %. 428 429# To enable system wide have in $GITWEB_CONFIG e.g. 430# $feature{'actions'}{'default'} = [('graphiclog', 431# '/git-browser/by-commit.html?r=%n', 'summary')]; 432# Project specific override is not supported. 433'actions'=> { 434'override'=>0, 435'default'=> []}, 436 437# Allow gitweb scan project content tags of project repository, 438# and display the popular Web 2.0-ish "tag cloud" near the projects 439# list. Note that this is something COMPLETELY different from the 440# normal Git tags. 441 442# gitweb by itself can show existing tags, but it does not handle 443# tagging itself; you need to do it externally, outside gitweb. 444# The format is described in git_get_project_ctags() subroutine. 445# You may want to install the HTML::TagCloud Perl module to get 446# a pretty tag cloud instead of just a list of tags. 447 448# To enable system wide have in $GITWEB_CONFIG 449# $feature{'ctags'}{'default'} = [1]; 450# Project specific override is not supported. 451 452# In the future whether ctags editing is enabled might depend 453# on the value, but using 1 should always mean no editing of ctags. 454'ctags'=> { 455'override'=>0, 456'default'=> [0]}, 457 458# The maximum number of patches in a patchset generated in patch 459# view. Set this to 0 or undef to disable patch view, or to a 460# negative number to remove any limit. 461 462# To disable system wide have in $GITWEB_CONFIG 463# $feature{'patches'}{'default'} = [0]; 464# To have project specific config enable override in $GITWEB_CONFIG 465# $feature{'patches'}{'override'} = 1; 466# and in project config gitweb.patches = 0|n; 467# where n is the maximum number of patches allowed in a patchset. 468'patches'=> { 469'sub'=> \&feature_patches, 470'override'=>0, 471'default'=> [16]}, 472 473# Avatar support. When this feature is enabled, views such as 474# shortlog or commit will display an avatar associated with 475# the email of the committer(s) and/or author(s). 476 477# Currently available providers are gravatar and picon. 478# If an unknown provider is specified, the feature is disabled. 479 480# Gravatar depends on Digest::MD5. 481# Picon currently relies on the indiana.edu database. 482 483# To enable system wide have in $GITWEB_CONFIG 484# $feature{'avatar'}{'default'} = ['<provider>']; 485# where <provider> is either gravatar or picon. 486# To have project specific config enable override in $GITWEB_CONFIG 487# $feature{'avatar'}{'override'} = 1; 488# and in project config gitweb.avatar = <provider>; 489'avatar'=> { 490'sub'=> \&feature_avatar, 491'override'=>0, 492'default'=> ['']}, 493 494# Enable displaying how much time and how many git commands 495# it took to generate and display page. Disabled by default. 496# Project specific override is not supported. 497'timed'=> { 498'override'=>0, 499'default'=> [0]}, 500 501# Enable turning some links into links to actions which require 502# JavaScript to run (like 'blame_incremental'). Not enabled by 503# default. Project specific override is currently not supported. 504'javascript-actions'=> { 505'override'=>0, 506'default'=> [0]}, 507 508# Enable and configure ability to change common timezone for dates 509# in gitweb output via JavaScript. Enabled by default. 510# Project specific override is not supported. 511'javascript-timezone'=> { 512'override'=>0, 513'default'=> [ 514'local',# default timezone: 'utc', 'local', or '(-|+)HHMM' format, 515# or undef to turn off this feature 516'gitweb_tz',# name of cookie where to store selected timezone 517'datetime',# CSS class used to mark up dates for manipulation 518]}, 519 520# Syntax highlighting support. This is based on Daniel Svensson's 521# and Sham Chukoury's work in gitweb-xmms2.git. 522# It requires the 'highlight' program present in $PATH, 523# and therefore is disabled by default. 524 525# To enable system wide have in $GITWEB_CONFIG 526# $feature{'highlight'}{'default'} = [1]; 527 528'highlight'=> { 529'sub'=>sub{ feature_bool('highlight',@_) }, 530'override'=>0, 531'default'=> [0]}, 532 533# Enable displaying of remote heads in the heads list 534 535# To enable system wide have in $GITWEB_CONFIG 536# $feature{'remote_heads'}{'default'} = [1]; 537# To have project specific config enable override in $GITWEB_CONFIG 538# $feature{'remote_heads'}{'override'} = 1; 539# and in project config gitweb.remote_heads = 0|1; 540'remote_heads'=> { 541'sub'=>sub{ feature_bool('remote_heads',@_) }, 542'override'=>0, 543'default'=> [0]}, 544); 545 546sub gitweb_get_feature { 547my($name) =@_; 548return unlessexists$feature{$name}; 549my($sub,$override,@defaults) = ( 550$feature{$name}{'sub'}, 551$feature{$name}{'override'}, 552@{$feature{$name}{'default'}}); 553# project specific override is possible only if we have project 554our$git_dir;# global variable, declared later 555if(!$override|| !defined$git_dir) { 556return@defaults; 557} 558if(!defined$sub) { 559warn"feature$nameis not overridable"; 560return@defaults; 561} 562return$sub->(@defaults); 563} 564 565# A wrapper to check if a given feature is enabled. 566# With this, you can say 567# 568# my $bool_feat = gitweb_check_feature('bool_feat'); 569# gitweb_check_feature('bool_feat') or somecode; 570# 571# instead of 572# 573# my ($bool_feat) = gitweb_get_feature('bool_feat'); 574# (gitweb_get_feature('bool_feat'))[0] or somecode; 575# 576sub gitweb_check_feature { 577return(gitweb_get_feature(@_))[0]; 578} 579 580 581sub feature_bool { 582my$key=shift; 583my($val) = git_get_project_config($key,'--bool'); 584 585if(!defined$val) { 586return($_[0]); 587}elsif($valeq'true') { 588return(1); 589}elsif($valeq'false') { 590return(0); 591} 592} 593 594sub feature_snapshot { 595my(@fmts) =@_; 596 597my($val) = git_get_project_config('snapshot'); 598 599if($val) { 600@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 601} 602 603return@fmts; 604} 605 606sub feature_patches { 607my@val= (git_get_project_config('patches','--int')); 608 609if(@val) { 610return@val; 611} 612 613return($_[0]); 614} 615 616sub feature_avatar { 617my@val= (git_get_project_config('avatar')); 618 619return@val?@val:@_; 620} 621 622# checking HEAD file with -e is fragile if the repository was 623# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 624# and then pruned. 625sub check_head_link { 626my($dir) =@_; 627my$headfile="$dir/HEAD"; 628return((-e $headfile) || 629(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 630} 631 632sub check_export_ok { 633my($dir) =@_; 634return(check_head_link($dir) && 635(!$export_ok|| -e "$dir/$export_ok") && 636(!$export_auth_hook||$export_auth_hook->($dir))); 637} 638 639# process alternate names for backward compatibility 640# filter out unsupported (unknown) snapshot formats 641sub filter_snapshot_fmts { 642my@fmts=@_; 643 644@fmts=map{ 645exists$known_snapshot_format_aliases{$_} ? 646$known_snapshot_format_aliases{$_} :$_}@fmts; 647@fmts=grep{ 648exists$known_snapshot_formats{$_} && 649!$known_snapshot_formats{$_}{'disabled'}}@fmts; 650} 651 652# If it is set to code reference, it is code that it is to be run once per 653# request, allowing updating configurations that change with each request, 654# while running other code in config file only once. 655# 656# Otherwise, if it is false then gitweb would process config file only once; 657# if it is true then gitweb config would be run for each request. 658our$per_request_config=1; 659 660# read and parse gitweb config file given by its parameter. 661# returns true on success, false on recoverable error, allowing 662# to chain this subroutine, using first file that exists. 663# dies on errors during parsing config file, as it is unrecoverable. 664sub read_config_file { 665my$filename=shift; 666return unlessdefined$filename; 667# die if there are errors parsing config file 668if(-e $filename) { 669do$filename; 670die$@if$@; 671return1; 672} 673return; 674} 675 676our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM,$GITWEB_CONFIG_COMMON); 677sub evaluate_gitweb_config { 678our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 679our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 680our$GITWEB_CONFIG_COMMON=$ENV{'GITWEB_CONFIG_COMMON'} ||"++GITWEB_CONFIG_COMMON++"; 681 682# Protect agains duplications of file names, to not read config twice. 683# Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so 684# there possibility of duplication of filename there doesn't matter. 685$GITWEB_CONFIG=""if($GITWEB_CONFIGeq$GITWEB_CONFIG_COMMON); 686$GITWEB_CONFIG_SYSTEM=""if($GITWEB_CONFIG_SYSTEMeq$GITWEB_CONFIG_COMMON); 687 688# Common system-wide settings for convenience. 689# Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM. 690 read_config_file($GITWEB_CONFIG_COMMON); 691 692# Use first config file that exists. This means use the per-instance 693# GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG. 694 read_config_file($GITWEB_CONFIG)andreturn; 695 read_config_file($GITWEB_CONFIG_SYSTEM); 696} 697 698# Get loadavg of system, to compare against $maxload. 699# Currently it requires '/proc/loadavg' present to get loadavg; 700# if it is not present it returns 0, which means no load checking. 701sub get_loadavg { 702if( -e '/proc/loadavg'){ 703open my$fd,'<','/proc/loadavg' 704orreturn0; 705my@load=split(/\s+/,scalar<$fd>); 706close$fd; 707 708# The first three columns measure CPU and IO utilization of the last one, 709# five, and 10 minute periods. The fourth column shows the number of 710# currently running processes and the total number of processes in the m/n 711# format. The last column displays the last process ID used. 712return$load[0] ||0; 713} 714# additional checks for load average should go here for things that don't export 715# /proc/loadavg 716 717return0; 718} 719 720# version of the core git binary 721our$git_version; 722sub evaluate_git_version { 723our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 724$number_of_git_cmds++; 725} 726 727sub check_loadavg { 728if(defined$maxload&& get_loadavg() >$maxload) { 729 die_error(503,"The load average on the server is too high"); 730} 731} 732 733# ====================================================================== 734# input validation and dispatch 735 736# input parameters can be collected from a variety of sources (presently, CGI 737# and PATH_INFO), so we define an %input_params hash that collects them all 738# together during validation: this allows subsequent uses (e.g. href()) to be 739# agnostic of the parameter origin 740 741our%input_params= (); 742 743# input parameters are stored with the long parameter name as key. This will 744# also be used in the href subroutine to convert parameters to their CGI 745# equivalent, and since the href() usage is the most frequent one, we store 746# the name -> CGI key mapping here, instead of the reverse. 747# 748# XXX: Warning: If you touch this, check the search form for updating, 749# too. 750 751our@cgi_param_mapping= ( 752 project =>"p", 753 action =>"a", 754 file_name =>"f", 755 file_parent =>"fp", 756 hash =>"h", 757 hash_parent =>"hp", 758 hash_base =>"hb", 759 hash_parent_base =>"hpb", 760 page =>"pg", 761 order =>"o", 762 searchtext =>"s", 763 searchtype =>"st", 764 snapshot_format =>"sf", 765 extra_options =>"opt", 766 search_use_regexp =>"sr", 767 ctag =>"by_tag", 768 diff_style =>"ds", 769 project_filter =>"pf", 770# this must be last entry (for manipulation from JavaScript) 771 javascript =>"js" 772); 773our%cgi_param_mapping=@cgi_param_mapping; 774 775# we will also need to know the possible actions, for validation 776our%actions= ( 777"blame"=> \&git_blame, 778"blame_incremental"=> \&git_blame_incremental, 779"blame_data"=> \&git_blame_data, 780"blobdiff"=> \&git_blobdiff, 781"blobdiff_plain"=> \&git_blobdiff_plain, 782"blob"=> \&git_blob, 783"blob_plain"=> \&git_blob_plain, 784"commitdiff"=> \&git_commitdiff, 785"commitdiff_plain"=> \&git_commitdiff_plain, 786"commit"=> \&git_commit, 787"forks"=> \&git_forks, 788"heads"=> \&git_heads, 789"history"=> \&git_history, 790"log"=> \&git_log, 791"patch"=> \&git_patch, 792"patches"=> \&git_patches, 793"remotes"=> \&git_remotes, 794"rss"=> \&git_rss, 795"atom"=> \&git_atom, 796"search"=> \&git_search, 797"search_help"=> \&git_search_help, 798"shortlog"=> \&git_shortlog, 799"summary"=> \&git_summary, 800"tag"=> \&git_tag, 801"tags"=> \&git_tags, 802"tree"=> \&git_tree, 803"snapshot"=> \&git_snapshot, 804"object"=> \&git_object, 805# those below don't need $project 806"opml"=> \&git_opml, 807"project_list"=> \&git_project_list, 808"project_index"=> \&git_project_index, 809); 810 811# finally, we have the hash of allowed extra_options for the commands that 812# allow them 813our%allowed_options= ( 814"--no-merges"=> [qw(rss atom log shortlog history)], 815); 816 817# fill %input_params with the CGI parameters. All values except for 'opt' 818# should be single values, but opt can be an array. We should probably 819# build an array of parameters that can be multi-valued, but since for the time 820# being it's only this one, we just single it out 821sub evaluate_query_params { 822our$cgi; 823 824while(my($name,$symbol) =each%cgi_param_mapping) { 825if($symboleq'opt') { 826$input_params{$name} = [map{ decode_utf8($_) }$cgi->param($symbol) ]; 827}else{ 828$input_params{$name} = decode_utf8($cgi->param($symbol)); 829} 830} 831} 832 833# now read PATH_INFO and update the parameter list for missing parameters 834sub evaluate_path_info { 835return ifdefined$input_params{'project'}; 836return if!$path_info; 837$path_info=~ s,^/+,,; 838return if!$path_info; 839 840# find which part of PATH_INFO is project 841my$project=$path_info; 842$project=~ s,/+$,,; 843while($project&& !check_head_link("$projectroot/$project")) { 844$project=~ s,/*[^/]*$,,; 845} 846return unless$project; 847$input_params{'project'} =$project; 848 849# do not change any parameters if an action is given using the query string 850return if$input_params{'action'}; 851$path_info=~ s,^\Q$project\E/*,,; 852 853# next, check if we have an action 854my$action=$path_info; 855$action=~ s,/.*$,,; 856if(exists$actions{$action}) { 857$path_info=~ s,^$action/*,,; 858$input_params{'action'} =$action; 859} 860 861# list of actions that want hash_base instead of hash, but can have no 862# pathname (f) parameter 863my@wants_base= ( 864'tree', 865'history', 866); 867 868# we want to catch, among others 869# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 870my($parentrefname,$parentpathname,$refname,$pathname) = 871($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/); 872 873# first, analyze the 'current' part 874if(defined$pathname) { 875# we got "branch:filename" or "branch:dir/" 876# we could use git_get_type(branch:pathname), but: 877# - it needs $git_dir 878# - it does a git() call 879# - the convention of terminating directories with a slash 880# makes it superfluous 881# - embedding the action in the PATH_INFO would make it even 882# more superfluous 883$pathname=~ s,^/+,,; 884if(!$pathname||substr($pathname, -1)eq"/") { 885$input_params{'action'} ||="tree"; 886$pathname=~ s,/$,,; 887}else{ 888# the default action depends on whether we had parent info 889# or not 890if($parentrefname) { 891$input_params{'action'} ||="blobdiff_plain"; 892}else{ 893$input_params{'action'} ||="blob_plain"; 894} 895} 896$input_params{'hash_base'} ||=$refname; 897$input_params{'file_name'} ||=$pathname; 898}elsif(defined$refname) { 899# we got "branch". In this case we have to choose if we have to 900# set hash or hash_base. 901# 902# Most of the actions without a pathname only want hash to be 903# set, except for the ones specified in @wants_base that want 904# hash_base instead. It should also be noted that hand-crafted 905# links having 'history' as an action and no pathname or hash 906# set will fail, but that happens regardless of PATH_INFO. 907if(defined$parentrefname) { 908# if there is parent let the default be 'shortlog' action 909# (for http://git.example.com/repo.git/A..B links); if there 910# is no parent, dispatch will detect type of object and set 911# action appropriately if required (if action is not set) 912$input_params{'action'} ||="shortlog"; 913} 914if($input_params{'action'} && 915grep{$_eq$input_params{'action'} }@wants_base) { 916$input_params{'hash_base'} ||=$refname; 917}else{ 918$input_params{'hash'} ||=$refname; 919} 920} 921 922# next, handle the 'parent' part, if present 923if(defined$parentrefname) { 924# a missing pathspec defaults to the 'current' filename, allowing e.g. 925# someproject/blobdiff/oldrev..newrev:/filename 926if($parentpathname) { 927$parentpathname=~ s,^/+,,; 928$parentpathname=~ s,/$,,; 929$input_params{'file_parent'} ||=$parentpathname; 930}else{ 931$input_params{'file_parent'} ||=$input_params{'file_name'}; 932} 933# we assume that hash_parent_base is wanted if a path was specified, 934# or if the action wants hash_base instead of hash 935if(defined$input_params{'file_parent'} || 936grep{$_eq$input_params{'action'} }@wants_base) { 937$input_params{'hash_parent_base'} ||=$parentrefname; 938}else{ 939$input_params{'hash_parent'} ||=$parentrefname; 940} 941} 942 943# for the snapshot action, we allow URLs in the form 944# $project/snapshot/$hash.ext 945# where .ext determines the snapshot and gets removed from the 946# passed $refname to provide the $hash. 947# 948# To be able to tell that $refname includes the format extension, we 949# require the following two conditions to be satisfied: 950# - the hash input parameter MUST have been set from the $refname part 951# of the URL (i.e. they must be equal) 952# - the snapshot format MUST NOT have been defined already (e.g. from 953# CGI parameter sf) 954# It's also useless to try any matching unless $refname has a dot, 955# so we check for that too 956if(defined$input_params{'action'} && 957$input_params{'action'}eq'snapshot'&& 958defined$refname&&index($refname,'.') != -1&& 959$refnameeq$input_params{'hash'} && 960!defined$input_params{'snapshot_format'}) { 961# We loop over the known snapshot formats, checking for 962# extensions. Allowed extensions are both the defined suffix 963# (which includes the initial dot already) and the snapshot 964# format key itself, with a prepended dot 965while(my($fmt,$opt) =each%known_snapshot_formats) { 966my$hash=$refname; 967unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 968next; 969} 970my$sfx=$1; 971# a valid suffix was found, so set the snapshot format 972# and reset the hash parameter 973$input_params{'snapshot_format'} =$fmt; 974$input_params{'hash'} =$hash; 975# we also set the format suffix to the one requested 976# in the URL: this way a request for e.g. .tgz returns 977# a .tgz instead of a .tar.gz 978$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 979last; 980} 981} 982} 983 984our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 985$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 986$searchtext,$search_regexp,$project_filter); 987sub evaluate_and_validate_params { 988our$action=$input_params{'action'}; 989if(defined$action) { 990if(!validate_action($action)) { 991 die_error(400,"Invalid action parameter"); 992} 993} 994 995# parameters which are pathnames 996our$project=$input_params{'project'}; 997if(defined$project) { 998if(!validate_project($project)) { 999undef$project;1000 die_error(404,"No such project");1001}1002}10031004our$project_filter=$input_params{'project_filter'};1005if(defined$project_filter) {1006if(!validate_pathname($project_filter)) {1007 die_error(404,"Invalid project_filter parameter");1008}1009}10101011our$file_name=$input_params{'file_name'};1012if(defined$file_name) {1013if(!validate_pathname($file_name)) {1014 die_error(400,"Invalid file parameter");1015}1016}10171018our$file_parent=$input_params{'file_parent'};1019if(defined$file_parent) {1020if(!validate_pathname($file_parent)) {1021 die_error(400,"Invalid file parent parameter");1022}1023}10241025# parameters which are refnames1026our$hash=$input_params{'hash'};1027if(defined$hash) {1028if(!validate_refname($hash)) {1029 die_error(400,"Invalid hash parameter");1030}1031}10321033our$hash_parent=$input_params{'hash_parent'};1034if(defined$hash_parent) {1035if(!validate_refname($hash_parent)) {1036 die_error(400,"Invalid hash parent parameter");1037}1038}10391040our$hash_base=$input_params{'hash_base'};1041if(defined$hash_base) {1042if(!validate_refname($hash_base)) {1043 die_error(400,"Invalid hash base parameter");1044}1045}10461047our@extra_options= @{$input_params{'extra_options'}};1048# @extra_options is always defined, since it can only be (currently) set from1049# CGI, and $cgi->param() returns the empty array in array context if the param1050# is not set1051foreachmy$opt(@extra_options) {1052if(not exists$allowed_options{$opt}) {1053 die_error(400,"Invalid option parameter");1054}1055if(not grep(/^$action$/, @{$allowed_options{$opt}})) {1056 die_error(400,"Invalid option parameter for this action");1057}1058}10591060our$hash_parent_base=$input_params{'hash_parent_base'};1061if(defined$hash_parent_base) {1062if(!validate_refname($hash_parent_base)) {1063 die_error(400,"Invalid hash parent base parameter");1064}1065}10661067# other parameters1068our$page=$input_params{'page'};1069if(defined$page) {1070if($page=~m/[^0-9]/) {1071 die_error(400,"Invalid page parameter");1072}1073}10741075our$searchtype=$input_params{'searchtype'};1076if(defined$searchtype) {1077if($searchtype=~m/[^a-z]/) {1078 die_error(400,"Invalid searchtype parameter");1079}1080}10811082our$search_use_regexp=$input_params{'search_use_regexp'};10831084our$searchtext=$input_params{'searchtext'};1085our$search_regexp;1086if(defined$searchtext) {1087if(length($searchtext) <2) {1088 die_error(403,"At least two characters are required for search parameter");1089}1090if($search_use_regexp) {1091$search_regexp=$searchtext;1092if(!eval{qr/$search_regexp/;1; }) {1093(my$error=$@) =~s/ at \S+ line \d+.*\n?//;1094 die_error(400,"Invalid search regexp '$search_regexp'",1095 esc_html($error));1096}1097}else{1098$search_regexp=quotemeta$searchtext;1099}1100}1101}11021103# path to the current git repository1104our$git_dir;1105sub evaluate_git_dir {1106our$git_dir="$projectroot/$project"if$project;1107}11081109our(@snapshot_fmts,$git_avatar);1110sub configure_gitweb_features {1111# list of supported snapshot formats1112our@snapshot_fmts= gitweb_get_feature('snapshot');1113@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);11141115# check that the avatar feature is set to a known provider name,1116# and for each provider check if the dependencies are satisfied.1117# if the provider name is invalid or the dependencies are not met,1118# reset $git_avatar to the empty string.1119our($git_avatar) = gitweb_get_feature('avatar');1120if($git_avatareq'gravatar') {1121$git_avatar=''unless(eval{require Digest::MD5;1; });1122}elsif($git_avatareq'picon') {1123# no dependencies1124}else{1125$git_avatar='';1126}1127}11281129# custom error handler: 'die <message>' is Internal Server Error1130sub handle_errors_html {1131my$msg=shift;# it is already HTML escaped11321133# to avoid infinite loop where error occurs in die_error,1134# change handler to default handler, disabling handle_errors_html1135 set_message("Error occured when inside die_error:\n$msg");11361137# you cannot jump out of die_error when called as error handler;1138# the subroutine set via CGI::Carp::set_message is called _after_1139# HTTP headers are already written, so it cannot write them itself1140 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1141}1142set_message(\&handle_errors_html);11431144# dispatch1145sub dispatch {1146if(!defined$action) {1147if(defined$hash) {1148$action= git_get_type($hash);1149$actionor die_error(404,"Object does not exist");1150}elsif(defined$hash_base&&defined$file_name) {1151$action= git_get_type("$hash_base:$file_name");1152$actionor die_error(404,"File or directory does not exist");1153}elsif(defined$project) {1154$action='summary';1155}else{1156$action='project_list';1157}1158}1159if(!defined($actions{$action})) {1160 die_error(400,"Unknown action");1161}1162if($action!~m/^(?:opml|project_list|project_index)$/&&1163!$project) {1164 die_error(400,"Project needed");1165}1166$actions{$action}->();1167}11681169sub reset_timer {1170our$t0= [ gettimeofday() ]1171ifdefined$t0;1172our$number_of_git_cmds=0;1173}11741175our$first_request=1;1176sub run_request {1177 reset_timer();11781179 evaluate_uri();1180if($first_request) {1181 evaluate_gitweb_config();1182 evaluate_git_version();1183}1184if($per_request_config) {1185if(ref($per_request_config)eq'CODE') {1186$per_request_config->();1187}elsif(!$first_request) {1188 evaluate_gitweb_config();1189}1190}1191 check_loadavg();11921193# $projectroot and $projects_list might be set in gitweb config file1194$projects_list||=$projectroot;11951196 evaluate_query_params();1197 evaluate_path_info();1198 evaluate_and_validate_params();1199 evaluate_git_dir();12001201 configure_gitweb_features();12021203 dispatch();1204}12051206our$is_last_request=sub{1};1207our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1208our$CGI='CGI';1209our$cgi;1210sub configure_as_fcgi {1211require CGI::Fast;1212our$CGI='CGI::Fast';12131214my$request_number=0;1215# let each child service 100 requests1216our$is_last_request=sub{ ++$request_number>100};1217}1218sub evaluate_argv {1219my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1220 configure_as_fcgi()1221if$script_name=~/\.fcgi$/;12221223return unless(@ARGV);12241225require Getopt::Long;1226 Getopt::Long::GetOptions(1227'fastcgi|fcgi|f'=> \&configure_as_fcgi,1228'nproc|n=i'=>sub{1229my($arg,$val) =@_;1230return unlesseval{require FCGI::ProcManager;1; };1231my$proc_manager= FCGI::ProcManager->new({1232 n_processes =>$val,1233});1234our$pre_listen_hook=sub{$proc_manager->pm_manage() };1235our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1236our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1237},1238);1239}12401241sub run {1242 evaluate_argv();12431244$first_request=1;1245$pre_listen_hook->()1246if$pre_listen_hook;12471248 REQUEST:1249while($cgi=$CGI->new()) {1250$pre_dispatch_hook->()1251if$pre_dispatch_hook;12521253 run_request();12541255$post_dispatch_hook->()1256if$post_dispatch_hook;1257$first_request=0;12581259last REQUEST if($is_last_request->());1260}12611262 DONE_GITWEB:12631;1264}12651266run();12671268if(defined caller) {1269# wrapped in a subroutine processing requests,1270# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1271return;1272}else{1273# pure CGI script, serving single request1274exit;1275}12761277## ======================================================================1278## action links12791280# possible values of extra options1281# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1282# -replay => 1 - start from a current view (replay with modifications)1283# -path_info => 0|1 - don't use/use path_info URL (if possible)1284# -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone1285sub href {1286my%params=@_;1287# default is to use -absolute url() i.e. $my_uri1288my$href=$params{-full} ?$my_url:$my_uri;12891290# implicit -replay, must be first of implicit params1291$params{-replay} =1if(keys%params==1&&$params{-anchor});12921293$params{'project'} =$projectunlessexists$params{'project'};12941295if($params{-replay}) {1296while(my($name,$symbol) =each%cgi_param_mapping) {1297if(!exists$params{$name}) {1298$params{$name} =$input_params{$name};1299}1300}1301}13021303my$use_pathinfo= gitweb_check_feature('pathinfo');1304if(defined$params{'project'} &&1305(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1306# try to put as many parameters as possible in PATH_INFO:1307# - project name1308# - action1309# - hash_parent or hash_parent_base:/file_parent1310# - hash or hash_base:/filename1311# - the snapshot_format as an appropriate suffix13121313# When the script is the root DirectoryIndex for the domain,1314# $href here would be something like http://gitweb.example.com/1315# Thus, we strip any trailing / from $href, to spare us double1316# slashes in the final URL1317$href=~ s,/$,,;13181319# Then add the project name, if present1320$href.="/".esc_path_info($params{'project'});1321delete$params{'project'};13221323# since we destructively absorb parameters, we keep this1324# boolean that remembers if we're handling a snapshot1325my$is_snapshot=$params{'action'}eq'snapshot';13261327# Summary just uses the project path URL, any other action is1328# added to the URL1329if(defined$params{'action'}) {1330$href.="/".esc_path_info($params{'action'})1331unless$params{'action'}eq'summary';1332delete$params{'action'};1333}13341335# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1336# stripping nonexistent or useless pieces1337$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1338||$params{'hash_parent'} ||$params{'hash'});1339if(defined$params{'hash_base'}) {1340if(defined$params{'hash_parent_base'}) {1341$href.= esc_path_info($params{'hash_parent_base'});1342# skip the file_parent if it's the same as the file_name1343if(defined$params{'file_parent'}) {1344if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1345delete$params{'file_parent'};1346}elsif($params{'file_parent'} !~/\.\./) {1347$href.=":/".esc_path_info($params{'file_parent'});1348delete$params{'file_parent'};1349}1350}1351$href.="..";1352delete$params{'hash_parent'};1353delete$params{'hash_parent_base'};1354}elsif(defined$params{'hash_parent'}) {1355$href.= esc_path_info($params{'hash_parent'})."..";1356delete$params{'hash_parent'};1357}13581359$href.= esc_path_info($params{'hash_base'});1360if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1361$href.=":/".esc_path_info($params{'file_name'});1362delete$params{'file_name'};1363}1364delete$params{'hash'};1365delete$params{'hash_base'};1366}elsif(defined$params{'hash'}) {1367$href.= esc_path_info($params{'hash'});1368delete$params{'hash'};1369}13701371# If the action was a snapshot, we can absorb the1372# snapshot_format parameter too1373if($is_snapshot) {1374my$fmt=$params{'snapshot_format'};1375# snapshot_format should always be defined when href()1376# is called, but just in case some code forgets, we1377# fall back to the default1378$fmt||=$snapshot_fmts[0];1379$href.=$known_snapshot_formats{$fmt}{'suffix'};1380delete$params{'snapshot_format'};1381}1382}13831384# now encode the parameters explicitly1385my@result= ();1386for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1387my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1388if(defined$params{$name}) {1389if(ref($params{$name})eq"ARRAY") {1390foreachmy$par(@{$params{$name}}) {1391push@result,$symbol."=". esc_param($par);1392}1393}else{1394push@result,$symbol."=". esc_param($params{$name});1395}1396}1397}1398$href.="?".join(';',@result)ifscalar@result;13991400# final transformation: trailing spaces must be escaped (URI-encoded)1401$href=~s/(\s+)$/CGI::escape($1)/e;14021403if($params{-anchor}) {1404$href.="#".esc_param($params{-anchor});1405}14061407return$href;1408}140914101411## ======================================================================1412## validation, quoting/unquoting and escaping14131414sub validate_action {1415my$input=shift||returnundef;1416returnundefunlessexists$actions{$input};1417return$input;1418}14191420sub validate_project {1421my$input=shift||returnundef;1422if(!validate_pathname($input) ||1423!(-d "$projectroot/$input") ||1424!check_export_ok("$projectroot/$input") ||1425($strict_export&& !project_in_list($input))) {1426returnundef;1427}else{1428return$input;1429}1430}14311432sub validate_pathname {1433my$input=shift||returnundef;14341435# no '.' or '..' as elements of path, i.e. no '.' nor '..'1436# at the beginning, at the end, and between slashes.1437# also this catches doubled slashes1438if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1439returnundef;1440}1441# no null characters1442if($input=~m!\0!) {1443returnundef;1444}1445return$input;1446}14471448sub validate_refname {1449my$input=shift||returnundef;14501451# textual hashes are O.K.1452if($input=~m/^[0-9a-fA-F]{40}$/) {1453return$input;1454}1455# it must be correct pathname1456$input= validate_pathname($input)1457orreturnundef;1458# restrictions on ref name according to git-check-ref-format1459if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1460returnundef;1461}1462return$input;1463}14641465# decode sequences of octets in utf8 into Perl's internal form,1466# which is utf-8 with utf8 flag set if needed. gitweb writes out1467# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1468sub to_utf8 {1469my$str=shift;1470returnundefunlessdefined$str;14711472if(utf8::is_utf8($str) || utf8::decode($str)) {1473return$str;1474}else{1475return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1476}1477}14781479# quote unsafe chars, but keep the slash, even when it's not1480# correct, but quoted slashes look too horrible in bookmarks1481sub esc_param {1482my$str=shift;1483returnundefunlessdefined$str;1484$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1485$str=~s/ /\+/g;1486return$str;1487}14881489# the quoting rules for path_info fragment are slightly different1490sub esc_path_info {1491my$str=shift;1492returnundefunlessdefined$str;14931494# path_info doesn't treat '+' as space (specially), but '?' must be escaped1495$str=~s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;14961497return$str;1498}14991500# quote unsafe chars in whole URL, so some characters cannot be quoted1501sub esc_url {1502my$str=shift;1503returnundefunlessdefined$str;1504$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1505$str=~s/ /\+/g;1506return$str;1507}15081509# quote unsafe characters in HTML attributes1510sub esc_attr {15111512# for XHTML conformance escaping '"' to '"' is not enough1513return esc_html(@_);1514}15151516# replace invalid utf8 character with SUBSTITUTION sequence1517sub esc_html {1518my$str=shift;1519my%opts=@_;15201521returnundefunlessdefined$str;15221523$str= to_utf8($str);1524$str=$cgi->escapeHTML($str);1525if($opts{'-nbsp'}) {1526$str=~s/ / /g;1527}1528$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1529return$str;1530}15311532# quote control characters and escape filename to HTML1533sub esc_path {1534my$str=shift;1535my%opts=@_;15361537returnundefunlessdefined$str;15381539$str= to_utf8($str);1540$str=$cgi->escapeHTML($str);1541if($opts{'-nbsp'}) {1542$str=~s/ / /g;1543}1544$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1545return$str;1546}15471548# Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)1549sub sanitize {1550my$str=shift;15511552returnundefunlessdefined$str;15531554$str= to_utf8($str);1555$str=~ s|([[:cntrl:]])|($1=~/[\t\n\r]/?$1: quot_cec($1))|eg;1556return$str;1557}15581559# Make control characters "printable", using character escape codes (CEC)1560sub quot_cec {1561my$cntrl=shift;1562my%opts=@_;1563my%es= (# character escape codes, aka escape sequences1564"\t"=>'\t',# tab (HT)1565"\n"=>'\n',# line feed (LF)1566"\r"=>'\r',# carrige return (CR)1567"\f"=>'\f',# form feed (FF)1568"\b"=>'\b',# backspace (BS)1569"\a"=>'\a',# alarm (bell) (BEL)1570"\e"=>'\e',# escape (ESC)1571"\013"=>'\v',# vertical tab (VT)1572"\000"=>'\0',# nul character (NUL)1573);1574my$chr= ( (exists$es{$cntrl})1575?$es{$cntrl}1576:sprintf('\%2x',ord($cntrl)) );1577if($opts{-nohtml}) {1578return$chr;1579}else{1580return"<span class=\"cntrl\">$chr</span>";1581}1582}15831584# Alternatively use unicode control pictures codepoints,1585# Unicode "printable representation" (PR)1586sub quot_upr {1587my$cntrl=shift;1588my%opts=@_;15891590my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1591if($opts{-nohtml}) {1592return$chr;1593}else{1594return"<span class=\"cntrl\">$chr</span>";1595}1596}15971598# git may return quoted and escaped filenames1599sub unquote {1600my$str=shift;16011602sub unq {1603my$seq=shift;1604my%es= (# character escape codes, aka escape sequences1605't'=>"\t",# tab (HT, TAB)1606'n'=>"\n",# newline (NL)1607'r'=>"\r",# return (CR)1608'f'=>"\f",# form feed (FF)1609'b'=>"\b",# backspace (BS)1610'a'=>"\a",# alarm (bell) (BEL)1611'e'=>"\e",# escape (ESC)1612'v'=>"\013",# vertical tab (VT)1613);16141615if($seq=~m/^[0-7]{1,3}$/) {1616# octal char sequence1617returnchr(oct($seq));1618}elsif(exists$es{$seq}) {1619# C escape sequence, aka character escape code1620return$es{$seq};1621}1622# quoted ordinary character1623return$seq;1624}16251626if($str=~m/^"(.*)"$/) {1627# needs unquoting1628$str=$1;1629$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1630}1631return$str;1632}16331634# escape tabs (convert tabs to spaces)1635sub untabify {1636my$line=shift;16371638while((my$pos=index($line,"\t")) != -1) {1639if(my$count= (8- ($pos%8))) {1640my$spaces=' ' x $count;1641$line=~s/\t/$spaces/;1642}1643}16441645return$line;1646}16471648sub project_in_list {1649my$project=shift;1650my@list= git_get_projects_list();1651return@list&&scalar(grep{$_->{'path'}eq$project}@list);1652}16531654## ----------------------------------------------------------------------1655## HTML aware string manipulation16561657# Try to chop given string on a word boundary between position1658# $len and $len+$add_len. If there is no word boundary there,1659# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1660# (marking chopped part) would be longer than given string.1661sub chop_str {1662my$str=shift;1663my$len=shift;1664my$add_len=shift||10;1665my$where=shift||'right';# 'left' | 'center' | 'right'16661667# Make sure perl knows it is utf8 encoded so we don't1668# cut in the middle of a utf8 multibyte char.1669$str= to_utf8($str);16701671# allow only $len chars, but don't cut a word if it would fit in $add_len1672# if it doesn't fit, cut it if it's still longer than the dots we would add1673# remove chopped character entities entirely16741675# when chopping in the middle, distribute $len into left and right part1676# return early if chopping wouldn't make string shorter1677if($whereeq'center') {1678return$strif($len+5>=length($str));# filler is length 51679$len=int($len/2);1680}else{1681return$strif($len+4>=length($str));# filler is length 41682}16831684# regexps: ending and beginning with word part up to $add_len1685my$endre=qr/.{$len}\w{0,$add_len}/;1686my$begre=qr/\w{0,$add_len}.{$len}/;16871688if($whereeq'left') {1689$str=~m/^(.*?)($begre)$/;1690my($lead,$body) = ($1,$2);1691if(length($lead) >4) {1692$lead=" ...";1693}1694return"$lead$body";16951696}elsif($whereeq'center') {1697$str=~m/^($endre)(.*)$/;1698my($left,$str) = ($1,$2);1699$str=~m/^(.*?)($begre)$/;1700my($mid,$right) = ($1,$2);1701if(length($mid) >5) {1702$mid=" ... ";1703}1704return"$left$mid$right";17051706}else{1707$str=~m/^($endre)(.*)$/;1708my$body=$1;1709my$tail=$2;1710if(length($tail) >4) {1711$tail="... ";1712}1713return"$body$tail";1714}1715}17161717# takes the same arguments as chop_str, but also wraps a <span> around the1718# result with a title attribute if it does get chopped. Additionally, the1719# string is HTML-escaped.1720sub chop_and_escape_str {1721my($str) =@_;17221723my$chopped= chop_str(@_);1724$str= to_utf8($str);1725if($choppedeq$str) {1726return esc_html($chopped);1727}else{1728$str=~s/[[:cntrl:]]/?/g;1729return$cgi->span({-title=>$str}, esc_html($chopped));1730}1731}17321733# Highlight selected fragments of string, using given CSS class,1734# and escape HTML. It is assumed that fragments do not overlap.1735# Regions are passed as list of pairs (array references).1736#1737# Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns1738# '<span class="mark">foo</span>bar'1739sub esc_html_hl_regions {1740my($str,$css_class,@sel) =@_;1741my%opts=grep{ref($_)ne'ARRAY'}@sel;1742@sel=grep{ref($_)eq'ARRAY'}@sel;1743return esc_html($str,%opts)unless@sel;17441745my$out='';1746my$pos=0;17471748formy$s(@sel) {1749my($begin,$end) =@$s;17501751# Don't create empty <span> elements.1752next if$end<=$begin;17531754my$escaped= esc_html(substr($str,$begin,$end-$begin),1755%opts);17561757$out.= esc_html(substr($str,$pos,$begin-$pos),%opts)1758if($begin-$pos>0);1759$out.=$cgi->span({-class=>$css_class},$escaped);17601761$pos=$end;1762}1763$out.= esc_html(substr($str,$pos),%opts)1764if($pos<length($str));17651766return$out;1767}17681769# return positions of beginning and end of each match1770sub matchpos_list {1771my($str,$regexp) =@_;1772return unless(defined$str&&defined$regexp);17731774my@matches;1775while($str=~/$regexp/g) {1776push@matches, [$-[0],$+[0]];1777}1778return@matches;1779}17801781# highlight match (if any), and escape HTML1782sub esc_html_match_hl {1783my($str,$regexp) =@_;1784return esc_html($str)unlessdefined$regexp;17851786my@matches= matchpos_list($str,$regexp);1787return esc_html($str)unless@matches;17881789return esc_html_hl_regions($str,'match',@matches);1790}179117921793# highlight match (if any) of shortened string, and escape HTML1794sub esc_html_match_hl_chopped {1795my($str,$chopped,$regexp) =@_;1796return esc_html_match_hl($str,$regexp)unlessdefined$chopped;17971798my@matches= matchpos_list($str,$regexp);1799return esc_html($chopped)unless@matches;18001801# filter matches so that we mark chopped string1802my$tail="... ";# see chop_str1803unless($chopped=~s/\Q$tail\E$//) {1804$tail='';1805}1806my$chop_len=length($chopped);1807my$tail_len=length($tail);1808my@filtered;18091810formy$m(@matches) {1811if($m->[0] >$chop_len) {1812push@filtered, [$chop_len,$chop_len+$tail_len]if($tail_len>0);1813last;1814}elsif($m->[1] >$chop_len) {1815push@filtered, [$m->[0],$chop_len+$tail_len];1816last;1817}1818push@filtered,$m;1819}18201821return esc_html_hl_regions($chopped.$tail,'match',@filtered);1822}18231824## ----------------------------------------------------------------------1825## functions returning short strings18261827# CSS class for given age value (in seconds)1828sub age_class {1829my$age=shift;18301831if(!defined$age) {1832return"noage";1833}elsif($age<60*60*2) {1834return"age0";1835}elsif($age<60*60*24*2) {1836return"age1";1837}else{1838return"age2";1839}1840}18411842# convert age in seconds to "nn units ago" string1843sub age_string {1844my$age=shift;1845my$age_str;18461847if($age>60*60*24*365*2) {1848$age_str= (int$age/60/60/24/365);1849$age_str.=" years ago";1850}elsif($age>60*60*24*(365/12)*2) {1851$age_str=int$age/60/60/24/(365/12);1852$age_str.=" months ago";1853}elsif($age>60*60*24*7*2) {1854$age_str=int$age/60/60/24/7;1855$age_str.=" weeks ago";1856}elsif($age>60*60*24*2) {1857$age_str=int$age/60/60/24;1858$age_str.=" days ago";1859}elsif($age>60*60*2) {1860$age_str=int$age/60/60;1861$age_str.=" hours ago";1862}elsif($age>60*2) {1863$age_str=int$age/60;1864$age_str.=" min ago";1865}elsif($age>2) {1866$age_str=int$age;1867$age_str.=" sec ago";1868}else{1869$age_str.=" right now";1870}1871return$age_str;1872}18731874useconstant{1875 S_IFINVALID =>0030000,1876 S_IFGITLINK =>0160000,1877};18781879# submodule/subproject, a commit object reference1880sub S_ISGITLINK {1881my$mode=shift;18821883return(($mode& S_IFMT) == S_IFGITLINK)1884}18851886# convert file mode in octal to symbolic file mode string1887sub mode_str {1888my$mode=oct shift;18891890if(S_ISGITLINK($mode)) {1891return'm---------';1892}elsif(S_ISDIR($mode& S_IFMT)) {1893return'drwxr-xr-x';1894}elsif(S_ISLNK($mode)) {1895return'lrwxrwxrwx';1896}elsif(S_ISREG($mode)) {1897# git cares only about the executable bit1898if($mode& S_IXUSR) {1899return'-rwxr-xr-x';1900}else{1901return'-rw-r--r--';1902};1903}else{1904return'----------';1905}1906}19071908# convert file mode in octal to file type string1909sub file_type {1910my$mode=shift;19111912if($mode!~m/^[0-7]+$/) {1913return$mode;1914}else{1915$mode=oct$mode;1916}19171918if(S_ISGITLINK($mode)) {1919return"submodule";1920}elsif(S_ISDIR($mode& S_IFMT)) {1921return"directory";1922}elsif(S_ISLNK($mode)) {1923return"symlink";1924}elsif(S_ISREG($mode)) {1925return"file";1926}else{1927return"unknown";1928}1929}19301931# convert file mode in octal to file type description string1932sub file_type_long {1933my$mode=shift;19341935if($mode!~m/^[0-7]+$/) {1936return$mode;1937}else{1938$mode=oct$mode;1939}19401941if(S_ISGITLINK($mode)) {1942return"submodule";1943}elsif(S_ISDIR($mode& S_IFMT)) {1944return"directory";1945}elsif(S_ISLNK($mode)) {1946return"symlink";1947}elsif(S_ISREG($mode)) {1948if($mode& S_IXUSR) {1949return"executable";1950}else{1951return"file";1952};1953}else{1954return"unknown";1955}1956}195719581959## ----------------------------------------------------------------------1960## functions returning short HTML fragments, or transforming HTML fragments1961## which don't belong to other sections19621963# format line of commit message.1964sub format_log_line_html {1965my$line=shift;19661967$line= esc_html($line, -nbsp=>1);1968$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1969$cgi->a({-href => href(action=>"object", hash=>$1),1970-class=>"text"},$1);1971}eg;19721973return$line;1974}19751976# format marker of refs pointing to given object19771978# the destination action is chosen based on object type and current context:1979# - for annotated tags, we choose the tag view unless it's the current view1980# already, in which case we go to shortlog view1981# - for other refs, we keep the current view if we're in history, shortlog or1982# log view, and select shortlog otherwise1983sub format_ref_marker {1984my($refs,$id) =@_;1985my$markers='';19861987if(defined$refs->{$id}) {1988foreachmy$ref(@{$refs->{$id}}) {1989# this code exploits the fact that non-lightweight tags are the1990# only indirect objects, and that they are the only objects for which1991# we want to use tag instead of shortlog as action1992my($type,$name) =qw();1993my$indirect= ($ref=~s/\^\{\}$//);1994# e.g. tags/v2.6.11 or heads/next1995if($ref=~m!^(.*?)s?/(.*)$!) {1996$type=$1;1997$name=$2;1998}else{1999$type="ref";2000$name=$ref;2001}20022003my$class=$type;2004$class.=" indirect"if$indirect;20052006my$dest_action="shortlog";20072008if($indirect) {2009$dest_action="tag"unless$actioneq"tag";2010}elsif($action=~/^(history|(short)?log)$/) {2011$dest_action=$action;2012}20132014my$dest="";2015$dest.="refs/"unless$ref=~ m!^refs/!;2016$dest.=$ref;20172018my$link=$cgi->a({2019-href => href(2020 action=>$dest_action,2021 hash=>$dest2022)},$name);20232024$markers.=" <span class=\"".esc_attr($class)."\"title=\"".esc_attr($ref)."\">".2025$link."</span>";2026}2027}20282029if($markers) {2030return' <span class="refs">'.$markers.'</span>';2031}else{2032return"";2033}2034}20352036# format, perhaps shortened and with markers, title line2037sub format_subject_html {2038my($long,$short,$href,$extra) =@_;2039$extra=''unlessdefined($extra);20402041if(length($short) <length($long)) {2042$long=~s/[[:cntrl:]]/?/g;2043return$cgi->a({-href =>$href, -class=>"list subject",2044-title => to_utf8($long)},2045 esc_html($short)) .$extra;2046}else{2047return$cgi->a({-href =>$href, -class=>"list subject"},2048 esc_html($long)) .$extra;2049}2050}20512052# Rather than recomputing the url for an email multiple times, we cache it2053# after the first hit. This gives a visible benefit in views where the avatar2054# for the same email is used repeatedly (e.g. shortlog).2055# The cache is shared by all avatar engines (currently gravatar only), which2056# are free to use it as preferred. Since only one avatar engine is used for any2057# given page, there's no risk for cache conflicts.2058our%avatar_cache= ();20592060# Compute the picon url for a given email, by using the picon search service over at2061# http://www.cs.indiana.edu/picons/search.html2062sub picon_url {2063my$email=lc shift;2064if(!$avatar_cache{$email}) {2065my($user,$domain) =split('@',$email);2066$avatar_cache{$email} =2067"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".2068"$domain/$user/".2069"users+domains+unknown/up/single";2070}2071return$avatar_cache{$email};2072}20732074# Compute the gravatar url for a given email, if it's not in the cache already.2075# Gravatar stores only the part of the URL before the size, since that's the2076# one computationally more expensive. This also allows reuse of the cache for2077# different sizes (for this particular engine).2078sub gravatar_url {2079my$email=lc shift;2080my$size=shift;2081$avatar_cache{$email} ||=2082"http://www.gravatar.com/avatar/".2083 Digest::MD5::md5_hex($email) ."?s=";2084return$avatar_cache{$email} .$size;2085}20862087# Insert an avatar for the given $email at the given $size if the feature2088# is enabled.2089sub git_get_avatar {2090my($email,%opts) =@_;2091my$pre_white= ($opts{-pad_before} ?" ":"");2092my$post_white= ($opts{-pad_after} ?" ":"");2093$opts{-size} ||='default';2094my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};2095my$url="";2096if($git_avatareq'gravatar') {2097$url= gravatar_url($email,$size);2098}elsif($git_avatareq'picon') {2099$url= picon_url($email);2100}2101# Other providers can be added by extending the if chain, defining $url2102# as needed. If no variant puts something in $url, we assume avatars2103# are completely disabled/unavailable.2104if($url) {2105return$pre_white.2106"<img width=\"$size\"".2107"class=\"avatar\"".2108"src=\"".esc_url($url)."\"".2109"alt=\"\"".2110"/>".$post_white;2111}else{2112return"";2113}2114}21152116sub format_search_author {2117my($author,$searchtype,$displaytext) =@_;2118my$have_search= gitweb_check_feature('search');21192120if($have_search) {2121my$performed="";2122if($searchtypeeq'author') {2123$performed="authored";2124}elsif($searchtypeeq'committer') {2125$performed="committed";2126}21272128return$cgi->a({-href => href(action=>"search", hash=>$hash,2129 searchtext=>$author,2130 searchtype=>$searchtype),class=>"list",2131 title=>"Search for commits$performedby$author"},2132$displaytext);21332134}else{2135return$displaytext;2136}2137}21382139# format the author name of the given commit with the given tag2140# the author name is chopped and escaped according to the other2141# optional parameters (see chop_str).2142sub format_author_html {2143my$tag=shift;2144my$co=shift;2145my$author= chop_and_escape_str($co->{'author_name'},@_);2146return"<$tagclass=\"author\">".2147 format_search_author($co->{'author_name'},"author",2148 git_get_avatar($co->{'author_email'}, -pad_after =>1) .2149$author) .2150"</$tag>";2151}21522153# format git diff header line, i.e. "diff --(git|combined|cc) ..."2154sub format_git_diff_header_line {2155my$line=shift;2156my$diffinfo=shift;2157my($from,$to) =@_;21582159if($diffinfo->{'nparents'}) {2160# combined diff2161$line=~s!^(diff (.*?) )"?.*$!$1!;2162if($to->{'href'}) {2163$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2164 esc_path($to->{'file'}));2165}else{# file was deleted (no href)2166$line.= esc_path($to->{'file'});2167}2168}else{2169# "ordinary" diff2170$line=~s!^(diff (.*?) )"?a/.*$!$1!;2171if($from->{'href'}) {2172$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},2173'a/'. esc_path($from->{'file'}));2174}else{# file was added (no href)2175$line.='a/'. esc_path($from->{'file'});2176}2177$line.=' ';2178if($to->{'href'}) {2179$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2180'b/'. esc_path($to->{'file'}));2181}else{# file was deleted2182$line.='b/'. esc_path($to->{'file'});2183}2184}21852186return"<div class=\"diff header\">$line</div>\n";2187}21882189# format extended diff header line, before patch itself2190sub format_extended_diff_header_line {2191my$line=shift;2192my$diffinfo=shift;2193my($from,$to) =@_;21942195# match <path>2196if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {2197$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},2198 esc_path($from->{'file'}));2199}2200if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {2201$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},2202 esc_path($to->{'file'}));2203}2204# match single <mode>2205if($line=~m/\s(\d{6})$/) {2206$line.='<span class="info"> ('.2207 file_type_long($1) .2208')</span>';2209}2210# match <hash>2211if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {2212# can match only for combined diff2213$line='index ';2214for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2215if($from->{'href'}[$i]) {2216$line.=$cgi->a({-href=>$from->{'href'}[$i],2217-class=>"hash"},2218substr($diffinfo->{'from_id'}[$i],0,7));2219}else{2220$line.='0' x 7;2221}2222# separator2223$line.=','if($i<$diffinfo->{'nparents'} -1);2224}2225$line.='..';2226if($to->{'href'}) {2227$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2228substr($diffinfo->{'to_id'},0,7));2229}else{2230$line.='0' x 7;2231}22322233}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {2234# can match only for ordinary diff2235my($from_link,$to_link);2236if($from->{'href'}) {2237$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},2238substr($diffinfo->{'from_id'},0,7));2239}else{2240$from_link='0' x 7;2241}2242if($to->{'href'}) {2243$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2244substr($diffinfo->{'to_id'},0,7));2245}else{2246$to_link='0' x 7;2247}2248my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});2249$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;2250}22512252return$line."<br/>\n";2253}22542255# format from-file/to-file diff header2256sub format_diff_from_to_header {2257my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2258my$line;2259my$result='';22602261$line=$from_line;2262#assert($line =~ m/^---/) if DEBUG;2263# no extra formatting for "^--- /dev/null"2264if(!$diffinfo->{'nparents'}) {2265# ordinary (single parent) diff2266if($line=~m!^--- "?a/!) {2267if($from->{'href'}) {2268$line='--- a/'.2269$cgi->a({-href=>$from->{'href'}, -class=>"path"},2270 esc_path($from->{'file'}));2271}else{2272$line='--- a/'.2273 esc_path($from->{'file'});2274}2275}2276$result.= qq!<div class="diff from_file">$line</div>\n!;22772278}else{2279# combined diff (merge commit)2280for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2281if($from->{'href'}[$i]) {2282$line='--- '.2283$cgi->a({-href=>href(action=>"blobdiff",2284 hash_parent=>$diffinfo->{'from_id'}[$i],2285 hash_parent_base=>$parents[$i],2286 file_parent=>$from->{'file'}[$i],2287 hash=>$diffinfo->{'to_id'},2288 hash_base=>$hash,2289 file_name=>$to->{'file'}),2290-class=>"path",2291-title=>"diff". ($i+1)},2292$i+1) .2293'/'.2294$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2295 esc_path($from->{'file'}[$i]));2296}else{2297$line='--- /dev/null';2298}2299$result.= qq!<div class="diff from_file">$line</div>\n!;2300}2301}23022303$line=$to_line;2304#assert($line =~ m/^\+\+\+/) if DEBUG;2305# no extra formatting for "^+++ /dev/null"2306if($line=~m!^\+\+\+ "?b/!) {2307if($to->{'href'}) {2308$line='+++ b/'.2309$cgi->a({-href=>$to->{'href'}, -class=>"path"},2310 esc_path($to->{'file'}));2311}else{2312$line='+++ b/'.2313 esc_path($to->{'file'});2314}2315}2316$result.= qq!<div class="diff to_file">$line</div>\n!;23172318return$result;2319}23202321# create note for patch simplified by combined diff2322sub format_diff_cc_simplified {2323my($diffinfo,@parents) =@_;2324my$result='';23252326$result.="<div class=\"diff header\">".2327"diff --cc ";2328if(!is_deleted($diffinfo)) {2329$result.=$cgi->a({-href => href(action=>"blob",2330 hash_base=>$hash,2331 hash=>$diffinfo->{'to_id'},2332 file_name=>$diffinfo->{'to_file'}),2333-class=>"path"},2334 esc_path($diffinfo->{'to_file'}));2335}else{2336$result.= esc_path($diffinfo->{'to_file'});2337}2338$result.="</div>\n".# class="diff header"2339"<div class=\"diff nodifferences\">".2340"Simple merge".2341"</div>\n";# class="diff nodifferences"23422343return$result;2344}23452346sub diff_line_class {2347my($line,$from,$to) =@_;23482349# ordinary diff2350my$num_sign=1;2351# combined diff2352if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2353$num_sign=scalar@{$from->{'href'}};2354}23552356my@diff_line_classifier= (2357{ regexp =>qr/^\@\@{$num_sign} /,class=>"chunk_header"},2358{ regexp =>qr/^\\/,class=>"incomplete"},2359{ regexp =>qr/^ {$num_sign}/,class=>"ctx"},2360# classifier for context must come before classifier add/rem,2361# or we would have to use more complicated regexp, for example2362# qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;2363{ regexp =>qr/^[+ ]{$num_sign}/,class=>"add"},2364{ regexp =>qr/^[- ]{$num_sign}/,class=>"rem"},2365);2366formy$clsfy(@diff_line_classifier) {2367return$clsfy->{'class'}2368if($line=~$clsfy->{'regexp'});2369}23702371# fallback2372return"";2373}23742375# assumes that $from and $to are defined and correctly filled,2376# and that $line holds a line of chunk header for unified diff2377sub format_unidiff_chunk_header {2378my($line,$from,$to) =@_;23792380my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2381$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;23822383$from_lines=0unlessdefined$from_lines;2384$to_lines=0unlessdefined$to_lines;23852386if($from->{'href'}) {2387$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2388-class=>"list"},$from_text);2389}2390if($to->{'href'}) {2391$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2392-class=>"list"},$to_text);2393}2394$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2395"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2396return$line;2397}23982399# assumes that $from and $to are defined and correctly filled,2400# and that $line holds a line of chunk header for combined diff2401sub format_cc_diff_chunk_header {2402my($line,$from,$to) =@_;24032404my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2405my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);24062407@from_text=split(' ',$ranges);2408for(my$i=0;$i<@from_text; ++$i) {2409($from_start[$i],$from_nlines[$i]) =2410(split(',',substr($from_text[$i],1)),0);2411}24122413$to_text=pop@from_text;2414$to_start=pop@from_start;2415$to_nlines=pop@from_nlines;24162417$line="<span class=\"chunk_info\">$prefix";2418for(my$i=0;$i<@from_text; ++$i) {2419if($from->{'href'}[$i]) {2420$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2421-class=>"list"},$from_text[$i]);2422}else{2423$line.=$from_text[$i];2424}2425$line.=" ";2426}2427if($to->{'href'}) {2428$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2429-class=>"list"},$to_text);2430}else{2431$line.=$to_text;2432}2433$line.="$prefix</span>".2434"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2435return$line;2436}24372438# process patch (diff) line (not to be used for diff headers),2439# returning HTML-formatted (but not wrapped) line.2440# If the line is passed as a reference, it is treated as HTML and not2441# esc_html()'ed.2442sub format_diff_line {2443my($line,$diff_class,$from,$to) =@_;24442445if(ref($line)) {2446$line=$$line;2447}else{2448chomp$line;2449$line= untabify($line);24502451if($from&&$to&&$line=~m/^\@{2} /) {2452$line= format_unidiff_chunk_header($line,$from,$to);2453}elsif($from&&$to&&$line=~m/^\@{3}/) {2454$line= format_cc_diff_chunk_header($line,$from,$to);2455}else{2456$line= esc_html($line, -nbsp=>1);2457}2458}24592460my$diff_classes="diff";2461$diff_classes.="$diff_class"if($diff_class);2462$line="<div class=\"$diff_classes\">$line</div>\n";24632464return$line;2465}24662467# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2468# linked. Pass the hash of the tree/commit to snapshot.2469sub format_snapshot_links {2470my($hash) =@_;2471my$num_fmts=@snapshot_fmts;2472if($num_fmts>1) {2473# A parenthesized list of links bearing format names.2474# e.g. "snapshot (_tar.gz_ _zip_)"2475return"snapshot (".join(' ',map2476$cgi->a({2477-href => href(2478 action=>"snapshot",2479 hash=>$hash,2480 snapshot_format=>$_2481)2482},$known_snapshot_formats{$_}{'display'})2483,@snapshot_fmts) .")";2484}elsif($num_fmts==1) {2485# A single "snapshot" link whose tooltip bears the format name.2486# i.e. "_snapshot_"2487my($fmt) =@snapshot_fmts;2488return2489$cgi->a({2490-href => href(2491 action=>"snapshot",2492 hash=>$hash,2493 snapshot_format=>$fmt2494),2495-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2496},"snapshot");2497}else{# $num_fmts == 02498returnundef;2499}2500}25012502## ......................................................................2503## functions returning values to be passed, perhaps after some2504## transformation, to other functions; e.g. returning arguments to href()25052506# returns hash to be passed to href to generate gitweb URL2507# in -title key it returns description of link2508sub get_feed_info {2509my$format=shift||'Atom';2510my%res= (action =>lc($format));25112512# feed links are possible only for project views2513return unless(defined$project);2514# some views should link to OPML, or to generic project feed,2515# or don't have specific feed yet (so they should use generic)2516return if(!$action||$action=~/^(?:tags|heads|forks|tag|search)$/x);25172518my$branch;2519# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2520# from tag links; this also makes possible to detect branch links2521if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2522(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2523$branch=$1;2524}2525# find log type for feed description (title)2526my$type='log';2527if(defined$file_name) {2528$type="history of$file_name";2529$type.="/"if($actioneq'tree');2530$type.=" on '$branch'"if(defined$branch);2531}else{2532$type="log of$branch"if(defined$branch);2533}25342535$res{-title} =$type;2536$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2537$res{'file_name'} =$file_name;25382539return%res;2540}25412542## ----------------------------------------------------------------------2543## git utility subroutines, invoking git commands25442545# returns path to the core git executable and the --git-dir parameter as list2546sub git_cmd {2547$number_of_git_cmds++;2548return$GIT,'--git-dir='.$git_dir;2549}25502551# quote the given arguments for passing them to the shell2552# quote_command("command", "arg 1", "arg with ' and ! characters")2553# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2554# Try to avoid using this function wherever possible.2555sub quote_command {2556returnjoin(' ',2557map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2558}25592560# get HEAD ref of given project as hash2561sub git_get_head_hash {2562return git_get_full_hash(shift,'HEAD');2563}25642565sub git_get_full_hash {2566return git_get_hash(@_);2567}25682569sub git_get_short_hash {2570return git_get_hash(@_,'--short=7');2571}25722573sub git_get_hash {2574my($project,$hash,@options) =@_;2575my$o_git_dir=$git_dir;2576my$retval=undef;2577$git_dir="$projectroot/$project";2578if(open my$fd,'-|', git_cmd(),'rev-parse',2579'--verify','-q',@options,$hash) {2580$retval= <$fd>;2581chomp$retvalifdefined$retval;2582close$fd;2583}2584if(defined$o_git_dir) {2585$git_dir=$o_git_dir;2586}2587return$retval;2588}25892590# get type of given object2591sub git_get_type {2592my$hash=shift;25932594open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2595my$type= <$fd>;2596close$fdorreturn;2597chomp$type;2598return$type;2599}26002601# repository configuration2602our$config_file='';2603our%config;26042605# store multiple values for single key as anonymous array reference2606# single values stored directly in the hash, not as [ <value> ]2607sub hash_set_multi {2608my($hash,$key,$value) =@_;26092610if(!exists$hash->{$key}) {2611$hash->{$key} =$value;2612}elsif(!ref$hash->{$key}) {2613$hash->{$key} = [$hash->{$key},$value];2614}else{2615push@{$hash->{$key}},$value;2616}2617}26182619# return hash of git project configuration2620# optionally limited to some section, e.g. 'gitweb'2621sub git_parse_project_config {2622my$section_regexp=shift;2623my%config;26242625local$/="\0";26262627open my$fh,"-|", git_cmd(),"config",'-z','-l',2628orreturn;26292630while(my$keyval= <$fh>) {2631chomp$keyval;2632my($key,$value) =split(/\n/,$keyval,2);26332634 hash_set_multi(\%config,$key,$value)2635if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2636}2637close$fh;26382639return%config;2640}26412642# convert config value to boolean: 'true' or 'false'2643# no value, number > 0, 'true' and 'yes' values are true2644# rest of values are treated as false (never as error)2645sub config_to_bool {2646my$val=shift;26472648return1if!defined$val;# section.key26492650# strip leading and trailing whitespace2651$val=~s/^\s+//;2652$val=~s/\s+$//;26532654return(($val=~/^\d+$/&&$val) ||# section.key = 12655($val=~/^(?:true|yes)$/i));# section.key = true2656}26572658# convert config value to simple decimal number2659# an optional value suffix of 'k', 'm', or 'g' will cause the value2660# to be multiplied by 1024, 1048576, or 10737418242661sub config_to_int {2662my$val=shift;26632664# strip leading and trailing whitespace2665$val=~s/^\s+//;2666$val=~s/\s+$//;26672668if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2669$unit=lc($unit);2670# unknown unit is treated as 12671return$num* ($uniteq'g'?1073741824:2672$uniteq'm'?1048576:2673$uniteq'k'?1024:1);2674}2675return$val;2676}26772678# convert config value to array reference, if needed2679sub config_to_multi {2680my$val=shift;26812682returnref($val) ?$val: (defined($val) ? [$val] : []);2683}26842685sub git_get_project_config {2686my($key,$type) =@_;26872688return unlessdefined$git_dir;26892690# key sanity check2691return unless($key);2692# only subsection, if exists, is case sensitive,2693# and not lowercased by 'git config -z -l'2694if(my($hi,$mi,$lo) = ($key=~/^([^.]*)\.(.*)\.([^.]*)$/)) {2695$key=join(".",lc($hi),$mi,lc($lo));2696}else{2697$key=lc($key);2698}2699$key=~s/^gitweb\.//;2700return if($key=~m/\W/);27012702# type sanity check2703if(defined$type) {2704$type=~s/^--//;2705$type=undef2706unless($typeeq'bool'||$typeeq'int');2707}27082709# get config2710if(!defined$config_file||2711$config_filene"$git_dir/config") {2712%config= git_parse_project_config('gitweb');2713$config_file="$git_dir/config";2714}27152716# check if config variable (key) exists2717return unlessexists$config{"gitweb.$key"};27182719# ensure given type2720if(!defined$type) {2721return$config{"gitweb.$key"};2722}elsif($typeeq'bool') {2723# backward compatibility: 'git config --bool' returns true/false2724return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2725}elsif($typeeq'int') {2726return config_to_int($config{"gitweb.$key"});2727}2728return$config{"gitweb.$key"};2729}27302731# get hash of given path at given ref2732sub git_get_hash_by_path {2733my$base=shift;2734my$path=shift||returnundef;2735my$type=shift;27362737$path=~ s,/+$,,;27382739open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2740or die_error(500,"Open git-ls-tree failed");2741my$line= <$fd>;2742close$fdorreturnundef;27432744if(!defined$line) {2745# there is no tree or hash given by $path at $base2746returnundef;2747}27482749#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2750$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2751if(defined$type&&$typene$2) {2752# type doesn't match2753returnundef;2754}2755return$3;2756}27572758# get path of entry with given hash at given tree-ish (ref)2759# used to get 'from' filename for combined diff (merge commit) for renames2760sub git_get_path_by_hash {2761my$base=shift||return;2762my$hash=shift||return;27632764local$/="\0";27652766open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2767orreturnundef;2768while(my$line= <$fd>) {2769chomp$line;27702771#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2772#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2773if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2774close$fd;2775return$1;2776}2777}2778close$fd;2779returnundef;2780}27812782## ......................................................................2783## git utility functions, directly accessing git repository27842785# get the value of config variable either from file named as the variable2786# itself in the repository ($GIT_DIR/$name file), or from gitweb.$name2787# configuration variable in the repository config file.2788sub git_get_file_or_project_config {2789my($path,$name) =@_;27902791$git_dir="$projectroot/$path";2792open my$fd,'<',"$git_dir/$name"2793orreturn git_get_project_config($name);2794my$conf= <$fd>;2795close$fd;2796if(defined$conf) {2797chomp$conf;2798}2799return$conf;2800}28012802sub git_get_project_description {2803my$path=shift;2804return git_get_file_or_project_config($path,'description');2805}28062807sub git_get_project_category {2808my$path=shift;2809return git_get_file_or_project_config($path,'category');2810}281128122813# supported formats:2814# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2815# - if its contents is a number, use it as tag weight,2816# - otherwise add a tag with weight 12817# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2818# the same value multiple times increases tag weight2819# * `gitweb.ctag' multi-valued repo config variable2820sub git_get_project_ctags {2821my$project=shift;2822my$ctags= {};28232824$git_dir="$projectroot/$project";2825if(opendir my$dh,"$git_dir/ctags") {2826my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2827foreachmy$tagfile(@files) {2828open my$ct,'<',$tagfile2829ornext;2830my$val= <$ct>;2831chomp$valif$val;2832close$ct;28332834(my$ctag=$tagfile) =~ s#.*/##;2835if($val=~/^\d+$/) {2836$ctags->{$ctag} =$val;2837}else{2838$ctags->{$ctag} =1;2839}2840}2841closedir$dh;28422843}elsif(open my$fh,'<',"$git_dir/ctags") {2844while(my$line= <$fh>) {2845chomp$line;2846$ctags->{$line}++if$line;2847}2848close$fh;28492850}else{2851my$taglist= config_to_multi(git_get_project_config('ctag'));2852foreachmy$tag(@$taglist) {2853$ctags->{$tag}++;2854}2855}28562857return$ctags;2858}28592860# return hash, where keys are content tags ('ctags'),2861# and values are sum of weights of given tag in every project2862sub git_gather_all_ctags {2863my$projects=shift;2864my$ctags= {};28652866foreachmy$p(@$projects) {2867foreachmy$ct(keys%{$p->{'ctags'}}) {2868$ctags->{$ct} +=$p->{'ctags'}->{$ct};2869}2870}28712872return$ctags;2873}28742875sub git_populate_project_tagcloud {2876my$ctags=shift;28772878# First, merge different-cased tags; tags vote on casing2879my%ctags_lc;2880foreach(keys%$ctags) {2881$ctags_lc{lc$_}->{count} +=$ctags->{$_};2882if(not$ctags_lc{lc$_}->{topcount}2883or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2884$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2885$ctags_lc{lc$_}->{topname} =$_;2886}2887}28882889my$cloud;2890my$matched=$input_params{'ctag'};2891if(eval{require HTML::TagCloud;1; }) {2892$cloud= HTML::TagCloud->new;2893foreachmy$ctag(sort keys%ctags_lc) {2894# Pad the title with spaces so that the cloud looks2895# less crammed.2896my$title= esc_html($ctags_lc{$ctag}->{topname});2897$title=~s/ / /g;2898$title=~s/^/ /g;2899$title=~s/$/ /g;2900if(defined$matched&&$matchedeq$ctag) {2901$title=qq(<span class="match">$title</span>);2902}2903$cloud->add($title, href(project=>undef, ctag=>$ctag),2904$ctags_lc{$ctag}->{count});2905}2906}else{2907$cloud= {};2908foreachmy$ctag(keys%ctags_lc) {2909my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2910if(defined$matched&&$matchedeq$ctag) {2911$title=qq(<span class="match">$title</span>);2912}2913$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};2914$cloud->{$ctag}{ctag} =2915$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);2916}2917}2918return$cloud;2919}29202921sub git_show_project_tagcloud {2922my($cloud,$count) =@_;2923if(ref$cloudeq'HTML::TagCloud') {2924return$cloud->html_and_css($count);2925}else{2926my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;2927return2928'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.2929join(', ',map{2930$cloud->{$_}->{'ctag'}2931}splice(@tags,0,$count)) .2932'</div>';2933}2934}29352936sub git_get_project_url_list {2937my$path=shift;29382939$git_dir="$projectroot/$path";2940open my$fd,'<',"$git_dir/cloneurl"2941orreturnwantarray?2942@{ config_to_multi(git_get_project_config('url')) } :2943 config_to_multi(git_get_project_config('url'));2944my@git_project_url_list=map{chomp;$_} <$fd>;2945close$fd;29462947returnwantarray?@git_project_url_list: \@git_project_url_list;2948}29492950sub git_get_projects_list {2951my$filter=shift||'';2952my$paranoid=shift;2953my@list;29542955if(-d $projects_list) {2956# search in directory2957my$dir=$projects_list;2958# remove the trailing "/"2959$dir=~s!/+$!!;2960my$pfxlen=length("$dir");2961my$pfxdepth= ($dir=~tr!/!!);2962# when filtering, search only given subdirectory2963if($filter&& !$paranoid) {2964$dir.="/$filter";2965$dir=~s!/+$!!;2966}29672968 File::Find::find({2969 follow_fast =>1,# follow symbolic links2970 follow_skip =>2,# ignore duplicates2971 dangling_symlinks =>0,# ignore dangling symlinks, silently2972 wanted =>sub{2973# global variables2974our$project_maxdepth;2975our$projectroot;2976# skip project-list toplevel, if we get it.2977return if(m!^[/.]$!);2978# only directories can be git repositories2979return unless(-d $_);2980# don't traverse too deep (Find is super slow on os x)2981# $project_maxdepth excludes depth of $projectroot2982if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2983$File::Find::prune =1;2984return;2985}29862987my$path=substr($File::Find::name,$pfxlen+1);2988# paranoidly only filter here2989if($paranoid&&$filter&&$path!~m!^\Q$filter\E/!) {2990next;2991}2992# we check related file in $projectroot2993if(check_export_ok("$projectroot/$path")) {2994push@list, { path =>$path};2995$File::Find::prune =1;2996}2997},2998},"$dir");29993000}elsif(-f $projects_list) {3001# read from file(url-encoded):3002# 'git%2Fgit.git Linus+Torvalds'3003# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'3004# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'3005open my$fd,'<',$projects_listorreturn;3006 PROJECT:3007while(my$line= <$fd>) {3008chomp$line;3009my($path,$owner) =split' ',$line;3010$path= unescape($path);3011$owner= unescape($owner);3012if(!defined$path) {3013next;3014}3015# if $filter is rpovided, check if $path begins with $filter3016if($filter&&$path!~m!^\Q$filter\E/!) {3017next;3018}3019if(check_export_ok("$projectroot/$path")) {3020my$pr= {3021 path =>$path3022};3023if($owner) {3024$pr->{'owner'} = to_utf8($owner);3025}3026push@list,$pr;3027}3028}3029close$fd;3030}3031return@list;3032}30333034# written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)3035# as side effects it sets 'forks' field to list of forks for forked projects3036sub filter_forks_from_projects_list {3037my$projects=shift;30383039my%trie;# prefix tree of directories (path components)3040# generate trie out of those directories that might contain forks3041foreachmy$pr(@$projects) {3042my$path=$pr->{'path'};3043$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory3044next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'3045next unless($path);# skip '.git' repository: tests, git-instaweb3046next unless(-d "$projectroot/$path");# containing directory exists3047$pr->{'forks'} = [];# there can be 0 or more forks of project30483049# add to trie3050my@dirs=split('/',$path);3051# walk the trie, until either runs out of components or out of trie3052my$ref= \%trie;3053while(scalar@dirs&&3054exists($ref->{$dirs[0]})) {3055$ref=$ref->{shift@dirs};3056}3057# create rest of trie structure from rest of components3058foreachmy$dir(@dirs) {3059$ref=$ref->{$dir} = {};3060}3061# create end marker, store $pr as a data3062$ref->{''} =$prif(!exists$ref->{''});3063}30643065# filter out forks, by finding shortest prefix match for paths3066my@filtered;3067 PROJECT:3068foreachmy$pr(@$projects) {3069# trie lookup3070my$ref= \%trie;3071 DIR:3072foreachmy$dir(split('/',$pr->{'path'})) {3073if(exists$ref->{''}) {3074# found [shortest] prefix, is a fork - skip it3075push@{$ref->{''}{'forks'}},$pr;3076next PROJECT;3077}3078if(!exists$ref->{$dir}) {3079# not in trie, cannot have prefix, not a fork3080push@filtered,$pr;3081next PROJECT;3082}3083# If the dir is there, we just walk one step down the trie.3084$ref=$ref->{$dir};3085}3086# we ran out of trie3087# (shouldn't happen: it's either no match, or end marker)3088push@filtered,$pr;3089}30903091return@filtered;3092}30933094# note: fill_project_list_info must be run first,3095# for 'descr_long' and 'ctags' to be filled3096sub search_projects_list {3097my($projlist,%opts) =@_;3098my$tagfilter=$opts{'tagfilter'};3099my$search_re=$opts{'search_regexp'};31003101return@$projlist3102unless($tagfilter||$search_re);31033104# searching projects require filling to be run before it;3105 fill_project_list_info($projlist,3106$tagfilter?'ctags': (),3107$search_re? ('path','descr') : ());3108my@projects;3109 PROJECT:3110foreachmy$pr(@$projlist) {31113112if($tagfilter) {3113next unlessref($pr->{'ctags'})eq'HASH';3114next unless3115grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};3116}31173118if($search_re) {3119next unless3120$pr->{'path'} =~/$search_re/||3121$pr->{'descr_long'} =~/$search_re/;3122}31233124push@projects,$pr;3125}31263127return@projects;3128}31293130our$gitweb_project_owner=undef;3131sub git_get_project_list_from_file {31323133return if(defined$gitweb_project_owner);31343135$gitweb_project_owner= {};3136# read from file (url-encoded):3137# 'git%2Fgit.git Linus+Torvalds'3138# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'3139# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'3140if(-f $projects_list) {3141open(my$fd,'<',$projects_list);3142while(my$line= <$fd>) {3143chomp$line;3144my($pr,$ow) =split' ',$line;3145$pr= unescape($pr);3146$ow= unescape($ow);3147$gitweb_project_owner->{$pr} = to_utf8($ow);3148}3149close$fd;3150}3151}31523153sub git_get_project_owner {3154my$project=shift;3155my$owner;31563157returnundefunless$project;3158$git_dir="$projectroot/$project";31593160if(!defined$gitweb_project_owner) {3161 git_get_project_list_from_file();3162}31633164if(exists$gitweb_project_owner->{$project}) {3165$owner=$gitweb_project_owner->{$project};3166}3167if(!defined$owner){3168$owner= git_get_project_config('owner');3169}3170if(!defined$owner) {3171$owner= get_file_owner("$git_dir");3172}31733174return$owner;3175}31763177sub git_get_last_activity {3178my($path) =@_;3179my$fd;31803181$git_dir="$projectroot/$path";3182open($fd,"-|", git_cmd(),'for-each-ref',3183'--format=%(committer)',3184'--sort=-committerdate',3185'--count=1',3186'refs/heads')orreturn;3187my$most_recent= <$fd>;3188close$fdorreturn;3189if(defined$most_recent&&3190$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {3191my$timestamp=$1;3192my$age=time-$timestamp;3193return($age, age_string($age));3194}3195return(undef,undef);3196}31973198# Implementation note: when a single remote is wanted, we cannot use 'git3199# remote show -n' because that command always work (assuming it's a remote URL3200# if it's not defined), and we cannot use 'git remote show' because that would3201# try to make a network roundtrip. So the only way to find if that particular3202# remote is defined is to walk the list provided by 'git remote -v' and stop if3203# and when we find what we want.3204sub git_get_remotes_list {3205my$wanted=shift;3206my%remotes= ();32073208open my$fd,'-|', git_cmd(),'remote','-v';3209return unless$fd;3210while(my$remote= <$fd>) {3211chomp$remote;3212$remote=~s!\t(.*?)\s+\((\w+)\)$!!;3213next if$wantedand not$remoteeq$wanted;3214my($url,$key) = ($1,$2);32153216$remotes{$remote} ||= {'heads'=> () };3217$remotes{$remote}{$key} =$url;3218}3219close$fdorreturn;3220returnwantarray?%remotes: \%remotes;3221}32223223# Takes a hash of remotes as first parameter and fills it by adding the3224# available remote heads for each of the indicated remotes.3225sub fill_remote_heads {3226my$remotes=shift;3227my@heads=map{"remotes/$_"}keys%$remotes;3228my@remoteheads= git_get_heads_list(undef,@heads);3229foreachmy$remote(keys%$remotes) {3230$remotes->{$remote}{'heads'} = [grep{3231$_->{'name'} =~s!^$remote/!!3232}@remoteheads];3233}3234}32353236sub git_get_references {3237my$type=shift||"";3238my%refs;3239# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113240# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3241open my$fd,"-|", git_cmd(),"show-ref","--dereference",3242($type? ("--","refs/$type") : ())# use -- <pattern> if $type3243orreturn;32443245while(my$line= <$fd>) {3246chomp$line;3247if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3248if(defined$refs{$1}) {3249push@{$refs{$1}},$2;3250}else{3251$refs{$1} = [$2];3252}3253}3254}3255close$fdorreturn;3256return \%refs;3257}32583259sub git_get_rev_name_tags {3260my$hash=shift||returnundef;32613262open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3263orreturn;3264my$name_rev= <$fd>;3265close$fd;32663267if($name_rev=~ m|^$hash tags/(.*)$|) {3268return$1;3269}else{3270# catches also '$hash undefined' output3271returnundef;3272}3273}32743275## ----------------------------------------------------------------------3276## parse to hash functions32773278sub parse_date {3279my$epoch=shift;3280my$tz=shift||"-0000";32813282my%date;3283my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3284my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3285my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3286$date{'hour'} =$hour;3287$date{'minute'} =$min;3288$date{'mday'} =$mday;3289$date{'day'} =$days[$wday];3290$date{'month'} =$months[$mon];3291$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3292$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3293$date{'mday-time'} =sprintf"%d%s%02d:%02d",3294$mday,$months[$mon],$hour,$min;3295$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",32961900+$year,1+$mon,$mday,$hour,$min,$sec;32973298my($tz_sign,$tz_hour,$tz_min) =3299($tz=~m/^([-+])(\d\d)(\d\d)$/);3300$tz_sign= ($tz_signeq'-'? -1: +1);3301my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3302($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3303$date{'hour_local'} =$hour;3304$date{'minute_local'} =$min;3305$date{'tz_local'} =$tz;3306$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",33071900+$year,$mon+1,$mday,3308$hour,$min,$sec,$tz);3309return%date;3310}33113312sub parse_tag {3313my$tag_id=shift;3314my%tag;3315my@comment;33163317open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3318$tag{'id'} =$tag_id;3319while(my$line= <$fd>) {3320chomp$line;3321if($line=~m/^object ([0-9a-fA-F]{40})$/) {3322$tag{'object'} =$1;3323}elsif($line=~m/^type (.+)$/) {3324$tag{'type'} =$1;3325}elsif($line=~m/^tag (.+)$/) {3326$tag{'name'} =$1;3327}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3328$tag{'author'} =$1;3329$tag{'author_epoch'} =$2;3330$tag{'author_tz'} =$3;3331if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3332$tag{'author_name'} =$1;3333$tag{'author_email'} =$2;3334}else{3335$tag{'author_name'} =$tag{'author'};3336}3337}elsif($line=~m/--BEGIN/) {3338push@comment,$line;3339last;3340}elsif($lineeq"") {3341last;3342}3343}3344push@comment, <$fd>;3345$tag{'comment'} = \@comment;3346close$fdorreturn;3347if(!defined$tag{'name'}) {3348return3349};3350return%tag3351}33523353sub parse_commit_text {3354my($commit_text,$withparents) =@_;3355my@commit_lines=split'\n',$commit_text;3356my%co;33573358pop@commit_lines;# Remove '\0'33593360if(!@commit_lines) {3361return;3362}33633364my$header=shift@commit_lines;3365if($header!~m/^[0-9a-fA-F]{40}/) {3366return;3367}3368($co{'id'},my@parents) =split' ',$header;3369while(my$line=shift@commit_lines) {3370last if$lineeq"\n";3371if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3372$co{'tree'} =$1;3373}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3374push@parents,$1;3375}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3376$co{'author'} = to_utf8($1);3377$co{'author_epoch'} =$2;3378$co{'author_tz'} =$3;3379if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3380$co{'author_name'} =$1;3381$co{'author_email'} =$2;3382}else{3383$co{'author_name'} =$co{'author'};3384}3385}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3386$co{'committer'} = to_utf8($1);3387$co{'committer_epoch'} =$2;3388$co{'committer_tz'} =$3;3389if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3390$co{'committer_name'} =$1;3391$co{'committer_email'} =$2;3392}else{3393$co{'committer_name'} =$co{'committer'};3394}3395}3396}3397if(!defined$co{'tree'}) {3398return;3399};3400$co{'parents'} = \@parents;3401$co{'parent'} =$parents[0];34023403foreachmy$title(@commit_lines) {3404$title=~s/^ //;3405if($titlene"") {3406$co{'title'} = chop_str($title,80,5);3407# remove leading stuff of merges to make the interesting part visible3408if(length($title) >50) {3409$title=~s/^Automatic //;3410$title=~s/^merge (of|with) /Merge ... /i;3411if(length($title) >50) {3412$title=~s/(http|rsync):\/\///;3413}3414if(length($title) >50) {3415$title=~s/(master|www|rsync)\.//;3416}3417if(length($title) >50) {3418$title=~s/kernel.org:?//;3419}3420if(length($title) >50) {3421$title=~s/\/pub\/scm//;3422}3423}3424$co{'title_short'} = chop_str($title,50,5);3425last;3426}3427}3428if(!defined$co{'title'} ||$co{'title'}eq"") {3429$co{'title'} =$co{'title_short'} ='(no commit message)';3430}3431# remove added spaces3432foreachmy$line(@commit_lines) {3433$line=~s/^ //;3434}3435$co{'comment'} = \@commit_lines;34363437my$age=time-$co{'committer_epoch'};3438$co{'age'} =$age;3439$co{'age_string'} = age_string($age);3440my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3441if($age>60*60*24*7*2) {3442$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3443$co{'age_string_age'} =$co{'age_string'};3444}else{3445$co{'age_string_date'} =$co{'age_string'};3446$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3447}3448return%co;3449}34503451sub parse_commit {3452my($commit_id) =@_;3453my%co;34543455local$/="\0";34563457open my$fd,"-|", git_cmd(),"rev-list",3458"--parents",3459"--header",3460"--max-count=1",3461$commit_id,3462"--",3463or die_error(500,"Open git-rev-list failed");3464%co= parse_commit_text(<$fd>,1);3465close$fd;34663467return%co;3468}34693470sub parse_commits {3471my($commit_id,$maxcount,$skip,$filename,@args) =@_;3472my@cos;34733474$maxcount||=1;3475$skip||=0;34763477local$/="\0";34783479open my$fd,"-|", git_cmd(),"rev-list",3480"--header",3481@args,3482("--max-count=".$maxcount),3483("--skip=".$skip),3484@extra_options,3485$commit_id,3486"--",3487($filename? ($filename) : ())3488or die_error(500,"Open git-rev-list failed");3489while(my$line= <$fd>) {3490my%co= parse_commit_text($line);3491push@cos, \%co;3492}3493close$fd;34943495returnwantarray?@cos: \@cos;3496}34973498# parse line of git-diff-tree "raw" output3499sub parse_difftree_raw_line {3500my$line=shift;3501my%res;35023503# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3504# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3505if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3506$res{'from_mode'} =$1;3507$res{'to_mode'} =$2;3508$res{'from_id'} =$3;3509$res{'to_id'} =$4;3510$res{'status'} =$5;3511$res{'similarity'} =$6;3512if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3513($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3514}else{3515$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3516}3517}3518# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3519# combined diff (for merge commit)3520elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3521$res{'nparents'} =length($1);3522$res{'from_mode'} = [split(' ',$2) ];3523$res{'to_mode'} =pop@{$res{'from_mode'}};3524$res{'from_id'} = [split(' ',$3) ];3525$res{'to_id'} =pop@{$res{'from_id'}};3526$res{'status'} = [split('',$4) ];3527$res{'to_file'} = unquote($5);3528}3529# 'c512b523472485aef4fff9e57b229d9d243c967f'3530elsif($line=~m/^([0-9a-fA-F]{40})$/) {3531$res{'commit'} =$1;3532}35333534returnwantarray?%res: \%res;3535}35363537# wrapper: return parsed line of git-diff-tree "raw" output3538# (the argument might be raw line, or parsed info)3539sub parsed_difftree_line {3540my$line_or_ref=shift;35413542if(ref($line_or_ref)eq"HASH") {3543# pre-parsed (or generated by hand)3544return$line_or_ref;3545}else{3546return parse_difftree_raw_line($line_or_ref);3547}3548}35493550# parse line of git-ls-tree output3551sub parse_ls_tree_line {3552my$line=shift;3553my%opts=@_;3554my%res;35553556if($opts{'-l'}) {3557#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3558$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;35593560$res{'mode'} =$1;3561$res{'type'} =$2;3562$res{'hash'} =$3;3563$res{'size'} =$4;3564if($opts{'-z'}) {3565$res{'name'} =$5;3566}else{3567$res{'name'} = unquote($5);3568}3569}else{3570#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3571$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;35723573$res{'mode'} =$1;3574$res{'type'} =$2;3575$res{'hash'} =$3;3576if($opts{'-z'}) {3577$res{'name'} =$4;3578}else{3579$res{'name'} = unquote($4);3580}3581}35823583returnwantarray?%res: \%res;3584}35853586# generates _two_ hashes, references to which are passed as 2 and 3 argument3587sub parse_from_to_diffinfo {3588my($diffinfo,$from,$to,@parents) =@_;35893590if($diffinfo->{'nparents'}) {3591# combined diff3592$from->{'file'} = [];3593$from->{'href'} = [];3594 fill_from_file_info($diffinfo,@parents)3595unlessexists$diffinfo->{'from_file'};3596for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3597$from->{'file'}[$i] =3598defined$diffinfo->{'from_file'}[$i] ?3599$diffinfo->{'from_file'}[$i] :3600$diffinfo->{'to_file'};3601if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3602$from->{'href'}[$i] = href(action=>"blob",3603 hash_base=>$parents[$i],3604 hash=>$diffinfo->{'from_id'}[$i],3605 file_name=>$from->{'file'}[$i]);3606}else{3607$from->{'href'}[$i] =undef;3608}3609}3610}else{3611# ordinary (not combined) diff3612$from->{'file'} =$diffinfo->{'from_file'};3613if($diffinfo->{'status'}ne"A") {# not new (added) file3614$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3615 hash=>$diffinfo->{'from_id'},3616 file_name=>$from->{'file'});3617}else{3618delete$from->{'href'};3619}3620}36213622$to->{'file'} =$diffinfo->{'to_file'};3623if(!is_deleted($diffinfo)) {# file exists in result3624$to->{'href'} = href(action=>"blob", hash_base=>$hash,3625 hash=>$diffinfo->{'to_id'},3626 file_name=>$to->{'file'});3627}else{3628delete$to->{'href'};3629}3630}36313632## ......................................................................3633## parse to array of hashes functions36343635sub git_get_heads_list {3636my($limit,@classes) =@_;3637@classes= ('heads')unless@classes;3638my@patterns=map{"refs/$_"}@classes;3639my@headslist;36403641open my$fd,'-|', git_cmd(),'for-each-ref',3642($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3643'--format=%(objectname) %(refname) %(subject)%00%(committer)',3644@patterns3645orreturn;3646while(my$line= <$fd>) {3647my%ref_item;36483649chomp$line;3650my($refinfo,$committerinfo) =split(/\0/,$line);3651my($hash,$name,$title) =split(' ',$refinfo,3);3652my($committer,$epoch,$tz) =3653($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3654$ref_item{'fullname'} =$name;3655$name=~s!^refs/(?:head|remote)s/!!;36563657$ref_item{'name'} =$name;3658$ref_item{'id'} =$hash;3659$ref_item{'title'} =$title||'(no commit message)';3660$ref_item{'epoch'} =$epoch;3661if($epoch) {3662$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3663}else{3664$ref_item{'age'} ="unknown";3665}36663667push@headslist, \%ref_item;3668}3669close$fd;36703671returnwantarray?@headslist: \@headslist;3672}36733674sub git_get_tags_list {3675my$limit=shift;3676my@tagslist;36773678open my$fd,'-|', git_cmd(),'for-each-ref',3679($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3680'--format=%(objectname) %(objecttype) %(refname) '.3681'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3682'refs/tags'3683orreturn;3684while(my$line= <$fd>) {3685my%ref_item;36863687chomp$line;3688my($refinfo,$creatorinfo) =split(/\0/,$line);3689my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3690my($creator,$epoch,$tz) =3691($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3692$ref_item{'fullname'} =$name;3693$name=~s!^refs/tags/!!;36943695$ref_item{'type'} =$type;3696$ref_item{'id'} =$id;3697$ref_item{'name'} =$name;3698if($typeeq"tag") {3699$ref_item{'subject'} =$title;3700$ref_item{'reftype'} =$reftype;3701$ref_item{'refid'} =$refid;3702}else{3703$ref_item{'reftype'} =$type;3704$ref_item{'refid'} =$id;3705}37063707if($typeeq"tag"||$typeeq"commit") {3708$ref_item{'epoch'} =$epoch;3709if($epoch) {3710$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3711}else{3712$ref_item{'age'} ="unknown";3713}3714}37153716push@tagslist, \%ref_item;3717}3718close$fd;37193720returnwantarray?@tagslist: \@tagslist;3721}37223723## ----------------------------------------------------------------------3724## filesystem-related functions37253726sub get_file_owner {3727my$path=shift;37283729my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3730my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3731if(!defined$gcos) {3732returnundef;3733}3734my$owner=$gcos;3735$owner=~s/[,;].*$//;3736return to_utf8($owner);3737}37383739# assume that file exists3740sub insert_file {3741my$filename=shift;37423743open my$fd,'<',$filename;3744print map{ to_utf8($_) } <$fd>;3745close$fd;3746}37473748## ......................................................................3749## mimetype related functions37503751sub mimetype_guess_file {3752my$filename=shift;3753my$mimemap=shift;3754-r $mimemaporreturnundef;37553756my%mimemap;3757open(my$mh,'<',$mimemap)orreturnundef;3758while(<$mh>) {3759next ifm/^#/;# skip comments3760my($mimetype,@exts) =split(/\s+/);3761foreachmy$ext(@exts) {3762$mimemap{$ext} =$mimetype;3763}3764}3765close($mh);37663767$filename=~/\.([^.]*)$/;3768return$mimemap{$1};3769}37703771sub mimetype_guess {3772my$filename=shift;3773my$mime;3774$filename=~/\./orreturnundef;37753776if($mimetypes_file) {3777my$file=$mimetypes_file;3778if($file!~m!^/!) {# if it is relative path3779# it is relative to project3780$file="$projectroot/$project/$file";3781}3782$mime= mimetype_guess_file($filename,$file);3783}3784$mime||= mimetype_guess_file($filename,'/etc/mime.types');3785return$mime;3786}37873788sub blob_mimetype {3789my$fd=shift;3790my$filename=shift;37913792if($filename) {3793my$mime= mimetype_guess($filename);3794$mimeandreturn$mime;3795}37963797# just in case3798return$default_blob_plain_mimetypeunless$fd;37993800if(-T $fd) {3801return'text/plain';3802}elsif(!$filename) {3803return'application/octet-stream';3804}elsif($filename=~m/\.png$/i) {3805return'image/png';3806}elsif($filename=~m/\.gif$/i) {3807return'image/gif';3808}elsif($filename=~m/\.jpe?g$/i) {3809return'image/jpeg';3810}else{3811return'application/octet-stream';3812}3813}38143815sub blob_contenttype {3816my($fd,$file_name,$type) =@_;38173818$type||= blob_mimetype($fd,$file_name);3819if($typeeq'text/plain'&&defined$default_text_plain_charset) {3820$type.="; charset=$default_text_plain_charset";3821}38223823return$type;3824}38253826# guess file syntax for syntax highlighting; return undef if no highlighting3827# the name of syntax can (in the future) depend on syntax highlighter used3828sub guess_file_syntax {3829my($highlight,$mimetype,$file_name) =@_;3830returnundefunless($highlight&&defined$file_name);3831my$basename= basename($file_name,'.in');3832return$highlight_basename{$basename}3833ifexists$highlight_basename{$basename};38343835$basename=~/\.([^.]*)$/;3836my$ext=$1orreturnundef;3837return$highlight_ext{$ext}3838ifexists$highlight_ext{$ext};38393840returnundef;3841}38423843# run highlighter and return FD of its output,3844# or return original FD if no highlighting3845sub run_highlighter {3846my($fd,$highlight,$syntax) =@_;3847return$fdunless($highlight&&defined$syntax);38483849close$fd;3850open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3851 quote_command($highlight_bin).3852" --replace-tabs=8 --fragment --syntax$syntax|"3853or die_error(500,"Couldn't open file or run syntax highlighter");3854return$fd;3855}38563857## ======================================================================3858## functions printing HTML: header, footer, error page38593860sub get_page_title {3861my$title= to_utf8($site_name);38623863unless(defined$project) {3864if(defined$project_filter) {3865$title.=" - projects in '". esc_path($project_filter) ."'";3866}3867return$title;3868}3869$title.=" - ". to_utf8($project);38703871return$titleunless(defined$action);3872$title.="/$action";# $action is US-ASCII (7bit ASCII)38733874return$titleunless(defined$file_name);3875$title.=" - ". esc_path($file_name);3876if($actioneq"tree"&&$file_name!~ m|/$|) {3877$title.="/";3878}38793880return$title;3881}38823883sub get_content_type_html {3884# require explicit support from the UA if we are to send the page as3885# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3886# we have to do this because MSIE sometimes globs '*/*', pretending to3887# support xhtml+xml but choking when it gets what it asked for.3888if(defined$cgi->http('HTTP_ACCEPT') &&3889$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3890$cgi->Accept('application/xhtml+xml') !=0) {3891return'application/xhtml+xml';3892}else{3893return'text/html';3894}3895}38963897sub print_feed_meta {3898if(defined$project) {3899my%href_params= get_feed_info();3900if(!exists$href_params{'-title'}) {3901$href_params{'-title'} ='log';3902}39033904foreachmy$format(qw(RSS Atom)) {3905my$type=lc($format);3906my%link_attr= (3907'-rel'=>'alternate',3908'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3909'-type'=>"application/$type+xml"3910);39113912$href_params{'extra_options'} =undef;3913$href_params{'action'} =$type;3914$link_attr{'-href'} = href(%href_params);3915print"<link ".3916"rel=\"$link_attr{'-rel'}\"".3917"title=\"$link_attr{'-title'}\"".3918"href=\"$link_attr{'-href'}\"".3919"type=\"$link_attr{'-type'}\"".3920"/>\n";39213922$href_params{'extra_options'} ='--no-merges';3923$link_attr{'-href'} = href(%href_params);3924$link_attr{'-title'} .=' (no merges)';3925print"<link ".3926"rel=\"$link_attr{'-rel'}\"".3927"title=\"$link_attr{'-title'}\"".3928"href=\"$link_attr{'-href'}\"".3929"type=\"$link_attr{'-type'}\"".3930"/>\n";3931}39323933}else{3934printf('<link rel="alternate" title="%sprojects list" '.3935'href="%s" type="text/plain; charset=utf-8" />'."\n",3936 esc_attr($site_name), href(project=>undef, action=>"project_index"));3937printf('<link rel="alternate" title="%sprojects feeds" '.3938'href="%s" type="text/x-opml" />'."\n",3939 esc_attr($site_name), href(project=>undef, action=>"opml"));3940}3941}39423943sub print_header_links {3944my$status=shift;39453946# print out each stylesheet that exist, providing backwards capability3947# for those people who defined $stylesheet in a config file3948if(defined$stylesheet) {3949print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3950}else{3951foreachmy$stylesheet(@stylesheets) {3952next unless$stylesheet;3953print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3954}3955}3956 print_feed_meta()3957if($statuseq'200 OK');3958if(defined$favicon) {3959printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);3960}3961}39623963sub print_nav_breadcrumbs_path {3964my$dirprefix=undef;3965while(my$part=shift) {3966$dirprefix.="/"ifdefined$dirprefix;3967$dirprefix.=$part;3968print$cgi->a({-href => href(project =>undef,3969 project_filter =>$dirprefix,3970 action =>"project_list")},3971 esc_html($part)) ." / ";3972}3973}39743975sub print_nav_breadcrumbs {3976my%opts=@_;39773978print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3979if(defined$project) {3980my@dirname=split'/',$project;3981my$projectbasename=pop@dirname;3982 print_nav_breadcrumbs_path(@dirname);3983print$cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));3984if(defined$action) {3985my$action_print=$action;3986if(defined$opts{-action_extra}) {3987$action_print=$cgi->a({-href => href(action=>$action)},3988$action);3989}3990print" /$action_print";3991}3992if(defined$opts{-action_extra}) {3993print" /$opts{-action_extra}";3994}3995print"\n";3996}elsif(defined$project_filter) {3997 print_nav_breadcrumbs_path(split'/',$project_filter);3998}3999}40004001sub print_search_form {4002if(!defined$searchtext) {4003$searchtext="";4004}4005my$search_hash;4006if(defined$hash_base) {4007$search_hash=$hash_base;4008}elsif(defined$hash) {4009$search_hash=$hash;4010}else{4011$search_hash="HEAD";4012}4013my$action=$my_uri;4014my$use_pathinfo= gitweb_check_feature('pathinfo');4015if($use_pathinfo) {4016$action.="/".esc_url($project);4017}4018print$cgi->startform(-method=>"get", -action =>$action) .4019"<div class=\"search\">\n".4020(!$use_pathinfo&&4021$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .4022$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".4023$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".4024$cgi->popup_menu(-name =>'st', -default=>'commit',4025-values=> ['commit','grep','author','committer','pickaxe']) .4026$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .4027" search:\n",4028$cgi->textfield(-name =>"s", -value =>$searchtext, -override =>1) ."\n".4029"<span title=\"Extended regular expression\">".4030$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',4031-checked =>$search_use_regexp) .4032"</span>".4033"</div>".4034$cgi->end_form() ."\n";4035}40364037sub git_header_html {4038my$status=shift||"200 OK";4039my$expires=shift;4040my%opts=@_;40414042my$title= get_page_title();4043my$content_type= get_content_type_html();4044print$cgi->header(-type=>$content_type, -charset =>'utf-8',4045-status=>$status, -expires =>$expires)4046unless($opts{'-no_http_header'});4047my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';4048print<<EOF;4049<?xml version="1.0" encoding="utf-8"?>4050<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4051<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">4052<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->4053<!-- git core binaries version$git_version-->4054<head>4055<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>4056<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>4057<meta name="robots" content="index, nofollow"/>4058<title>$title</title>4059EOF4060# the stylesheet, favicon etc urls won't work correctly with path_info4061# unless we set the appropriate base URL4062if($ENV{'PATH_INFO'}) {4063print"<base href=\"".esc_url($base_url)."\"/>\n";4064}4065 print_header_links($status);40664067if(defined$site_html_head_string) {4068print to_utf8($site_html_head_string);4069}40704071print"</head>\n".4072"<body>\n";40734074if(defined$site_header&& -f $site_header) {4075 insert_file($site_header);4076}40774078print"<div class=\"page_header\">\n";4079if(defined$logo) {4080print$cgi->a({-href => esc_url($logo_url),4081-title =>$logo_label},4082$cgi->img({-src => esc_url($logo),4083-width =>72, -height =>27,4084-alt =>"git",4085-class=>"logo"}));4086}4087 print_nav_breadcrumbs(%opts);4088print"</div>\n";40894090my$have_search= gitweb_check_feature('search');4091if(defined$project&&$have_search) {4092 print_search_form();4093}4094}40954096sub git_footer_html {4097my$feed_class='rss_logo';40984099print"<div class=\"page_footer\">\n";4100if(defined$project) {4101my$descr= git_get_project_description($project);4102if(defined$descr) {4103print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";4104}41054106my%href_params= get_feed_info();4107if(!%href_params) {4108$feed_class.=' generic';4109}4110$href_params{'-title'} ||='log';41114112foreachmy$format(qw(RSS Atom)) {4113$href_params{'action'} =lc($format);4114print$cgi->a({-href => href(%href_params),4115-title =>"$href_params{'-title'}$formatfeed",4116-class=>$feed_class},$format)."\n";4117}41184119}else{4120print$cgi->a({-href => href(project=>undef, action=>"opml",4121 project_filter =>$project_filter),4122-class=>$feed_class},"OPML") ." ";4123print$cgi->a({-href => href(project=>undef, action=>"project_index",4124 project_filter =>$project_filter),4125-class=>$feed_class},"TXT") ."\n";4126}4127print"</div>\n";# class="page_footer"41284129if(defined$t0&& gitweb_check_feature('timed')) {4130print"<div id=\"generating_info\">\n";4131print'This page took '.4132'<span id="generating_time" class="time_span">'.4133 tv_interval($t0, [ gettimeofday() ]).4134' seconds </span>'.4135' and '.4136'<span id="generating_cmd">'.4137$number_of_git_cmds.4138'</span> git commands '.4139" to generate.\n";4140print"</div>\n";# class="page_footer"4141}41424143if(defined$site_footer&& -f $site_footer) {4144 insert_file($site_footer);4145}41464147print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;4148if(defined$action&&4149$actioneq'blame_incremental') {4150print qq!<script type="text/javascript">\n!.4151 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.4152 qq!"!. href() .qq!");\n!.4153 qq!</script>\n!;4154}else{4155my($jstimezone,$tz_cookie,$datetime_class) =4156 gitweb_get_feature('javascript-timezone');41574158print qq!<script type="text/javascript">\n!.4159 qq!window.onload = function () {\n!;4160if(gitweb_check_feature('javascript-actions')) {4161print qq! fixLinks();\n!;4162}4163if($jstimezone&&$tz_cookie&&$datetime_class) {4164print qq! var tz_cookie = { name:'$tz_cookie', expires:14, path:'/'};\n!.# in days4165 qq! onloadTZSetup('$jstimezone', tz_cookie,'$datetime_class');\n!;4166}4167print qq!};\n!.4168 qq!</script>\n!;4169}41704171print"</body>\n".4172"</html>";4173}41744175# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])4176# Example: die_error(404, 'Hash not found')4177# By convention, use the following status codes (as defined in RFC 2616):4178# 400: Invalid or missing CGI parameters, or4179# requested object exists but has wrong type.4180# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on4181# this server or project.4182# 404: Requested object/revision/project doesn't exist.4183# 500: The server isn't configured properly, or4184# an internal error occurred (e.g. failed assertions caused by bugs), or4185# an unknown error occurred (e.g. the git binary died unexpectedly).4186# 503: The server is currently unavailable (because it is overloaded,4187# or down for maintenance). Generally, this is a temporary state.4188sub die_error {4189my$status=shift||500;4190my$error= esc_html(shift) ||"Internal Server Error";4191my$extra=shift;4192my%opts=@_;41934194my%http_responses= (4195400=>'400 Bad Request',4196403=>'403 Forbidden',4197404=>'404 Not Found',4198500=>'500 Internal Server Error',4199503=>'503 Service Unavailable',4200);4201 git_header_html($http_responses{$status},undef,%opts);4202print<<EOF;4203<div class="page_body">4204<br /><br />4205$status-$error4206<br />4207EOF4208if(defined$extra) {4209print"<hr />\n".4210"$extra\n";4211}4212print"</div>\n";42134214 git_footer_html();4215goto DONE_GITWEB4216unless($opts{'-error_handler'});4217}42184219## ----------------------------------------------------------------------4220## functions printing or outputting HTML: navigation42214222sub git_print_page_nav {4223my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;4224$extra=''if!defined$extra;# pager or formats42254226my@navs=qw(summary shortlog log commit commitdiff tree);4227if($suppress) {4228@navs=grep{$_ne$suppress}@navs;4229}42304231my%arg=map{$_=> {action=>$_} }@navs;4232if(defined$head) {4233for(qw(commit commitdiff)) {4234$arg{$_}{'hash'} =$head;4235}4236if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {4237for(qw(shortlog log)) {4238$arg{$_}{'hash'} =$head;4239}4240}4241}42424243$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;4244$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;42454246my@actions= gitweb_get_feature('actions');4247my%repl= (4248'%'=>'%',4249'n'=>$project,# project name4250'f'=>$git_dir,# project path within filesystem4251'h'=>$treehead||'',# current hash ('h' parameter)4252'b'=>$treebase||'',# hash base ('hb' parameter)4253);4254while(@actions) {4255my($label,$link,$pos) =splice(@actions,0,3);4256# insert4257@navs=map{$_eq$pos? ($_,$label) :$_}@navs;4258# munch munch4259$link=~s/%([%nfhb])/$repl{$1}/g;4260$arg{$label}{'_href'} =$link;4261}42624263print"<div class=\"page_nav\">\n".4264(join" | ",4265map{$_eq$current?4266$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4267}@navs);4268print"<br/>\n$extra<br/>\n".4269"</div>\n";4270}42714272# returns a submenu for the nagivation of the refs views (tags, heads,4273# remotes) with the current view disabled and the remotes view only4274# available if the feature is enabled4275sub format_ref_views {4276my($current) =@_;4277my@ref_views=qw{tags heads};4278push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4279returnjoin" | ",map{4280$_eq$current?$_:4281$cgi->a({-href => href(action=>$_)},$_)4282}@ref_views4283}42844285sub format_paging_nav {4286my($action,$page,$has_next_link) =@_;4287my$paging_nav;428842894290if($page>0) {4291$paging_nav.=4292$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4293" ⋅ ".4294$cgi->a({-href => href(-replay=>1, page=>$page-1),4295-accesskey =>"p", -title =>"Alt-p"},"prev");4296}else{4297$paging_nav.="first ⋅ prev";4298}42994300if($has_next_link) {4301$paging_nav.=" ⋅ ".4302$cgi->a({-href => href(-replay=>1, page=>$page+1),4303-accesskey =>"n", -title =>"Alt-n"},"next");4304}else{4305$paging_nav.=" ⋅ next";4306}43074308return$paging_nav;4309}43104311## ......................................................................4312## functions printing or outputting HTML: div43134314sub git_print_header_div {4315my($action,$title,$hash,$hash_base) =@_;4316my%args= ();43174318$args{'action'} =$action;4319$args{'hash'} =$hashif$hash;4320$args{'hash_base'} =$hash_baseif$hash_base;43214322print"<div class=\"header\">\n".4323$cgi->a({-href => href(%args), -class=>"title"},4324$title?$title:$action) .4325"\n</div>\n";4326}43274328sub format_repo_url {4329my($name,$url) =@_;4330return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4331}43324333# Group output by placing it in a DIV element and adding a header.4334# Options for start_div() can be provided by passing a hash reference as the4335# first parameter to the function.4336# Options to git_print_header_div() can be provided by passing an array4337# reference. This must follow the options to start_div if they are present.4338# The content can be a scalar, which is output as-is, a scalar reference, which4339# is output after html escaping, an IO handle passed either as *handle or4340# *handle{IO}, or a function reference. In the latter case all following4341# parameters will be taken as argument to the content function call.4342sub git_print_section {4343my($div_args,$header_args,$content);4344my$arg=shift;4345if(ref($arg)eq'HASH') {4346$div_args=$arg;4347$arg=shift;4348}4349if(ref($arg)eq'ARRAY') {4350$header_args=$arg;4351$arg=shift;4352}4353$content=$arg;43544355print$cgi->start_div($div_args);4356 git_print_header_div(@$header_args);43574358if(ref($content)eq'CODE') {4359$content->(@_);4360}elsif(ref($content)eq'SCALAR') {4361print esc_html($$content);4362}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4363print<$content>;4364}elsif(!ref($content) &&defined($content)) {4365print$content;4366}43674368print$cgi->end_div;4369}43704371sub format_timestamp_html {4372my$date=shift;4373my$strtime=$date->{'rfc2822'};43744375my(undef,undef,$datetime_class) =4376 gitweb_get_feature('javascript-timezone');4377if($datetime_class) {4378$strtime= qq!<span class="$datetime_class">$strtime</span>!;4379}43804381my$localtime_format='(%02d:%02d%s)';4382if($date->{'hour_local'} <6) {4383$localtime_format='(<span class="atnight">%02d:%02d</span>%s)';4384}4385$strtime.=' '.4386sprintf($localtime_format,4387$date->{'hour_local'},$date->{'minute_local'},$date->{'tz_local'});43884389return$strtime;4390}43914392# Outputs the author name and date in long form4393sub git_print_authorship {4394my$co=shift;4395my%opts=@_;4396my$tag=$opts{-tag} ||'div';4397my$author=$co->{'author_name'};43984399my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4400print"<$tagclass=\"author_date\">".4401 format_search_author($author,"author", esc_html($author)) .4402" [".format_timestamp_html(\%ad)."]".4403 git_get_avatar($co->{'author_email'}, -pad_before =>1) .4404"</$tag>\n";4405}44064407# Outputs table rows containing the full author or committer information,4408# in the format expected for 'commit' view (& similar).4409# Parameters are a commit hash reference, followed by the list of people4410# to output information for. If the list is empty it defaults to both4411# author and committer.4412sub git_print_authorship_rows {4413my$co=shift;4414# too bad we can't use @people = @_ || ('author', 'committer')4415my@people=@_;4416@people= ('author','committer')unless@people;4417foreachmy$who(@people) {4418my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4419print"<tr><td>$who</td><td>".4420 format_search_author($co->{"${who}_name"},$who,4421 esc_html($co->{"${who}_name"})) ." ".4422 format_search_author($co->{"${who}_email"},$who,4423 esc_html("<".$co->{"${who}_email"} .">")) .4424"</td><td rowspan=\"2\">".4425 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4426"</td></tr>\n".4427"<tr>".4428"<td></td><td>".4429 format_timestamp_html(\%wd) .4430"</td>".4431"</tr>\n";4432}4433}44344435sub git_print_page_path {4436my$name=shift;4437my$type=shift;4438my$hb=shift;443944404441print"<div class=\"page_path\">";4442print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4443-title =>'tree root'}, to_utf8("[$project]"));4444print" / ";4445if(defined$name) {4446my@dirname=split'/',$name;4447my$basename=pop@dirname;4448my$fullname='';44494450foreachmy$dir(@dirname) {4451$fullname.= ($fullname?'/':'') .$dir;4452print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4453 hash_base=>$hb),4454-title =>$fullname}, esc_path($dir));4455print" / ";4456}4457if(defined$type&&$typeeq'blob') {4458print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4459 hash_base=>$hb),4460-title =>$name}, esc_path($basename));4461}elsif(defined$type&&$typeeq'tree') {4462print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4463 hash_base=>$hb),4464-title =>$name}, esc_path($basename));4465print" / ";4466}else{4467print esc_path($basename);4468}4469}4470print"<br/></div>\n";4471}44724473sub git_print_log {4474my$log=shift;4475my%opts=@_;44764477if($opts{'-remove_title'}) {4478# remove title, i.e. first line of log4479shift@$log;4480}4481# remove leading empty lines4482while(defined$log->[0] &&$log->[0]eq"") {4483shift@$log;4484}44854486# print log4487my$skip_blank_line=0;4488foreachmy$line(@$log) {4489if($line=~m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {4490if(!$opts{'-remove_signoff'}) {4491print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4492$skip_blank_line=1;4493}4494next;4495}44964497if($line=~ m,\s*([a-z]*link): (https?://\S+),i) {4498if(!$opts{'-remove_signoff'}) {4499print"<span class=\"signoff\">". esc_html($1) .": ".4500"<a href=\"". esc_html($2) ."\">". esc_html($2) ."</a>".4501"</span><br/>\n";4502$skip_blank_line=1;4503}4504next;4505}45064507# print only one empty line4508# do not print empty line after signoff4509if($lineeq"") {4510next if($skip_blank_line);4511$skip_blank_line=1;4512}else{4513$skip_blank_line=0;4514}45154516print format_log_line_html($line) ."<br/>\n";4517}45184519if($opts{'-final_empty_line'}) {4520# end with single empty line4521print"<br/>\n"unless$skip_blank_line;4522}4523}45244525# return link target (what link points to)4526sub git_get_link_target {4527my$hash=shift;4528my$link_target;45294530# read link4531open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4532orreturn;4533{4534local$/=undef;4535$link_target= <$fd>;4536}4537close$fd4538orreturn;45394540return$link_target;4541}45424543# given link target, and the directory (basedir) the link is in,4544# return target of link relative to top directory (top tree);4545# return undef if it is not possible (including absolute links).4546sub normalize_link_target {4547my($link_target,$basedir) =@_;45484549# absolute symlinks (beginning with '/') cannot be normalized4550return if(substr($link_target,0,1)eq'/');45514552# normalize link target to path from top (root) tree (dir)4553my$path;4554if($basedir) {4555$path=$basedir.'/'.$link_target;4556}else{4557# we are in top (root) tree (dir)4558$path=$link_target;4559}45604561# remove //, /./, and /../4562my@path_parts;4563foreachmy$part(split('/',$path)) {4564# discard '.' and ''4565next if(!$part||$parteq'.');4566# handle '..'4567if($parteq'..') {4568if(@path_parts) {4569pop@path_parts;4570}else{4571# link leads outside repository (outside top dir)4572return;4573}4574}else{4575push@path_parts,$part;4576}4577}4578$path=join('/',@path_parts);45794580return$path;4581}45824583# print tree entry (row of git_tree), but without encompassing <tr> element4584sub git_print_tree_entry {4585my($t,$basedir,$hash_base,$have_blame) =@_;45864587my%base_key= ();4588$base_key{'hash_base'} =$hash_baseifdefined$hash_base;45894590# The format of a table row is: mode list link. Where mode is4591# the mode of the entry, list is the name of the entry, an href,4592# and link is the action links of the entry.45934594print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4595if(exists$t->{'size'}) {4596print"<td class=\"size\">$t->{'size'}</td>\n";4597}4598if($t->{'type'}eq"blob") {4599print"<td class=\"list\">".4600$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4601 file_name=>"$basedir$t->{'name'}",%base_key),4602-class=>"list"}, esc_path($t->{'name'}));4603if(S_ISLNK(oct$t->{'mode'})) {4604my$link_target= git_get_link_target($t->{'hash'});4605if($link_target) {4606my$norm_target= normalize_link_target($link_target,$basedir);4607if(defined$norm_target) {4608print" -> ".4609$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4610 file_name=>$norm_target),4611-title =>$norm_target}, esc_path($link_target));4612}else{4613print" -> ". esc_path($link_target);4614}4615}4616}4617print"</td>\n";4618print"<td class=\"link\">";4619print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4620 file_name=>"$basedir$t->{'name'}",%base_key)},4621"blob");4622if($have_blame) {4623print" | ".4624$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4625 file_name=>"$basedir$t->{'name'}",%base_key)},4626"blame");4627}4628if(defined$hash_base) {4629print" | ".4630$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4631 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4632"history");4633}4634print" | ".4635$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4636 file_name=>"$basedir$t->{'name'}")},4637"raw");4638print"</td>\n";46394640}elsif($t->{'type'}eq"tree") {4641print"<td class=\"list\">";4642print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4643 file_name=>"$basedir$t->{'name'}",4644%base_key)},4645 esc_path($t->{'name'}));4646print"</td>\n";4647print"<td class=\"link\">";4648print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4649 file_name=>"$basedir$t->{'name'}",4650%base_key)},4651"tree");4652if(defined$hash_base) {4653print" | ".4654$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4655 file_name=>"$basedir$t->{'name'}")},4656"history");4657}4658print"</td>\n";4659}else{4660# unknown object: we can only present history for it4661# (this includes 'commit' object, i.e. submodule support)4662print"<td class=\"list\">".4663 esc_path($t->{'name'}) .4664"</td>\n";4665print"<td class=\"link\">";4666if(defined$hash_base) {4667print$cgi->a({-href => href(action=>"history",4668 hash_base=>$hash_base,4669 file_name=>"$basedir$t->{'name'}")},4670"history");4671}4672print"</td>\n";4673}4674}46754676## ......................................................................4677## functions printing large fragments of HTML46784679# get pre-image filenames for merge (combined) diff4680sub fill_from_file_info {4681my($diff,@parents) =@_;46824683$diff->{'from_file'} = [ ];4684$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4685for(my$i=0;$i<$diff->{'nparents'};$i++) {4686if($diff->{'status'}[$i]eq'R'||4687$diff->{'status'}[$i]eq'C') {4688$diff->{'from_file'}[$i] =4689 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4690}4691}46924693return$diff;4694}46954696# is current raw difftree line of file deletion4697sub is_deleted {4698my$diffinfo=shift;46994700return$diffinfo->{'to_id'}eq('0' x 40);4701}47024703# does patch correspond to [previous] difftree raw line4704# $diffinfo - hashref of parsed raw diff format4705# $patchinfo - hashref of parsed patch diff format4706# (the same keys as in $diffinfo)4707sub is_patch_split {4708my($diffinfo,$patchinfo) =@_;47094710returndefined$diffinfo&&defined$patchinfo4711&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4712}471347144715sub git_difftree_body {4716my($difftree,$hash,@parents) =@_;4717my($parent) =$parents[0];4718my$have_blame= gitweb_check_feature('blame');4719print"<div class=\"list_head\">\n";4720if($#{$difftree} >10) {4721print(($#{$difftree} +1) ." files changed:\n");4722}4723print"</div>\n";47244725print"<table class=\"".4726(@parents>1?"combined ":"") .4727"diff_tree\">\n";47284729# header only for combined diff in 'commitdiff' view4730my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4731if($has_header) {4732# table header4733print"<thead><tr>\n".4734"<th></th><th></th>\n";# filename, patchN link4735for(my$i=0;$i<@parents;$i++) {4736my$par=$parents[$i];4737print"<th>".4738$cgi->a({-href => href(action=>"commitdiff",4739 hash=>$hash, hash_parent=>$par),4740-title =>'commitdiff to parent number '.4741($i+1) .': '.substr($par,0,7)},4742$i+1) .4743" </th>\n";4744}4745print"</tr></thead>\n<tbody>\n";4746}47474748my$alternate=1;4749my$patchno=0;4750foreachmy$line(@{$difftree}) {4751my$diff= parsed_difftree_line($line);47524753if($alternate) {4754print"<tr class=\"dark\">\n";4755}else{4756print"<tr class=\"light\">\n";4757}4758$alternate^=1;47594760if(exists$diff->{'nparents'}) {# combined diff47614762 fill_from_file_info($diff,@parents)4763unlessexists$diff->{'from_file'};47644765if(!is_deleted($diff)) {4766# file exists in the result (child) commit4767print"<td>".4768$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4769 file_name=>$diff->{'to_file'},4770 hash_base=>$hash),4771-class=>"list"}, esc_path($diff->{'to_file'})) .4772"</td>\n";4773}else{4774print"<td>".4775 esc_path($diff->{'to_file'}) .4776"</td>\n";4777}47784779if($actioneq'commitdiff') {4780# link to patch4781$patchno++;4782print"<td class=\"link\">".4783$cgi->a({-href => href(-anchor=>"patch$patchno")},4784"patch") .4785" | ".4786"</td>\n";4787}47884789my$has_history=0;4790my$not_deleted=0;4791for(my$i=0;$i<$diff->{'nparents'};$i++) {4792my$hash_parent=$parents[$i];4793my$from_hash=$diff->{'from_id'}[$i];4794my$from_path=$diff->{'from_file'}[$i];4795my$status=$diff->{'status'}[$i];47964797$has_history||= ($statusne'A');4798$not_deleted||= ($statusne'D');47994800if($statuseq'A') {4801print"<td class=\"link\"align=\"right\"> | </td>\n";4802}elsif($statuseq'D') {4803print"<td class=\"link\">".4804$cgi->a({-href => href(action=>"blob",4805 hash_base=>$hash,4806 hash=>$from_hash,4807 file_name=>$from_path)},4808"blob". ($i+1)) .4809" | </td>\n";4810}else{4811if($diff->{'to_id'}eq$from_hash) {4812print"<td class=\"link nochange\">";4813}else{4814print"<td class=\"link\">";4815}4816print$cgi->a({-href => href(action=>"blobdiff",4817 hash=>$diff->{'to_id'},4818 hash_parent=>$from_hash,4819 hash_base=>$hash,4820 hash_parent_base=>$hash_parent,4821 file_name=>$diff->{'to_file'},4822 file_parent=>$from_path)},4823"diff". ($i+1)) .4824" | </td>\n";4825}4826}48274828print"<td class=\"link\">";4829if($not_deleted) {4830print$cgi->a({-href => href(action=>"blob",4831 hash=>$diff->{'to_id'},4832 file_name=>$diff->{'to_file'},4833 hash_base=>$hash)},4834"blob");4835print" | "if($has_history);4836}4837if($has_history) {4838print$cgi->a({-href => href(action=>"history",4839 file_name=>$diff->{'to_file'},4840 hash_base=>$hash)},4841"history");4842}4843print"</td>\n";48444845print"</tr>\n";4846next;# instead of 'else' clause, to avoid extra indent4847}4848# else ordinary diff48494850my($to_mode_oct,$to_mode_str,$to_file_type);4851my($from_mode_oct,$from_mode_str,$from_file_type);4852if($diff->{'to_mode'}ne('0' x 6)) {4853$to_mode_oct=oct$diff->{'to_mode'};4854if(S_ISREG($to_mode_oct)) {# only for regular file4855$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4856}4857$to_file_type= file_type($diff->{'to_mode'});4858}4859if($diff->{'from_mode'}ne('0' x 6)) {4860$from_mode_oct=oct$diff->{'from_mode'};4861if(S_ISREG($from_mode_oct)) {# only for regular file4862$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4863}4864$from_file_type= file_type($diff->{'from_mode'});4865}48664867if($diff->{'status'}eq"A") {# created4868my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4869$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4870$mode_chng.="]</span>";4871print"<td>";4872print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4873 hash_base=>$hash, file_name=>$diff->{'file'}),4874-class=>"list"}, esc_path($diff->{'file'}));4875print"</td>\n";4876print"<td>$mode_chng</td>\n";4877print"<td class=\"link\">";4878if($actioneq'commitdiff') {4879# link to patch4880$patchno++;4881print$cgi->a({-href => href(-anchor=>"patch$patchno")},4882"patch") .4883" | ";4884}4885print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4886 hash_base=>$hash, file_name=>$diff->{'file'})},4887"blob");4888print"</td>\n";48894890}elsif($diff->{'status'}eq"D") {# deleted4891my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4892print"<td>";4893print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4894 hash_base=>$parent, file_name=>$diff->{'file'}),4895-class=>"list"}, esc_path($diff->{'file'}));4896print"</td>\n";4897print"<td>$mode_chng</td>\n";4898print"<td class=\"link\">";4899if($actioneq'commitdiff') {4900# link to patch4901$patchno++;4902print$cgi->a({-href => href(-anchor=>"patch$patchno")},4903"patch") .4904" | ";4905}4906print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4907 hash_base=>$parent, file_name=>$diff->{'file'})},4908"blob") ." | ";4909if($have_blame) {4910print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4911 file_name=>$diff->{'file'})},4912"blame") ." | ";4913}4914print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4915 file_name=>$diff->{'file'})},4916"history");4917print"</td>\n";49184919}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4920my$mode_chnge="";4921if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4922$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4923if($from_file_typene$to_file_type) {4924$mode_chnge.=" from$from_file_typeto$to_file_type";4925}4926if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4927if($from_mode_str&&$to_mode_str) {4928$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4929}elsif($to_mode_str) {4930$mode_chnge.=" mode:$to_mode_str";4931}4932}4933$mode_chnge.="]</span>\n";4934}4935print"<td>";4936print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4937 hash_base=>$hash, file_name=>$diff->{'file'}),4938-class=>"list"}, esc_path($diff->{'file'}));4939print"</td>\n";4940print"<td>$mode_chnge</td>\n";4941print"<td class=\"link\">";4942if($actioneq'commitdiff') {4943# link to patch4944$patchno++;4945print$cgi->a({-href => href(-anchor=>"patch$patchno")},4946"patch") .4947" | ";4948}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4949# "commit" view and modified file (not onlu mode changed)4950print$cgi->a({-href => href(action=>"blobdiff",4951 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4952 hash_base=>$hash, hash_parent_base=>$parent,4953 file_name=>$diff->{'file'})},4954"diff") .4955" | ";4956}4957print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4958 hash_base=>$hash, file_name=>$diff->{'file'})},4959"blob") ." | ";4960if($have_blame) {4961print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4962 file_name=>$diff->{'file'})},4963"blame") ." | ";4964}4965print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4966 file_name=>$diff->{'file'})},4967"history");4968print"</td>\n";49694970}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4971my%status_name= ('R'=>'moved','C'=>'copied');4972my$nstatus=$status_name{$diff->{'status'}};4973my$mode_chng="";4974if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4975# mode also for directories, so we cannot use $to_mode_str4976$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4977}4978print"<td>".4979$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4980 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4981-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4982"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4983$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4984 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4985-class=>"list"}, esc_path($diff->{'from_file'})) .4986" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4987"<td class=\"link\">";4988if($actioneq'commitdiff') {4989# link to patch4990$patchno++;4991print$cgi->a({-href => href(-anchor=>"patch$patchno")},4992"patch") .4993" | ";4994}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4995# "commit" view and modified file (not only pure rename or copy)4996print$cgi->a({-href => href(action=>"blobdiff",4997 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4998 hash_base=>$hash, hash_parent_base=>$parent,4999 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},5000"diff") .5001" | ";5002}5003print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},5004 hash_base=>$parent, file_name=>$diff->{'to_file'})},5005"blob") ." | ";5006if($have_blame) {5007print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,5008 file_name=>$diff->{'to_file'})},5009"blame") ." | ";5010}5011print$cgi->a({-href => href(action=>"history", hash_base=>$hash,5012 file_name=>$diff->{'to_file'})},5013"history");5014print"</td>\n";50155016}# we should not encounter Unmerged (U) or Unknown (X) status5017print"</tr>\n";5018}5019print"</tbody>"if$has_header;5020print"</table>\n";5021}50225023# Print context lines and then rem/add lines in a side-by-side manner.5024sub print_sidebyside_diff_lines {5025my($ctx,$rem,$add) =@_;50265027# print context block before add/rem block5028if(@$ctx) {5029print join'',5030'<div class="chunk_block ctx">',5031'<div class="old">',5032@$ctx,5033'</div>',5034'<div class="new">',5035@$ctx,5036'</div>',5037'</div>';5038}50395040if(!@$add) {5041# pure removal5042print join'',5043'<div class="chunk_block rem">',5044'<div class="old">',5045@$rem,5046'</div>',5047'</div>';5048}elsif(!@$rem) {5049# pure addition5050print join'',5051'<div class="chunk_block add">',5052'<div class="new">',5053@$add,5054'</div>',5055'</div>';5056}else{5057print join'',5058'<div class="chunk_block chg">',5059'<div class="old">',5060@$rem,5061'</div>',5062'<div class="new">',5063@$add,5064'</div>',5065'</div>';5066}5067}50685069# Print context lines and then rem/add lines in inline manner.5070sub print_inline_diff_lines {5071my($ctx,$rem,$add) =@_;50725073print@$ctx,@$rem,@$add;5074}50755076# Format removed and added line, mark changed part and HTML-format them.5077# Implementation is based on contrib/diff-highlight5078sub format_rem_add_lines_pair {5079my($rem,$add,$num_parents) =@_;50805081# We need to untabify lines before split()'ing them;5082# otherwise offsets would be invalid.5083chomp$rem;5084chomp$add;5085$rem= untabify($rem);5086$add= untabify($add);50875088my@rem=split(//,$rem);5089my@add=split(//,$add);5090my($esc_rem,$esc_add);5091# Ignore leading +/- characters for each parent.5092my($prefix_len,$suffix_len) = ($num_parents,0);5093my($prefix_has_nonspace,$suffix_has_nonspace);50945095my$shorter= (@rem<@add) ?@rem:@add;5096while($prefix_len<$shorter) {5097last if($rem[$prefix_len]ne$add[$prefix_len]);50985099$prefix_has_nonspace=1if($rem[$prefix_len] !~/\s/);5100$prefix_len++;5101}51025103while($prefix_len+$suffix_len<$shorter) {5104last if($rem[-1-$suffix_len]ne$add[-1-$suffix_len]);51055106$suffix_has_nonspace=1if($rem[-1-$suffix_len] !~/\s/);5107$suffix_len++;5108}51095110# Mark lines that are different from each other, but have some common5111# part that isn't whitespace. If lines are completely different, don't5112# mark them because that would make output unreadable, especially if5113# diff consists of multiple lines.5114if($prefix_has_nonspace||$suffix_has_nonspace) {5115$esc_rem= esc_html_hl_regions($rem,'marked',5116[$prefix_len,@rem-$suffix_len], -nbsp=>1);5117$esc_add= esc_html_hl_regions($add,'marked',5118[$prefix_len,@add-$suffix_len], -nbsp=>1);5119}else{5120$esc_rem= esc_html($rem, -nbsp=>1);5121$esc_add= esc_html($add, -nbsp=>1);5122}51235124return format_diff_line(\$esc_rem,'rem'),5125 format_diff_line(\$esc_add,'add');5126}51275128# HTML-format diff context, removed and added lines.5129sub format_ctx_rem_add_lines {5130my($ctx,$rem,$add,$num_parents) =@_;5131my(@new_ctx,@new_rem,@new_add);5132my$can_highlight=0;5133my$is_combined= ($num_parents>1);51345135# Highlight if every removed line has a corresponding added line.5136if(@$add>0&&@$add==@$rem) {5137$can_highlight=1;51385139# Highlight lines in combined diff only if the chunk contains5140# diff between the same version, e.g.5141#5142# - a5143# - b5144# + c5145# + d5146#5147# Otherwise the highlightling would be confusing.5148if($is_combined) {5149for(my$i=0;$i<@$add;$i++) {5150my$prefix_rem=substr($rem->[$i],0,$num_parents);5151my$prefix_add=substr($add->[$i],0,$num_parents);51525153$prefix_rem=~s/-/+/g;51545155if($prefix_remne$prefix_add) {5156$can_highlight=0;5157last;5158}5159}5160}5161}51625163if($can_highlight) {5164for(my$i=0;$i<@$add;$i++) {5165my($line_rem,$line_add) = format_rem_add_lines_pair(5166$rem->[$i],$add->[$i],$num_parents);5167push@new_rem,$line_rem;5168push@new_add,$line_add;5169}5170}else{5171@new_rem=map{ format_diff_line($_,'rem') }@$rem;5172@new_add=map{ format_diff_line($_,'add') }@$add;5173}51745175@new_ctx=map{ format_diff_line($_,'ctx') }@$ctx;51765177return(\@new_ctx, \@new_rem, \@new_add);5178}51795180# Print context lines and then rem/add lines.5181sub print_diff_lines {5182my($ctx,$rem,$add,$diff_style,$num_parents) =@_;5183my$is_combined=$num_parents>1;51845185($ctx,$rem,$add) = format_ctx_rem_add_lines($ctx,$rem,$add,5186$num_parents);51875188if($diff_styleeq'sidebyside'&& !$is_combined) {5189 print_sidebyside_diff_lines($ctx,$rem,$add);5190}else{5191# default 'inline' style and unknown styles5192 print_inline_diff_lines($ctx,$rem,$add);5193}5194}51955196sub print_diff_chunk {5197my($diff_style,$num_parents,$from,$to,@chunk) =@_;5198my(@ctx,@rem,@add);51995200# The class of the previous line.5201my$prev_class='';52025203return unless@chunk;52045205# incomplete last line might be among removed or added lines,5206# or both, or among context lines: find which5207for(my$i=1;$i<@chunk;$i++) {5208if($chunk[$i][0]eq'incomplete') {5209$chunk[$i][0] =$chunk[$i-1][0];5210}5211}52125213# guardian5214push@chunk, ["",""];52155216foreachmy$line_info(@chunk) {5217my($class,$line) =@$line_info;52185219# print chunk headers5220if($class&&$classeq'chunk_header') {5221print format_diff_line($line,$class,$from,$to);5222next;5223}52245225## print from accumulator when have some add/rem lines or end5226# of chunk (flush context lines), or when have add and rem5227# lines and new block is reached (otherwise add/rem lines could5228# be reordered)5229if(!$class|| ((@rem||@add) &&$classeq'ctx') ||5230(@rem&&@add&&$classne$prev_class)) {5231 print_diff_lines(\@ctx, \@rem, \@add,5232$diff_style,$num_parents);5233@ctx=@rem=@add= ();5234}52355236## adding lines to accumulator5237# guardian value5238last unless$line;5239# rem, add or change5240if($classeq'rem') {5241push@rem,$line;5242}elsif($classeq'add') {5243push@add,$line;5244}5245# context line5246if($classeq'ctx') {5247push@ctx,$line;5248}52495250$prev_class=$class;5251}5252}52535254sub git_patchset_body {5255my($fd,$diff_style,$difftree,$hash,@hash_parents) =@_;5256my($hash_parent) =$hash_parents[0];52575258my$is_combined= (@hash_parents>1);5259my$patch_idx=0;5260my$patch_number=0;5261my$patch_line;5262my$diffinfo;5263my$to_name;5264my(%from,%to);5265my@chunk;# for side-by-side diff52665267print"<div class=\"patchset\">\n";52685269# skip to first patch5270while($patch_line= <$fd>) {5271chomp$patch_line;52725273last if($patch_line=~m/^diff /);5274}52755276 PATCH:5277while($patch_line) {52785279# parse "git diff" header line5280if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {5281# $1 is from_name, which we do not use5282$to_name= unquote($2);5283$to_name=~s!^b/!!;5284}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {5285# $1 is 'cc' or 'combined', which we do not use5286$to_name= unquote($2);5287}else{5288$to_name=undef;5289}52905291# check if current patch belong to current raw line5292# and parse raw git-diff line if needed5293if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {5294# this is continuation of a split patch5295print"<div class=\"patch cont\">\n";5296}else{5297# advance raw git-diff output if needed5298$patch_idx++ifdefined$diffinfo;52995300# read and prepare patch information5301$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);53025303# compact combined diff output can have some patches skipped5304# find which patch (using pathname of result) we are at now;5305if($is_combined) {5306while($to_namene$diffinfo->{'to_file'}) {5307print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5308 format_diff_cc_simplified($diffinfo,@hash_parents) .5309"</div>\n";# class="patch"53105311$patch_idx++;5312$patch_number++;53135314last if$patch_idx>$#$difftree;5315$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);5316}5317}53185319# modifies %from, %to hashes5320 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);53215322# this is first patch for raw difftree line with $patch_idx index5323# we index @$difftree array from 0, but number patches from 15324print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";5325}53265327# git diff header5328#assert($patch_line =~ m/^diff /) if DEBUG;5329#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed5330$patch_number++;5331# print "git diff" header5332print format_git_diff_header_line($patch_line,$diffinfo,5333 \%from, \%to);53345335# print extended diff header5336print"<div class=\"diff extended_header\">\n";5337 EXTENDED_HEADER:5338while($patch_line= <$fd>) {5339chomp$patch_line;53405341last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);53425343print format_extended_diff_header_line($patch_line,$diffinfo,5344 \%from, \%to);5345}5346print"</div>\n";# class="diff extended_header"53475348# from-file/to-file diff header5349if(!$patch_line) {5350print"</div>\n";# class="patch"5351last PATCH;5352}5353next PATCH if($patch_line=~m/^diff /);5354#assert($patch_line =~ m/^---/) if DEBUG;53555356my$last_patch_line=$patch_line;5357$patch_line= <$fd>;5358chomp$patch_line;5359#assert($patch_line =~ m/^\+\+\+/) if DEBUG;53605361print format_diff_from_to_header($last_patch_line,$patch_line,5362$diffinfo, \%from, \%to,5363@hash_parents);53645365# the patch itself5366 LINE:5367while($patch_line= <$fd>) {5368chomp$patch_line;53695370next PATCH if($patch_line=~m/^diff /);53715372my$class= diff_line_class($patch_line, \%from, \%to);53735374if($classeq'chunk_header') {5375 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5376@chunk= ();5377}53785379push@chunk, [$class,$patch_line];5380}53815382}continue{5383if(@chunk) {5384 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5385@chunk= ();5386}5387print"</div>\n";# class="patch"5388}53895390# for compact combined (--cc) format, with chunk and patch simplification5391# the patchset might be empty, but there might be unprocessed raw lines5392for(++$patch_idxif$patch_number>0;5393$patch_idx<@$difftree;5394++$patch_idx) {5395# read and prepare patch information5396$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);53975398# generate anchor for "patch" links in difftree / whatchanged part5399print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5400 format_diff_cc_simplified($diffinfo,@hash_parents) .5401"</div>\n";# class="patch"54025403$patch_number++;5404}54055406if($patch_number==0) {5407if(@hash_parents>1) {5408print"<div class=\"diff nodifferences\">Trivial merge</div>\n";5409}else{5410print"<div class=\"diff nodifferences\">No differences found</div>\n";5411}5412}54135414print"</div>\n";# class="patchset"5415}54165417# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .54185419sub git_project_search_form {5420my($searchtext,$search_use_regexp) =@_;54215422my$limit='';5423if($project_filter) {5424$limit=" in '$project_filter/'";5425}54265427print"<div class=\"projsearch\">\n";5428print$cgi->startform(-method=>'get', -action =>$my_uri) .5429$cgi->hidden(-name =>'a', -value =>'project_list') ."\n";5430print$cgi->hidden(-name =>'pf', -value =>$project_filter)."\n"5431if(defined$project_filter);5432print$cgi->textfield(-name =>'s', -value =>$searchtext,5433-title =>"Search project by name and description$limit",5434-size =>60) ."\n".5435"<span title=\"Extended regular expression\">".5436$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',5437-checked =>$search_use_regexp) .5438"</span>\n".5439$cgi->submit(-name =>'btnS', -value =>'Search') .5440$cgi->end_form() ."\n".5441$cgi->a({-href => href(project =>undef, searchtext =>undef,5442 project_filter =>$project_filter)},5443 esc_html("List all projects$limit")) ."<br />\n";5444print"</div>\n";5445}54465447# entry for given @keys needs filling if at least one of keys in list5448# is not present in %$project_info5449sub project_info_needs_filling {5450my($project_info,@keys) =@_;54515452# return List::MoreUtils::any { !exists $project_info->{$_} } @keys;5453foreachmy$key(@keys) {5454if(!exists$project_info->{$key}) {5455return1;5456}5457}5458return;5459}54605461# fills project list info (age, description, owner, category, forks, etc.)5462# for each project in the list, removing invalid projects from5463# returned list, or fill only specified info.5464#5465# Invalid projects are removed from the returned list if and only if you5466# ask 'age' or 'age_string' to be filled, because they are the only fields5467# that run unconditionally git command that requires repository, and5468# therefore do always check if project repository is invalid.5469#5470# USAGE:5471# * fill_project_list_info(\@project_list, 'descr_long', 'ctags')5472# ensures that 'descr_long' and 'ctags' fields are filled5473# * @project_list = fill_project_list_info(\@project_list)5474# ensures that all fields are filled (and invalid projects removed)5475#5476# NOTE: modifies $projlist, but does not remove entries from it5477sub fill_project_list_info {5478my($projlist,@wanted_keys) =@_;5479my@projects;5480my$filter_set=sub{return@_; };5481if(@wanted_keys) {5482my%wanted_keys=map{$_=>1}@wanted_keys;5483$filter_set=sub{returngrep{$wanted_keys{$_} }@_; };5484}54855486my$show_ctags= gitweb_check_feature('ctags');5487 PROJECT:5488foreachmy$pr(@$projlist) {5489if(project_info_needs_filling($pr,$filter_set->('age','age_string'))) {5490my(@activity) = git_get_last_activity($pr->{'path'});5491unless(@activity) {5492next PROJECT;5493}5494($pr->{'age'},$pr->{'age_string'}) =@activity;5495}5496if(project_info_needs_filling($pr,$filter_set->('descr','descr_long'))) {5497my$descr= git_get_project_description($pr->{'path'}) ||"";5498$descr= to_utf8($descr);5499$pr->{'descr_long'} =$descr;5500$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);5501}5502if(project_info_needs_filling($pr,$filter_set->('owner'))) {5503$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";5504}5505if($show_ctags&&5506 project_info_needs_filling($pr,$filter_set->('ctags'))) {5507$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});5508}5509if($projects_list_group_categories&&5510 project_info_needs_filling($pr,$filter_set->('category'))) {5511my$cat= git_get_project_category($pr->{'path'}) ||5512$project_list_default_category;5513$pr->{'category'} = to_utf8($cat);5514}55155516push@projects,$pr;5517}55185519return@projects;5520}55215522sub sort_projects_list {5523my($projlist,$order) =@_;5524my@projects;55255526my%order_info= (5527 project => { key =>'path', type =>'str'},5528 descr => { key =>'descr_long', type =>'str'},5529 owner => { key =>'owner', type =>'str'},5530 age => { key =>'age', type =>'num'}5531);5532my$oi=$order_info{$order};5533return@$projlistunlessdefined$oi;5534if($oi->{'type'}eq'str') {5535@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@$projlist;5536}else{5537@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@$projlist;5538}55395540return@projects;5541}55425543# returns a hash of categories, containing the list of project5544# belonging to each category5545sub build_projlist_by_category {5546my($projlist,$from,$to) =@_;5547my%categories;55485549$from=0unlessdefined$from;5550$to=$#$projlistif(!defined$to||$#$projlist<$to);55515552for(my$i=$from;$i<=$to;$i++) {5553my$pr=$projlist->[$i];5554push@{$categories{$pr->{'category'} }},$pr;5555}55565557returnwantarray?%categories: \%categories;5558}55595560# print 'sort by' <th> element, generating 'sort by $name' replay link5561# if that order is not selected5562sub print_sort_th {5563print format_sort_th(@_);5564}55655566sub format_sort_th {5567my($name,$order,$header) =@_;5568my$sort_th="";5569$header||=ucfirst($name);55705571if($ordereq$name) {5572$sort_th.="<th>$header</th>\n";5573}else{5574$sort_th.="<th>".5575$cgi->a({-href => href(-replay=>1, order=>$name),5576-class=>"header"},$header) .5577"</th>\n";5578}55795580return$sort_th;5581}55825583sub git_project_list_rows {5584my($projlist,$from,$to,$check_forks) =@_;55855586$from=0unlessdefined$from;5587$to=$#$projlistif(!defined$to||$#$projlist<$to);55885589my$alternate=1;5590for(my$i=$from;$i<=$to;$i++) {5591my$pr=$projlist->[$i];55925593if($alternate) {5594print"<tr class=\"dark\">\n";5595}else{5596print"<tr class=\"light\">\n";5597}5598$alternate^=1;55995600if($check_forks) {5601print"<td>";5602if($pr->{'forks'}) {5603my$nforks=scalar@{$pr->{'forks'}};5604if($nforks>0) {5605print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5606-title =>"$nforksforks"},"+");5607}else{5608print$cgi->span({-title =>"$nforksforks"},"+");5609}5610}5611print"</td>\n";5612}5613print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5614-class=>"list"},5615 esc_html_match_hl($pr->{'path'},$search_regexp)) .5616"</td>\n".5617"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5618-class=>"list",5619-title =>$pr->{'descr_long'}},5620$search_regexp5621? esc_html_match_hl_chopped($pr->{'descr_long'},5622$pr->{'descr'},$search_regexp)5623: esc_html($pr->{'descr'})) .5624"</td>\n";5625unless($omit_owner) {5626print"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5627}5628unless($omit_age_column) {5629print"<td class=\"". age_class($pr->{'age'}) ."\">".5630(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n";5631}5632print"<td class=\"link\">".5633$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5634$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5635$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5636$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5637($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5638"</td>\n".5639"</tr>\n";5640}5641}56425643sub git_project_list_body {5644# actually uses global variable $project5645my($projlist,$order,$from,$to,$extra,$no_header) =@_;5646my@projects=@$projlist;56475648my$check_forks= gitweb_check_feature('forks');5649my$show_ctags= gitweb_check_feature('ctags');5650my$tagfilter=$show_ctags?$input_params{'ctag'} :undef;5651$check_forks=undef5652if($tagfilter||$search_regexp);56535654# filtering out forks before filling info allows to do less work5655@projects= filter_forks_from_projects_list(\@projects)5656if($check_forks);5657# search_projects_list pre-fills required info5658@projects= search_projects_list(\@projects,5659'search_regexp'=>$search_regexp,5660'tagfilter'=>$tagfilter)5661if($tagfilter||$search_regexp);5662# fill the rest5663my@all_fields= ('descr','descr_long','ctags','category');5664push@all_fields, ('age','age_string')unless($omit_age_column);5665push@all_fields,'owner'unless($omit_owner);5666@projects= fill_project_list_info(\@projects,@all_fields);56675668$order||=$default_projects_order;5669$from=0unlessdefined$from;5670$to=$#projectsif(!defined$to||$#projects<$to);56715672# short circuit5673if($from>$to) {5674print"<center>\n".5675"<b>No such projects found</b><br />\n".5676"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5677"</center>\n<br />\n";5678return;5679}56805681@projects= sort_projects_list(\@projects,$order);56825683if($show_ctags) {5684my$ctags= git_gather_all_ctags(\@projects);5685my$cloud= git_populate_project_tagcloud($ctags);5686print git_show_project_tagcloud($cloud,64);5687}56885689print"<table class=\"project_list\">\n";5690unless($no_header) {5691print"<tr>\n";5692if($check_forks) {5693print"<th></th>\n";5694}5695 print_sort_th('project',$order,'Project');5696 print_sort_th('descr',$order,'Description');5697 print_sort_th('owner',$order,'Owner')unless$omit_owner;5698 print_sort_th('age',$order,'Last Change')unless$omit_age_column;5699print"<th></th>\n".# for links5700"</tr>\n";5701}57025703if($projects_list_group_categories) {5704# only display categories with projects in the $from-$to window5705@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5706my%categories= build_projlist_by_category(\@projects,$from,$to);5707foreachmy$cat(sort keys%categories) {5708unless($cateq"") {5709print"<tr>\n";5710if($check_forks) {5711print"<td></td>\n";5712}5713print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5714print"</tr>\n";5715}57165717 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5718}5719}else{5720 git_project_list_rows(\@projects,$from,$to,$check_forks);5721}57225723if(defined$extra) {5724print"<tr>\n";5725if($check_forks) {5726print"<td></td>\n";5727}5728print"<td colspan=\"5\">$extra</td>\n".5729"</tr>\n";5730}5731print"</table>\n";5732}57335734sub git_log_body {5735# uses global variable $project5736my($commitlist,$from,$to,$refs,$extra) =@_;57375738$from=0unlessdefined$from;5739$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);57405741for(my$i=0;$i<=$to;$i++) {5742my%co= %{$commitlist->[$i]};5743next if!%co;5744my$commit=$co{'id'};5745my$ref= format_ref_marker($refs,$commit);5746 git_print_header_div('commit',5747"<span class=\"age\">$co{'age_string'}</span>".5748 esc_html($co{'title'}) .$ref,5749$commit);5750print"<div class=\"title_text\">\n".5751"<div class=\"log_link\">\n".5752$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5753" | ".5754$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5755" | ".5756$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5757"<br/>\n".5758"</div>\n";5759 git_print_authorship(\%co, -tag =>'span');5760print"<br/>\n</div>\n";57615762print"<div class=\"log_body\">\n";5763 git_print_log($co{'comment'}, -final_empty_line=>1);5764print"</div>\n";5765}5766if($extra) {5767print"<div class=\"page_nav\">\n";5768print"$extra\n";5769print"</div>\n";5770}5771}57725773sub git_shortlog_body {5774# uses global variable $project5775my($commitlist,$from,$to,$refs,$extra) =@_;57765777$from=0unlessdefined$from;5778$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);57795780print"<table class=\"shortlog\">\n";5781my$alternate=1;5782for(my$i=$from;$i<=$to;$i++) {5783my%co= %{$commitlist->[$i]};5784my$commit=$co{'id'};5785my$ref= format_ref_marker($refs,$commit);5786if($alternate) {5787print"<tr class=\"dark\">\n";5788}else{5789print"<tr class=\"light\">\n";5790}5791$alternate^=1;5792# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5793print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5794 format_author_html('td', \%co,10) ."<td>";5795print format_subject_html($co{'title'},$co{'title_short'},5796 href(action=>"commit", hash=>$commit),$ref);5797print"</td>\n".5798"<td class=\"link\">".5799$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5800$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5801$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5802my$snapshot_links= format_snapshot_links($commit);5803if(defined$snapshot_links) {5804print" | ".$snapshot_links;5805}5806print"</td>\n".5807"</tr>\n";5808}5809if(defined$extra) {5810print"<tr>\n".5811"<td colspan=\"4\">$extra</td>\n".5812"</tr>\n";5813}5814print"</table>\n";5815}58165817sub git_history_body {5818# Warning: assumes constant type (blob or tree) during history5819my($commitlist,$from,$to,$refs,$extra,5820$file_name,$file_hash,$ftype) =@_;58215822$from=0unlessdefined$from;5823$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});58245825print"<table class=\"history\">\n";5826my$alternate=1;5827for(my$i=$from;$i<=$to;$i++) {5828my%co= %{$commitlist->[$i]};5829if(!%co) {5830next;5831}5832my$commit=$co{'id'};58335834my$ref= format_ref_marker($refs,$commit);58355836if($alternate) {5837print"<tr class=\"dark\">\n";5838}else{5839print"<tr class=\"light\">\n";5840}5841$alternate^=1;5842print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5843# shortlog: format_author_html('td', \%co, 10)5844 format_author_html('td', \%co,15,3) ."<td>";5845# originally git_history used chop_str($co{'title'}, 50)5846print format_subject_html($co{'title'},$co{'title_short'},5847 href(action=>"commit", hash=>$commit),$ref);5848print"</td>\n".5849"<td class=\"link\">".5850$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5851$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");58525853if($ftypeeq'blob') {5854my$blob_current=$file_hash;5855my$blob_parent= git_get_hash_by_path($commit,$file_name);5856if(defined$blob_current&&defined$blob_parent&&5857$blob_currentne$blob_parent) {5858print" | ".5859$cgi->a({-href => href(action=>"blobdiff",5860 hash=>$blob_current, hash_parent=>$blob_parent,5861 hash_base=>$hash_base, hash_parent_base=>$commit,5862 file_name=>$file_name)},5863"diff to current");5864}5865}5866print"</td>\n".5867"</tr>\n";5868}5869if(defined$extra) {5870print"<tr>\n".5871"<td colspan=\"4\">$extra</td>\n".5872"</tr>\n";5873}5874print"</table>\n";5875}58765877sub git_tags_body {5878# uses global variable $project5879my($taglist,$from,$to,$extra) =@_;5880$from=0unlessdefined$from;5881$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);58825883print"<table class=\"tags\">\n";5884my$alternate=1;5885for(my$i=$from;$i<=$to;$i++) {5886my$entry=$taglist->[$i];5887my%tag=%$entry;5888my$comment=$tag{'subject'};5889my$comment_short;5890if(defined$comment) {5891$comment_short= chop_str($comment,30,5);5892}5893if($alternate) {5894print"<tr class=\"dark\">\n";5895}else{5896print"<tr class=\"light\">\n";5897}5898$alternate^=1;5899if(defined$tag{'age'}) {5900print"<td><i>$tag{'age'}</i></td>\n";5901}else{5902print"<td></td>\n";5903}5904print"<td>".5905$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5906-class=>"list name"}, esc_html($tag{'name'})) .5907"</td>\n".5908"<td>";5909if(defined$comment) {5910print format_subject_html($comment,$comment_short,5911 href(action=>"tag", hash=>$tag{'id'}));5912}5913print"</td>\n".5914"<td class=\"selflink\">";5915if($tag{'type'}eq"tag") {5916print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");5917}else{5918print" ";5919}5920print"</td>\n".5921"<td class=\"link\">"." | ".5922$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});5923if($tag{'reftype'}eq"commit") {5924print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .5925" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");5926}elsif($tag{'reftype'}eq"blob") {5927print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");5928}5929print"</td>\n".5930"</tr>";5931}5932if(defined$extra) {5933print"<tr>\n".5934"<td colspan=\"5\">$extra</td>\n".5935"</tr>\n";5936}5937print"</table>\n";5938}59395940sub git_heads_body {5941# uses global variable $project5942my($headlist,$head_at,$from,$to,$extra) =@_;5943$from=0unlessdefined$from;5944$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);59455946print"<table class=\"heads\">\n";5947my$alternate=1;5948for(my$i=$from;$i<=$to;$i++) {5949my$entry=$headlist->[$i];5950my%ref=%$entry;5951my$curr=defined$head_at&&$ref{'id'}eq$head_at;5952if($alternate) {5953print"<tr class=\"dark\">\n";5954}else{5955print"<tr class=\"light\">\n";5956}5957$alternate^=1;5958print"<td><i>$ref{'age'}</i></td>\n".5959($curr?"<td class=\"current_head\">":"<td>") .5960$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),5961-class=>"list name"},esc_html($ref{'name'})) .5962"</td>\n".5963"<td class=\"link\">".5964$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".5965$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".5966$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .5967"</td>\n".5968"</tr>";5969}5970if(defined$extra) {5971print"<tr>\n".5972"<td colspan=\"3\">$extra</td>\n".5973"</tr>\n";5974}5975print"</table>\n";5976}59775978# Display a single remote block5979sub git_remote_block {5980my($remote,$rdata,$limit,$head) =@_;59815982my$heads=$rdata->{'heads'};5983my$fetch=$rdata->{'fetch'};5984my$push=$rdata->{'push'};59855986my$urls_table="<table class=\"projects_list\">\n";59875988if(defined$fetch) {5989if($fetcheq$push) {5990$urls_table.= format_repo_url("URL",$fetch);5991}else{5992$urls_table.= format_repo_url("Fetch URL",$fetch);5993$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;5994}5995}elsif(defined$push) {5996$urls_table.= format_repo_url("Push URL",$push);5997}else{5998$urls_table.= format_repo_url("","No remote URL");5999}60006001$urls_table.="</table>\n";60026003my$dots;6004if(defined$limit&&$limit<@$heads) {6005$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");6006}60076008print$urls_table;6009 git_heads_body($heads,$head,0,$limit,$dots);6010}60116012# Display a list of remote names with the respective fetch and push URLs6013sub git_remotes_list {6014my($remotedata,$limit) =@_;6015print"<table class=\"heads\">\n";6016my$alternate=1;6017my@remotes=sort keys%$remotedata;60186019my$limited=$limit&&$limit<@remotes;60206021$#remotes=$limit-1if$limited;60226023while(my$remote=shift@remotes) {6024my$rdata=$remotedata->{$remote};6025my$fetch=$rdata->{'fetch'};6026my$push=$rdata->{'push'};6027if($alternate) {6028print"<tr class=\"dark\">\n";6029}else{6030print"<tr class=\"light\">\n";6031}6032$alternate^=1;6033print"<td>".6034$cgi->a({-href=> href(action=>'remotes', hash=>$remote),6035-class=>"list name"},esc_html($remote)) .6036"</td>";6037print"<td class=\"link\">".6038(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .6039" | ".6040(defined$push?$cgi->a({-href=>$push},"push") :"push") .6041"</td>";60426043print"</tr>\n";6044}60456046if($limited) {6047print"<tr>\n".6048"<td colspan=\"3\">".6049$cgi->a({-href => href(action=>"remotes")},"...") .6050"</td>\n"."</tr>\n";6051}60526053print"</table>";6054}60556056# Display remote heads grouped by remote, unless there are too many6057# remotes, in which case we only display the remote names6058sub git_remotes_body {6059my($remotedata,$limit,$head) =@_;6060if($limitand$limit<keys%$remotedata) {6061 git_remotes_list($remotedata,$limit);6062}else{6063 fill_remote_heads($remotedata);6064while(my($remote,$rdata) =each%$remotedata) {6065 git_print_section({-class=>"remote", -id=>$remote},6066["remotes",$remote,$remote],sub{6067 git_remote_block($remote,$rdata,$limit,$head);6068});6069}6070}6071}60726073sub git_search_message {6074my%co=@_;60756076my$greptype;6077if($searchtypeeq'commit') {6078$greptype="--grep=";6079}elsif($searchtypeeq'author') {6080$greptype="--author=";6081}elsif($searchtypeeq'committer') {6082$greptype="--committer=";6083}6084$greptype.=$searchtext;6085my@commitlist= parse_commits($hash,101, (100*$page),undef,6086$greptype,'--regexp-ignore-case',6087$search_use_regexp?'--extended-regexp':'--fixed-strings');60886089my$paging_nav='';6090if($page>0) {6091$paging_nav.=6092$cgi->a({-href => href(-replay=>1, page=>undef)},6093"first") .6094" ⋅ ".6095$cgi->a({-href => href(-replay=>1, page=>$page-1),6096-accesskey =>"p", -title =>"Alt-p"},"prev");6097}else{6098$paging_nav.="first ⋅ prev";6099}6100my$next_link='';6101if($#commitlist>=100) {6102$next_link=6103$cgi->a({-href => href(-replay=>1, page=>$page+1),6104-accesskey =>"n", -title =>"Alt-n"},"next");6105$paging_nav.=" ⋅$next_link";6106}else{6107$paging_nav.=" ⋅ next";6108}61096110 git_header_html();61116112 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);6113 git_print_header_div('commit', esc_html($co{'title'}),$hash);6114if($page==0&& !@commitlist) {6115print"<p>No match.</p>\n";6116}else{6117 git_search_grep_body(\@commitlist,0,99,$next_link);6118}61196120 git_footer_html();6121}61226123sub git_search_changes {6124my%co=@_;61256126local$/="\n";6127open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,6128'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",6129($search_use_regexp?'--pickaxe-regex': ())6130or die_error(500,"Open git-log failed");61316132 git_header_html();61336134 git_print_page_nav('','',$hash,$co{'tree'},$hash);6135 git_print_header_div('commit', esc_html($co{'title'}),$hash);61366137print"<table class=\"pickaxe search\">\n";6138my$alternate=1;6139undef%co;6140my@files;6141while(my$line= <$fd>) {6142chomp$line;6143next unless$line;61446145my%set= parse_difftree_raw_line($line);6146if(defined$set{'commit'}) {6147# finish previous commit6148if(%co) {6149print"</td>\n".6150"<td class=\"link\">".6151$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6152"commit") .6153" | ".6154$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6155 hash_base=>$co{'id'})},6156"tree") .6157"</td>\n".6158"</tr>\n";6159}61606161if($alternate) {6162print"<tr class=\"dark\">\n";6163}else{6164print"<tr class=\"light\">\n";6165}6166$alternate^=1;6167%co= parse_commit($set{'commit'});6168my$author= chop_and_escape_str($co{'author_name'},15,5);6169print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6170"<td><i>$author</i></td>\n".6171"<td>".6172$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6173-class=>"list subject"},6174 chop_and_escape_str($co{'title'},50) ."<br/>");6175}elsif(defined$set{'to_id'}) {6176next if($set{'to_id'} =~m/^0{40}$/);61776178print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},6179 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),6180-class=>"list"},6181"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .6182"<br/>\n";6183}6184}6185close$fd;61866187# finish last commit (warning: repetition!)6188if(%co) {6189print"</td>\n".6190"<td class=\"link\">".6191$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6192"commit") .6193" | ".6194$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6195 hash_base=>$co{'id'})},6196"tree") .6197"</td>\n".6198"</tr>\n";6199}62006201print"</table>\n";62026203 git_footer_html();6204}62056206sub git_search_files {6207my%co=@_;62086209local$/="\n";6210open my$fd,"-|", git_cmd(),'grep','-n','-z',6211$search_use_regexp? ('-E','-i') :'-F',6212$searchtext,$co{'tree'}6213or die_error(500,"Open git-grep failed");62146215 git_header_html();62166217 git_print_page_nav('','',$hash,$co{'tree'},$hash);6218 git_print_header_div('commit', esc_html($co{'title'}),$hash);62196220print"<table class=\"grep_search\">\n";6221my$alternate=1;6222my$matches=0;6223my$lastfile='';6224my$file_href;6225while(my$line= <$fd>) {6226chomp$line;6227my($file,$lno,$ltext,$binary);6228last if($matches++>1000);6229if($line=~/^Binary file (.+) matches$/) {6230$file=$1;6231$binary=1;6232}else{6233($file,$lno,$ltext) =split(/\0/,$line,3);6234$file=~s/^$co{'tree'}://;6235}6236if($filene$lastfile) {6237$lastfileand print"</td></tr>\n";6238if($alternate++) {6239print"<tr class=\"dark\">\n";6240}else{6241print"<tr class=\"light\">\n";6242}6243$file_href= href(action=>"blob", hash_base=>$co{'id'},6244 file_name=>$file);6245print"<td class=\"list\">".6246$cgi->a({-href =>$file_href, -class=>"list"}, esc_path($file));6247print"</td><td>\n";6248$lastfile=$file;6249}6250if($binary) {6251print"<div class=\"binary\">Binary file</div>\n";6252}else{6253$ltext= untabify($ltext);6254if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6255$ltext= esc_html($1, -nbsp=>1);6256$ltext.='<span class="match">';6257$ltext.= esc_html($2, -nbsp=>1);6258$ltext.='</span>';6259$ltext.= esc_html($3, -nbsp=>1);6260}else{6261$ltext= esc_html($ltext, -nbsp=>1);6262}6263print"<div class=\"pre\">".6264$cgi->a({-href =>$file_href.'#l'.$lno,6265-class=>"linenr"},sprintf('%4i',$lno)) .6266' '.$ltext."</div>\n";6267}6268}6269if($lastfile) {6270print"</td></tr>\n";6271if($matches>1000) {6272print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6273}6274}else{6275print"<div class=\"diff nodifferences\">No matches found</div>\n";6276}6277close$fd;62786279print"</table>\n";62806281 git_footer_html();6282}62836284sub git_search_grep_body {6285my($commitlist,$from,$to,$extra) =@_;6286$from=0unlessdefined$from;6287$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);62886289print"<table class=\"commit_search\">\n";6290my$alternate=1;6291for(my$i=$from;$i<=$to;$i++) {6292my%co= %{$commitlist->[$i]};6293if(!%co) {6294next;6295}6296my$commit=$co{'id'};6297if($alternate) {6298print"<tr class=\"dark\">\n";6299}else{6300print"<tr class=\"light\">\n";6301}6302$alternate^=1;6303print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6304 format_author_html('td', \%co,15,5) .6305"<td>".6306$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6307-class=>"list subject"},6308 chop_and_escape_str($co{'title'},50) ."<br/>");6309my$comment=$co{'comment'};6310foreachmy$line(@$comment) {6311if($line=~m/^(.*?)($search_regexp)(.*)$/i) {6312my($lead,$match,$trail) = ($1,$2,$3);6313$match= chop_str($match,70,5,'center');6314my$contextlen=int((80-length($match))/2);6315$contextlen=30if($contextlen>30);6316$lead= chop_str($lead,$contextlen,10,'left');6317$trail= chop_str($trail,$contextlen,10,'right');63186319$lead= esc_html($lead);6320$match= esc_html($match);6321$trail= esc_html($trail);63226323print"$lead<span class=\"match\">$match</span>$trail<br />";6324}6325}6326print"</td>\n".6327"<td class=\"link\">".6328$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6329" | ".6330$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .6331" | ".6332$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6333print"</td>\n".6334"</tr>\n";6335}6336if(defined$extra) {6337print"<tr>\n".6338"<td colspan=\"3\">$extra</td>\n".6339"</tr>\n";6340}6341print"</table>\n";6342}63436344## ======================================================================6345## ======================================================================6346## actions63476348sub git_project_list {6349my$order=$input_params{'order'};6350if(defined$order&&$order!~m/none|project|descr|owner|age/) {6351 die_error(400,"Unknown order parameter");6352}63536354my@list= git_get_projects_list($project_filter,$strict_export);6355if(!@list) {6356 die_error(404,"No projects found");6357}63586359 git_header_html();6360if(defined$home_text&& -f $home_text) {6361print"<div class=\"index_include\">\n";6362 insert_file($home_text);6363print"</div>\n";6364}63656366 git_project_search_form($searchtext,$search_use_regexp);6367 git_project_list_body(\@list,$order);6368 git_footer_html();6369}63706371sub git_forks {6372my$order=$input_params{'order'};6373if(defined$order&&$order!~m/none|project|descr|owner|age/) {6374 die_error(400,"Unknown order parameter");6375}63766377my$filter=$project;6378$filter=~s/\.git$//;6379my@list= git_get_projects_list($filter);6380if(!@list) {6381 die_error(404,"No forks found");6382}63836384 git_header_html();6385 git_print_page_nav('','');6386 git_print_header_div('summary',"$projectforks");6387 git_project_list_body(\@list,$order);6388 git_footer_html();6389}63906391sub git_project_index {6392my@projects= git_get_projects_list($project_filter,$strict_export);6393if(!@projects) {6394 die_error(404,"No projects found");6395}63966397print$cgi->header(6398-type =>'text/plain',6399-charset =>'utf-8',6400-content_disposition =>'inline; filename="index.aux"');64016402foreachmy$pr(@projects) {6403if(!exists$pr->{'owner'}) {6404$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");6405}64066407my($path,$owner) = ($pr->{'path'},$pr->{'owner'});6408# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '6409$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6410$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6411$path=~s/ /\+/g;6412$owner=~s/ /\+/g;64136414print"$path$owner\n";6415}6416}64176418sub git_summary {6419my$descr= git_get_project_description($project) ||"none";6420my%co= parse_commit("HEAD");6421my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();6422my$head=$co{'id'};6423my$remote_heads= gitweb_check_feature('remote_heads');64246425my$owner= git_get_project_owner($project);64266427my$refs= git_get_references();6428# These get_*_list functions return one more to allow us to see if6429# there are more ...6430my@taglist= git_get_tags_list(16);6431my@headlist= git_get_heads_list(16);6432my%remotedata=$remote_heads? git_get_remotes_list() : ();6433my@forklist;6434my$check_forks= gitweb_check_feature('forks');64356436if($check_forks) {6437# find forks of a project6438my$filter=$project;6439$filter=~s/\.git$//;6440@forklist= git_get_projects_list($filter);6441# filter out forks of forks6442@forklist= filter_forks_from_projects_list(\@forklist)6443if(@forklist);6444}64456446 git_header_html();6447 git_print_page_nav('summary','',$head);64486449print"<div class=\"title\"> </div>\n";6450print"<table class=\"projects_list\">\n".6451"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n";6452unless($omit_owner) {6453print"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";6454}6455if(defined$cd{'rfc2822'}) {6456print"<tr id=\"metadata_lchange\"><td>last change</td>".6457"<td>".format_timestamp_html(\%cd)."</td></tr>\n";6458}64596460# use per project git URL list in $projectroot/$project/cloneurl6461# or make project git URL from git base URL and project name6462my$url_tag="URL";6463my@url_list= git_get_project_url_list($project);6464@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;6465foreachmy$git_url(@url_list) {6466next unless$git_url;6467print format_repo_url($url_tag,$git_url);6468$url_tag="";6469}64706471# Tag cloud6472my$show_ctags= gitweb_check_feature('ctags');6473if($show_ctags) {6474my$ctags= git_get_project_ctags($project);6475if(%$ctags) {6476# without ability to add tags, don't show if there are none6477my$cloud= git_populate_project_tagcloud($ctags);6478print"<tr id=\"metadata_ctags\">".6479"<td>content tags</td>".6480"<td>".git_show_project_tagcloud($cloud,48)."</td>".6481"</tr>\n";6482}6483}64846485print"</table>\n";64866487# If XSS prevention is on, we don't include README.html.6488# TODO: Allow a readme in some safe format.6489if(!$prevent_xss&& -s "$projectroot/$project/README.html") {6490print"<div class=\"title\">readme</div>\n".6491"<div class=\"readme\">\n";6492 insert_file("$projectroot/$project/README.html");6493print"\n</div>\n";# class="readme"6494}64956496# we need to request one more than 16 (0..15) to check if6497# those 16 are all6498my@commitlist=$head? parse_commits($head,17) : ();6499if(@commitlist) {6500 git_print_header_div('shortlog');6501 git_shortlog_body(\@commitlist,0,15,$refs,6502$#commitlist<=15?undef:6503$cgi->a({-href => href(action=>"shortlog")},"..."));6504}65056506if(@taglist) {6507 git_print_header_div('tags');6508 git_tags_body(\@taglist,0,15,6509$#taglist<=15?undef:6510$cgi->a({-href => href(action=>"tags")},"..."));6511}65126513if(@headlist) {6514 git_print_header_div('heads');6515 git_heads_body(\@headlist,$head,0,15,6516$#headlist<=15?undef:6517$cgi->a({-href => href(action=>"heads")},"..."));6518}65196520if(%remotedata) {6521 git_print_header_div('remotes');6522 git_remotes_body(\%remotedata,15,$head);6523}65246525if(@forklist) {6526 git_print_header_div('forks');6527 git_project_list_body(\@forklist,'age',0,15,6528$#forklist<=15?undef:6529$cgi->a({-href => href(action=>"forks")},"..."),6530'no_header');6531}65326533 git_footer_html();6534}65356536sub git_tag {6537my%tag= parse_tag($hash);65386539if(!%tag) {6540 die_error(404,"Unknown tag object");6541}65426543my$head= git_get_head_hash($project);6544 git_header_html();6545 git_print_page_nav('','',$head,undef,$head);6546 git_print_header_div('commit', esc_html($tag{'name'}),$hash);6547print"<div class=\"title_text\">\n".6548"<table class=\"object_header\">\n".6549"<tr>\n".6550"<td>object</td>\n".6551"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6552$tag{'object'}) ."</td>\n".6553"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6554$tag{'type'}) ."</td>\n".6555"</tr>\n";6556if(defined($tag{'author'})) {6557 git_print_authorship_rows(\%tag,'author');6558}6559print"</table>\n\n".6560"</div>\n";6561print"<div class=\"page_body\">";6562my$comment=$tag{'comment'};6563foreachmy$line(@$comment) {6564chomp$line;6565print esc_html($line, -nbsp=>1) ."<br/>\n";6566}6567print"</div>\n";6568 git_footer_html();6569}65706571sub git_blame_common {6572my$format=shift||'porcelain';6573if($formateq'porcelain'&&$input_params{'javascript'}) {6574$format='incremental';6575$action='blame_incremental';# for page title etc6576}65776578# permissions6579 gitweb_check_feature('blame')6580or die_error(403,"Blame view not allowed");65816582# error checking6583 die_error(400,"No file name given")unless$file_name;6584$hash_base||= git_get_head_hash($project);6585 die_error(404,"Couldn't find base commit")unless$hash_base;6586my%co= parse_commit($hash_base)6587or die_error(404,"Commit not found");6588my$ftype="blob";6589if(!defined$hash) {6590$hash= git_get_hash_by_path($hash_base,$file_name,"blob")6591or die_error(404,"Error looking up file");6592}else{6593$ftype= git_get_type($hash);6594if($ftype!~"blob") {6595 die_error(400,"Object is not a blob");6596}6597}65986599my$fd;6600if($formateq'incremental') {6601# get file contents (as base)6602open$fd,"-|", git_cmd(),'cat-file','blob',$hash6603or die_error(500,"Open git-cat-file failed");6604}elsif($formateq'data') {6605# run git-blame --incremental6606open$fd,"-|", git_cmd(),"blame","--incremental",6607$hash_base,"--",$file_name6608or die_error(500,"Open git-blame --incremental failed");6609}else{6610# run git-blame --porcelain6611open$fd,"-|", git_cmd(),"blame",'-p',6612$hash_base,'--',$file_name6613or die_error(500,"Open git-blame --porcelain failed");6614}66156616# incremental blame data returns early6617if($formateq'data') {6618print$cgi->header(6619-type=>"text/plain", -charset =>"utf-8",6620-status=>"200 OK");6621local$| =1;# output autoflush6622while(my$line= <$fd>) {6623print to_utf8($line);6624}6625close$fd6626or print"ERROR$!\n";66276628print'END';6629if(defined$t0&& gitweb_check_feature('timed')) {6630print' '.6631 tv_interval($t0, [ gettimeofday() ]).6632' '.$number_of_git_cmds;6633}6634print"\n";66356636return;6637}66386639# page header6640 git_header_html();6641my$formats_nav=6642$cgi->a({-href => href(action=>"blob", -replay=>1)},6643"blob") .6644" | ";6645if($formateq'incremental') {6646$formats_nav.=6647$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},6648"blame") ." (non-incremental)";6649}else{6650$formats_nav.=6651$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},6652"blame") ." (incremental)";6653}6654$formats_nav.=6655" | ".6656$cgi->a({-href => href(action=>"history", -replay=>1)},6657"history") .6658" | ".6659$cgi->a({-href => href(action=>$action, file_name=>$file_name)},6660"HEAD");6661 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6662 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6663 git_print_page_path($file_name,$ftype,$hash_base);66646665# page body6666if($formateq'incremental') {6667print"<noscript>\n<div class=\"error\"><center><b>\n".6668"This page requires JavaScript to run.\nUse ".6669$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},6670'this page').6671" instead.\n".6672"</b></center></div>\n</noscript>\n";66736674print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;6675}66766677print qq!<div class="page_body">\n!;6678print qq!<div id="progress_info">.../ ...</div>\n!6679if($formateq'incremental');6680print qq!<table id="blame_table"class="blame" width="100%">\n!.6681#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.6682 qq!<thead>\n!.6683 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.6684 qq!</thead>\n!.6685 qq!<tbody>\n!;66866687my@rev_color=qw(light dark);6688my$num_colors=scalar(@rev_color);6689my$current_color=0;66906691if($formateq'incremental') {6692my$color_class=$rev_color[$current_color];66936694#contents of a file6695my$linenr=0;6696 LINE:6697while(my$line= <$fd>) {6698chomp$line;6699$linenr++;67006701print qq!<tr id="l$linenr"class="$color_class">!.6702 qq!<td class="sha1"><a href=""> </a></td>!.6703 qq!<td class="linenr">!.6704 qq!<a class="linenr" href="">$linenr</a></td>!;6705print qq!<td class="pre">! . esc_html($line) ."</td>\n";6706print qq!</tr>\n!;6707}67086709}else{# porcelain, i.e. ordinary blame6710my%metainfo= ();# saves information about commits67116712# blame data6713 LINE:6714while(my$line= <$fd>) {6715chomp$line;6716# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]6717# no <lines in group> for subsequent lines in group of lines6718my($full_rev,$orig_lineno,$lineno,$group_size) =6719($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);6720if(!exists$metainfo{$full_rev}) {6721$metainfo{$full_rev} = {'nprevious'=>0};6722}6723my$meta=$metainfo{$full_rev};6724my$data;6725while($data= <$fd>) {6726chomp$data;6727last if($data=~s/^\t//);# contents of line6728if($data=~/^(\S+)(?: (.*))?$/) {6729$meta->{$1} =$2unlessexists$meta->{$1};6730}6731if($data=~/^previous /) {6732$meta->{'nprevious'}++;6733}6734}6735my$short_rev=substr($full_rev,0,8);6736my$author=$meta->{'author'};6737my%date=6738 parse_date($meta->{'author-time'},$meta->{'author-tz'});6739my$date=$date{'iso-tz'};6740if($group_size) {6741$current_color= ($current_color+1) %$num_colors;6742}6743my$tr_class=$rev_color[$current_color];6744$tr_class.=' boundary'if(exists$meta->{'boundary'});6745$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);6746$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);6747print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";6748if($group_size) {6749print"<td class=\"sha1\"";6750print" title=\"". esc_html($author) .",$date\"";6751print" rowspan=\"$group_size\""if($group_size>1);6752print">";6753print$cgi->a({-href => href(action=>"commit",6754 hash=>$full_rev,6755 file_name=>$file_name)},6756 esc_html($short_rev));6757if($group_size>=2) {6758my@author_initials= ($author=~/\b([[:upper:]])\B/g);6759if(@author_initials) {6760print"<br />".6761 esc_html(join('',@author_initials));6762# or join('.', ...)6763}6764}6765print"</td>\n";6766}6767# 'previous' <sha1 of parent commit> <filename at commit>6768if(exists$meta->{'previous'} &&6769$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {6770$meta->{'parent'} =$1;6771$meta->{'file_parent'} = unquote($2);6772}6773my$linenr_commit=6774exists($meta->{'parent'}) ?6775$meta->{'parent'} :$full_rev;6776my$linenr_filename=6777exists($meta->{'file_parent'}) ?6778$meta->{'file_parent'} : unquote($meta->{'filename'});6779my$blamed= href(action =>'blame',6780 file_name =>$linenr_filename,6781 hash_base =>$linenr_commit);6782print"<td class=\"linenr\">";6783print$cgi->a({ -href =>"$blamed#l$orig_lineno",6784-class=>"linenr"},6785 esc_html($lineno));6786print"</td>";6787print"<td class=\"pre\">". esc_html($data) ."</td>\n";6788print"</tr>\n";6789}# end while67906791}67926793# footer6794print"</tbody>\n".6795"</table>\n";# class="blame"6796print"</div>\n";# class="blame_body"6797close$fd6798or print"Reading blob failed\n";67996800 git_footer_html();6801}68026803sub git_blame {6804 git_blame_common();6805}68066807sub git_blame_incremental {6808 git_blame_common('incremental');6809}68106811sub git_blame_data {6812 git_blame_common('data');6813}68146815sub git_tags {6816my$head= git_get_head_hash($project);6817 git_header_html();6818 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6819 git_print_header_div('summary',$project);68206821my@tagslist= git_get_tags_list();6822if(@tagslist) {6823 git_tags_body(\@tagslist);6824}6825 git_footer_html();6826}68276828sub git_heads {6829my$head= git_get_head_hash($project);6830 git_header_html();6831 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6832 git_print_header_div('summary',$project);68336834my@headslist= git_get_heads_list();6835if(@headslist) {6836 git_heads_body(\@headslist,$head);6837}6838 git_footer_html();6839}68406841# used both for single remote view and for list of all the remotes6842sub git_remotes {6843 gitweb_check_feature('remote_heads')6844or die_error(403,"Remote heads view is disabled");68456846my$head= git_get_head_hash($project);6847my$remote=$input_params{'hash'};68486849my$remotedata= git_get_remotes_list($remote);6850 die_error(500,"Unable to get remote information")unlessdefined$remotedata;68516852unless(%$remotedata) {6853 die_error(404,defined$remote?6854"Remote$remotenot found":6855"No remotes found");6856}68576858 git_header_html(undef,undef, -action_extra =>$remote);6859 git_print_page_nav('','',$head,undef,$head,6860 format_ref_views($remote?'':'remotes'));68616862 fill_remote_heads($remotedata);6863if(defined$remote) {6864 git_print_header_div('remotes',"$remoteremote for$project");6865 git_remote_block($remote,$remotedata->{$remote},undef,$head);6866}else{6867 git_print_header_div('summary',"$projectremotes");6868 git_remotes_body($remotedata,undef,$head);6869}68706871 git_footer_html();6872}68736874sub git_blob_plain {6875my$type=shift;6876my$expires;68776878if(!defined$hash) {6879if(defined$file_name) {6880my$base=$hash_base|| git_get_head_hash($project);6881$hash= git_get_hash_by_path($base,$file_name,"blob")6882or die_error(404,"Cannot find file");6883}else{6884 die_error(400,"No file name defined");6885}6886}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6887# blobs defined by non-textual hash id's can be cached6888$expires="+1d";6889}68906891open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6892or die_error(500,"Open git-cat-file blob '$hash' failed");68936894# content-type (can include charset)6895$type= blob_contenttype($fd,$file_name,$type);68966897# "save as" filename, even when no $file_name is given6898my$save_as="$hash";6899if(defined$file_name) {6900$save_as=$file_name;6901}elsif($type=~m/^text\//) {6902$save_as.='.txt';6903}69046905# With XSS prevention on, blobs of all types except a few known safe6906# ones are served with "Content-Disposition: attachment" to make sure6907# they don't run in our security domain. For certain image types,6908# blob view writes an <img> tag referring to blob_plain view, and we6909# want to be sure not to break that by serving the image as an6910# attachment (though Firefox 3 doesn't seem to care).6911my$sandbox=$prevent_xss&&6912$type!~m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;69136914# serve text/* as text/plain6915if($prevent_xss&&6916($type=~m!^text/[a-z]+\b(.*)$!||6917($type=~m!^[a-z]+/[a-z]\+xml\b(.*)$!&& -T $fd))) {6918my$rest=$1;6919$rest=defined$rest?$rest:'';6920$type="text/plain$rest";6921}69226923print$cgi->header(6924-type =>$type,6925-expires =>$expires,6926-content_disposition =>6927($sandbox?'attachment':'inline')6928.'; filename="'.$save_as.'"');6929local$/=undef;6930binmode STDOUT,':raw';6931print<$fd>;6932binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6933close$fd;6934}69356936sub git_blob {6937my$expires;69386939if(!defined$hash) {6940if(defined$file_name) {6941my$base=$hash_base|| git_get_head_hash($project);6942$hash= git_get_hash_by_path($base,$file_name,"blob")6943or die_error(404,"Cannot find file");6944}else{6945 die_error(400,"No file name defined");6946}6947}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6948# blobs defined by non-textual hash id's can be cached6949$expires="+1d";6950}69516952my$have_blame= gitweb_check_feature('blame');6953open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6954or die_error(500,"Couldn't cat$file_name,$hash");6955my$mimetype= blob_mimetype($fd,$file_name);6956# use 'blob_plain' (aka 'raw') view for files that cannot be displayed6957if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {6958close$fd;6959return git_blob_plain($mimetype);6960}6961# we can have blame only for text/* mimetype6962$have_blame&&= ($mimetype=~m!^text/!);69636964my$highlight= gitweb_check_feature('highlight');6965my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);6966$fd= run_highlighter($fd,$highlight,$syntax)6967if$syntax;69686969 git_header_html(undef,$expires);6970my$formats_nav='';6971if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6972if(defined$file_name) {6973if($have_blame) {6974$formats_nav.=6975$cgi->a({-href => href(action=>"blame", -replay=>1)},6976"blame") .6977" | ";6978}6979$formats_nav.=6980$cgi->a({-href => href(action=>"history", -replay=>1)},6981"history") .6982" | ".6983$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6984"raw") .6985" | ".6986$cgi->a({-href => href(action=>"blob",6987 hash_base=>"HEAD", file_name=>$file_name)},6988"HEAD");6989}else{6990$formats_nav.=6991$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6992"raw");6993}6994 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6995 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6996}else{6997print"<div class=\"page_nav\">\n".6998"<br/><br/></div>\n".6999"<div class=\"title\">".esc_html($hash)."</div>\n";7000}7001 git_print_page_path($file_name,"blob",$hash_base);7002print"<div class=\"page_body\">\n";7003if($mimetype=~m!^image/!) {7004print qq!<img type="!.esc_attr($mimetype).qq!"!;7005if($file_name) {7006print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;7007}7008print qq! src="! .7009 href(action=>"blob_plain", hash=>$hash,7010 hash_base=>$hash_base, file_name=>$file_name) .7011 qq!"/>\n!;7012}else{7013my$nr;7014while(my$line= <$fd>) {7015chomp$line;7016$nr++;7017$line= untabify($line);7018printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,7019$nr, esc_attr(href(-replay =>1)),$nr,$nr,7020$syntax? sanitize($line) : esc_html($line, -nbsp=>1);7021}7022}7023close$fd7024or print"Reading blob failed.\n";7025print"</div>";7026 git_footer_html();7027}70287029sub git_tree {7030if(!defined$hash_base) {7031$hash_base="HEAD";7032}7033if(!defined$hash) {7034if(defined$file_name) {7035$hash= git_get_hash_by_path($hash_base,$file_name,"tree");7036}else{7037$hash=$hash_base;7038}7039}7040 die_error(404,"No such tree")unlessdefined($hash);70417042my$show_sizes= gitweb_check_feature('show-sizes');7043my$have_blame= gitweb_check_feature('blame');70447045my@entries= ();7046{7047local$/="\0";7048open my$fd,"-|", git_cmd(),"ls-tree",'-z',7049($show_sizes?'-l': ()),@extra_options,$hash7050or die_error(500,"Open git-ls-tree failed");7051@entries=map{chomp;$_} <$fd>;7052close$fd7053or die_error(404,"Reading tree failed");7054}70557056my$refs= git_get_references();7057my$ref= format_ref_marker($refs,$hash_base);7058 git_header_html();7059my$basedir='';7060if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7061my@views_nav= ();7062if(defined$file_name) {7063push@views_nav,7064$cgi->a({-href => href(action=>"history", -replay=>1)},7065"history"),7066$cgi->a({-href => href(action=>"tree",7067 hash_base=>"HEAD", file_name=>$file_name)},7068"HEAD"),7069}7070my$snapshot_links= format_snapshot_links($hash);7071if(defined$snapshot_links) {7072# FIXME: Should be available when we have no hash base as well.7073push@views_nav,$snapshot_links;7074}7075 git_print_page_nav('tree','',$hash_base,undef,undef,7076join(' | ',@views_nav));7077 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);7078}else{7079undef$hash_base;7080print"<div class=\"page_nav\">\n";7081print"<br/><br/></div>\n";7082print"<div class=\"title\">".esc_html($hash)."</div>\n";7083}7084if(defined$file_name) {7085$basedir=$file_name;7086if($basedirne''&&substr($basedir, -1)ne'/') {7087$basedir.='/';7088}7089 git_print_page_path($file_name,'tree',$hash_base);7090}7091print"<div class=\"page_body\">\n";7092print"<table class=\"tree\">\n";7093my$alternate=1;7094# '..' (top directory) link if possible7095if(defined$hash_base&&7096defined$file_name&&$file_name=~m![^/]+$!) {7097if($alternate) {7098print"<tr class=\"dark\">\n";7099}else{7100print"<tr class=\"light\">\n";7101}7102$alternate^=1;71037104my$up=$file_name;7105$up=~s!/?[^/]+$!!;7106undef$upunless$up;7107# based on git_print_tree_entry7108print'<td class="mode">'. mode_str('040000') ."</td>\n";7109print'<td class="size"> </td>'."\n"if$show_sizes;7110print'<td class="list">';7111print$cgi->a({-href => href(action=>"tree",7112 hash_base=>$hash_base,7113 file_name=>$up)},7114"..");7115print"</td>\n";7116print"<td class=\"link\"></td>\n";71177118print"</tr>\n";7119}7120foreachmy$line(@entries) {7121my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);71227123if($alternate) {7124print"<tr class=\"dark\">\n";7125}else{7126print"<tr class=\"light\">\n";7127}7128$alternate^=1;71297130 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);71317132print"</tr>\n";7133}7134print"</table>\n".7135"</div>";7136 git_footer_html();7137}71387139sub snapshot_name {7140my($project,$hash) =@_;71417142# path/to/project.git -> project7143# path/to/project/.git -> project7144my$name= to_utf8($project);7145$name=~ s,([^/])/*\.git$,$1,;7146$name= basename($name);7147# sanitize name7148$name=~s/[[:cntrl:]]/?/g;71497150my$ver=$hash;7151if($hash=~/^[0-9a-fA-F]+$/) {7152# shorten SHA-1 hash7153my$full_hash= git_get_full_hash($project,$hash);7154if($full_hash=~/^$hash/&&length($hash) >7) {7155$ver= git_get_short_hash($project,$hash);7156}7157}elsif($hash=~m!^refs/tags/(.*)$!) {7158# tags don't need shortened SHA-1 hash7159$ver=$1;7160}else{7161# branches and other need shortened SHA-1 hash7162if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {7163$ver=$1;7164}7165$ver.='-'. git_get_short_hash($project,$hash);7166}7167# in case of hierarchical branch names7168$ver=~s!/!.!g;71697170# name = project-version_string7171$name="$name-$ver";71727173returnwantarray? ($name,$name) :$name;7174}71757176sub exit_if_unmodified_since {7177my($latest_epoch) =@_;7178our$cgi;71797180my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7181if(defined$if_modified) {7182my$since;7183if(eval{require HTTP::Date;1; }) {7184$since= HTTP::Date::str2time($if_modified);7185}elsif(eval{require Time::ParseDate;1; }) {7186$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7187}7188if(defined$since&&$latest_epoch<=$since) {7189my%latest_date= parse_date($latest_epoch);7190print$cgi->header(7191-last_modified =>$latest_date{'rfc2822'},7192-status =>'304 Not Modified');7193goto DONE_GITWEB;7194}7195}7196}71977198sub git_snapshot {7199my$format=$input_params{'snapshot_format'};7200if(!@snapshot_fmts) {7201 die_error(403,"Snapshots not allowed");7202}7203# default to first supported snapshot format7204$format||=$snapshot_fmts[0];7205if($format!~m/^[a-z0-9]+$/) {7206 die_error(400,"Invalid snapshot format parameter");7207}elsif(!exists($known_snapshot_formats{$format})) {7208 die_error(400,"Unknown snapshot format");7209}elsif($known_snapshot_formats{$format}{'disabled'}) {7210 die_error(403,"Snapshot format not allowed");7211}elsif(!grep($_eq$format,@snapshot_fmts)) {7212 die_error(403,"Unsupported snapshot format");7213}72147215my$type= git_get_type("$hash^{}");7216if(!$type) {7217 die_error(404,'Object does not exist');7218}elsif($typeeq'blob') {7219 die_error(400,'Object is not a tree-ish');7220}72217222my($name,$prefix) = snapshot_name($project,$hash);7223my$filename="$name$known_snapshot_formats{$format}{'suffix'}";72247225my%co= parse_commit($hash);7226 exit_if_unmodified_since($co{'committer_epoch'})if%co;72277228my$cmd= quote_command(7229 git_cmd(),'archive',7230"--format=$known_snapshot_formats{$format}{'format'}",7231"--prefix=$prefix/",$hash);7232if(exists$known_snapshot_formats{$format}{'compressor'}) {7233$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});7234}72357236$filename=~s/(["\\])/\\$1/g;7237my%latest_date;7238if(%co) {7239%latest_date= parse_date($co{'committer_epoch'},$co{'committer_tz'});7240}72417242print$cgi->header(7243-type =>$known_snapshot_formats{$format}{'type'},7244-content_disposition =>'inline; filename="'.$filename.'"',7245%co? (-last_modified =>$latest_date{'rfc2822'}) : (),7246-status =>'200 OK');72477248open my$fd,"-|",$cmd7249or die_error(500,"Execute git-archive failed");7250binmode STDOUT,':raw';7251print<$fd>;7252binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi7253close$fd;7254}72557256sub git_log_generic {7257my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;72587259my$head= git_get_head_hash($project);7260if(!defined$base) {7261$base=$head;7262}7263if(!defined$page) {7264$page=0;7265}7266my$refs= git_get_references();72677268my$commit_hash=$base;7269if(defined$parent) {7270$commit_hash="$parent..$base";7271}7272my@commitlist=7273 parse_commits($commit_hash,101, (100*$page),7274defined$file_name? ($file_name,"--full-history") : ());72757276my$ftype;7277if(!defined$file_hash&&defined$file_name) {7278# some commits could have deleted file in question,7279# and not have it in tree, but one of them has to have it7280for(my$i=0;$i<@commitlist;$i++) {7281$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);7282last ifdefined$file_hash;7283}7284}7285if(defined$file_hash) {7286$ftype= git_get_type($file_hash);7287}7288if(defined$file_name&& !defined$ftype) {7289 die_error(500,"Unknown type of object");7290}7291my%co;7292if(defined$file_name) {7293%co= parse_commit($base)7294or die_error(404,"Unknown commit object");7295}729672977298my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);7299my$next_link='';7300if($#commitlist>=100) {7301$next_link=7302$cgi->a({-href => href(-replay=>1, page=>$page+1),7303-accesskey =>"n", -title =>"Alt-n"},"next");7304}7305my$patch_max= gitweb_get_feature('patches');7306if($patch_max&& !defined$file_name) {7307if($patch_max<0||@commitlist<=$patch_max) {7308$paging_nav.=" ⋅ ".7309$cgi->a({-href => href(action=>"patches", -replay=>1)},7310"patches");7311}7312}73137314 git_header_html();7315 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);7316if(defined$file_name) {7317 git_print_header_div('commit', esc_html($co{'title'}),$base);7318}else{7319 git_print_header_div('summary',$project)7320}7321 git_print_page_path($file_name,$ftype,$hash_base)7322if(defined$file_name);73237324$body_subr->(\@commitlist,0,99,$refs,$next_link,7325$file_name,$file_hash,$ftype);73267327 git_footer_html();7328}73297330sub git_log {7331 git_log_generic('log', \&git_log_body,7332$hash,$hash_parent);7333}73347335sub git_commit {7336$hash||=$hash_base||"HEAD";7337my%co= parse_commit($hash)7338or die_error(404,"Unknown commit object");73397340my$parent=$co{'parent'};7341my$parents=$co{'parents'};# listref73427343# we need to prepare $formats_nav before any parameter munging7344my$formats_nav;7345if(!defined$parent) {7346# --root commitdiff7347$formats_nav.='(initial)';7348}elsif(@$parents==1) {7349# single parent commit7350$formats_nav.=7351'(parent: '.7352$cgi->a({-href => href(action=>"commit",7353 hash=>$parent)},7354 esc_html(substr($parent,0,7))) .7355')';7356}else{7357# merge commit7358$formats_nav.=7359'(merge: '.7360join(' ',map{7361$cgi->a({-href => href(action=>"commit",7362 hash=>$_)},7363 esc_html(substr($_,0,7)));7364}@$parents) .7365')';7366}7367if(gitweb_check_feature('patches') &&@$parents<=1) {7368$formats_nav.=" | ".7369$cgi->a({-href => href(action=>"patch", -replay=>1)},7370"patch");7371}73727373if(!defined$parent) {7374$parent="--root";7375}7376my@difftree;7377open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",7378@diff_opts,7379(@$parents<=1?$parent:'-c'),7380$hash,"--"7381or die_error(500,"Open git-diff-tree failed");7382@difftree=map{chomp;$_} <$fd>;7383close$fdor die_error(404,"Reading git-diff-tree failed");73847385# non-textual hash id's can be cached7386my$expires;7387if($hash=~m/^[0-9a-fA-F]{40}$/) {7388$expires="+1d";7389}7390my$refs= git_get_references();7391my$ref= format_ref_marker($refs,$co{'id'});73927393 git_header_html(undef,$expires);7394 git_print_page_nav('commit','',7395$hash,$co{'tree'},$hash,7396$formats_nav);73977398if(defined$co{'parent'}) {7399 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);7400}else{7401 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);7402}7403print"<div class=\"title_text\">\n".7404"<table class=\"object_header\">\n";7405 git_print_authorship_rows(\%co);7406print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";7407print"<tr>".7408"<td>tree</td>".7409"<td class=\"sha1\">".7410$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),7411class=>"list"},$co{'tree'}) .7412"</td>".7413"<td class=\"link\">".7414$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},7415"tree");7416my$snapshot_links= format_snapshot_links($hash);7417if(defined$snapshot_links) {7418print" | ".$snapshot_links;7419}7420print"</td>".7421"</tr>\n";74227423foreachmy$par(@$parents) {7424print"<tr>".7425"<td>parent</td>".7426"<td class=\"sha1\">".7427$cgi->a({-href => href(action=>"commit", hash=>$par),7428class=>"list"},$par) .7429"</td>".7430"<td class=\"link\">".7431$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .7432" | ".7433$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .7434"</td>".7435"</tr>\n";7436}7437print"</table>".7438"</div>\n";74397440print"<div class=\"page_body\">\n";7441 git_print_log($co{'comment'});7442print"</div>\n";74437444 git_difftree_body(\@difftree,$hash,@$parents);74457446 git_footer_html();7447}74487449sub git_object {7450# object is defined by:7451# - hash or hash_base alone7452# - hash_base and file_name7453my$type;74547455# - hash or hash_base alone7456if($hash|| ($hash_base&& !defined$file_name)) {7457my$object_id=$hash||$hash_base;74587459open my$fd,"-|", quote_command(7460 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'7461or die_error(404,"Object does not exist");7462$type= <$fd>;7463chomp$type;7464close$fd7465or die_error(404,"Object does not exist");74667467# - hash_base and file_name7468}elsif($hash_base&&defined$file_name) {7469$file_name=~ s,/+$,,;74707471system(git_cmd(),"cat-file",'-e',$hash_base) ==07472or die_error(404,"Base object does not exist");74737474# here errors should not hapen7475open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name7476or die_error(500,"Open git-ls-tree failed");7477my$line= <$fd>;7478close$fd;74797480#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'7481unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {7482 die_error(404,"File or directory for given base does not exist");7483}7484$type=$2;7485$hash=$3;7486}else{7487 die_error(400,"Not enough information to find object");7488}74897490print$cgi->redirect(-uri => href(action=>$type, -full=>1,7491 hash=>$hash, hash_base=>$hash_base,7492 file_name=>$file_name),7493-status =>'302 Found');7494}74957496sub git_blobdiff {7497my$format=shift||'html';7498my$diff_style=$input_params{'diff_style'} ||'inline';74997500my$fd;7501my@difftree;7502my%diffinfo;7503my$expires;75047505# preparing $fd and %diffinfo for git_patchset_body7506# new style URI7507if(defined$hash_base&&defined$hash_parent_base) {7508if(defined$file_name) {7509# read raw output7510open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7511$hash_parent_base,$hash_base,7512"--", (defined$file_parent?$file_parent: ()),$file_name7513or die_error(500,"Open git-diff-tree failed");7514@difftree=map{chomp;$_} <$fd>;7515close$fd7516or die_error(404,"Reading git-diff-tree failed");7517@difftree7518or die_error(404,"Blob diff not found");75197520}elsif(defined$hash&&7521$hash=~/[0-9a-fA-F]{40}/) {7522# try to find filename from $hash75237524# read filtered raw output7525open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7526$hash_parent_base,$hash_base,"--"7527or die_error(500,"Open git-diff-tree failed");7528@difftree=7529# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'7530# $hash == to_id7531grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}7532map{chomp;$_} <$fd>;7533close$fd7534or die_error(404,"Reading git-diff-tree failed");7535@difftree7536or die_error(404,"Blob diff not found");75377538}else{7539 die_error(400,"Missing one of the blob diff parameters");7540}75417542if(@difftree>1) {7543 die_error(400,"Ambiguous blob diff specification");7544}75457546%diffinfo= parse_difftree_raw_line($difftree[0]);7547$file_parent||=$diffinfo{'from_file'} ||$file_name;7548$file_name||=$diffinfo{'to_file'};75497550$hash_parent||=$diffinfo{'from_id'};7551$hash||=$diffinfo{'to_id'};75527553# non-textual hash id's can be cached7554if($hash_base=~m/^[0-9a-fA-F]{40}$/&&7555$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {7556$expires='+1d';7557}75587559# open patch output7560open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7561'-p', ($formateq'html'?"--full-index": ()),7562$hash_parent_base,$hash_base,7563"--", (defined$file_parent?$file_parent: ()),$file_name7564or die_error(500,"Open git-diff-tree failed");7565}75667567# old/legacy style URI -- not generated anymore since 1.4.3.7568if(!%diffinfo) {7569 die_error('404 Not Found',"Missing one of the blob diff parameters")7570}75717572# header7573if($formateq'html') {7574my$formats_nav=7575$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},7576"raw");7577$formats_nav.= diff_style_nav($diff_style);7578 git_header_html(undef,$expires);7579if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7580 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7581 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7582}else{7583print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";7584print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";7585}7586if(defined$file_name) {7587 git_print_page_path($file_name,"blob",$hash_base);7588}else{7589print"<div class=\"page_path\"></div>\n";7590}75917592}elsif($formateq'plain') {7593print$cgi->header(7594-type =>'text/plain',7595-charset =>'utf-8',7596-expires =>$expires,7597-content_disposition =>'inline; filename="'."$file_name".'.patch"');75987599print"X-Git-Url: ".$cgi->self_url() ."\n\n";76007601}else{7602 die_error(400,"Unknown blobdiff format");7603}76047605# patch7606if($formateq'html') {7607print"<div class=\"page_body\">\n";76087609 git_patchset_body($fd,$diff_style,7610[ \%diffinfo],$hash_base,$hash_parent_base);7611close$fd;76127613print"</div>\n";# class="page_body"7614 git_footer_html();76157616}else{7617while(my$line= <$fd>) {7618$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;7619$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;76207621print$line;76227623last if$line=~m!^\+\+\+!;7624}7625local$/=undef;7626print<$fd>;7627close$fd;7628}7629}76307631sub git_blobdiff_plain {7632 git_blobdiff('plain');7633}76347635# assumes that it is added as later part of already existing navigation,7636# so it returns "| foo | bar" rather than just "foo | bar"7637sub diff_style_nav {7638my($diff_style,$is_combined) =@_;7639$diff_style||='inline';76407641return""if($is_combined);76427643my@styles= (inline =>'inline','sidebyside'=>'side by side');7644my%styles=@styles;7645@styles=7646@styles[map{$_*2}0..$#styles/2];76477648returnjoin'',7649map{" | ".$_}7650map{7651$_eq$diff_style?$styles{$_} :7652$cgi->a({-href => href(-replay=>1, diff_style =>$_)},$styles{$_})7653}@styles;7654}76557656sub git_commitdiff {7657my%params=@_;7658my$format=$params{-format} ||'html';7659my$diff_style=$input_params{'diff_style'} ||'inline';76607661my($patch_max) = gitweb_get_feature('patches');7662if($formateq'patch') {7663 die_error(403,"Patch view not allowed")unless$patch_max;7664}76657666$hash||=$hash_base||"HEAD";7667my%co= parse_commit($hash)7668or die_error(404,"Unknown commit object");76697670# choose format for commitdiff for merge7671if(!defined$hash_parent&& @{$co{'parents'}} >1) {7672$hash_parent='--cc';7673}7674# we need to prepare $formats_nav before almost any parameter munging7675my$formats_nav;7676if($formateq'html') {7677$formats_nav=7678$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},7679"raw");7680if($patch_max&& @{$co{'parents'}} <=1) {7681$formats_nav.=" | ".7682$cgi->a({-href => href(action=>"patch", -replay=>1)},7683"patch");7684}7685$formats_nav.= diff_style_nav($diff_style, @{$co{'parents'}} >1);76867687if(defined$hash_parent&&7688$hash_parentne'-c'&&$hash_parentne'--cc') {7689# commitdiff with two commits given7690my$hash_parent_short=$hash_parent;7691if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {7692$hash_parent_short=substr($hash_parent,0,7);7693}7694$formats_nav.=7695' (from';7696for(my$i=0;$i< @{$co{'parents'}};$i++) {7697if($co{'parents'}[$i]eq$hash_parent) {7698$formats_nav.=' parent '. ($i+1);7699last;7700}7701}7702$formats_nav.=': '.7703$cgi->a({-href => href(-replay=>1,7704 hash=>$hash_parent, hash_base=>undef)},7705 esc_html($hash_parent_short)) .7706')';7707}elsif(!$co{'parent'}) {7708# --root commitdiff7709$formats_nav.=' (initial)';7710}elsif(scalar@{$co{'parents'}} ==1) {7711# single parent commit7712$formats_nav.=7713' (parent: '.7714$cgi->a({-href => href(-replay=>1,7715 hash=>$co{'parent'}, hash_base=>undef)},7716 esc_html(substr($co{'parent'},0,7))) .7717')';7718}else{7719# merge commit7720if($hash_parenteq'--cc') {7721$formats_nav.=' | '.7722$cgi->a({-href => href(-replay=>1,7723 hash=>$hash, hash_parent=>'-c')},7724'combined');7725}else{# $hash_parent eq '-c'7726$formats_nav.=' | '.7727$cgi->a({-href => href(-replay=>1,7728 hash=>$hash, hash_parent=>'--cc')},7729'compact');7730}7731$formats_nav.=7732' (merge: '.7733join(' ',map{7734$cgi->a({-href => href(-replay=>1,7735 hash=>$_, hash_base=>undef)},7736 esc_html(substr($_,0,7)));7737} @{$co{'parents'}} ) .7738')';7739}7740}77417742my$hash_parent_param=$hash_parent;7743if(!defined$hash_parent_param) {7744# --cc for multiple parents, --root for parentless7745$hash_parent_param=7746@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';7747}77487749# read commitdiff7750my$fd;7751my@difftree;7752if($formateq'html') {7753open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7754"--no-commit-id","--patch-with-raw","--full-index",7755$hash_parent_param,$hash,"--"7756or die_error(500,"Open git-diff-tree failed");77577758while(my$line= <$fd>) {7759chomp$line;7760# empty line ends raw part of diff-tree output7761last unless$line;7762push@difftree,scalar parse_difftree_raw_line($line);7763}77647765}elsif($formateq'plain') {7766open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7767'-p',$hash_parent_param,$hash,"--"7768or die_error(500,"Open git-diff-tree failed");7769}elsif($formateq'patch') {7770# For commit ranges, we limit the output to the number of7771# patches specified in the 'patches' feature.7772# For single commits, we limit the output to a single patch,7773# diverging from the git-format-patch default.7774my@commit_spec= ();7775if($hash_parent) {7776if($patch_max>0) {7777push@commit_spec,"-$patch_max";7778}7779push@commit_spec,'-n',"$hash_parent..$hash";7780}else{7781if($params{-single}) {7782push@commit_spec,'-1';7783}else{7784if($patch_max>0) {7785push@commit_spec,"-$patch_max";7786}7787push@commit_spec,"-n";7788}7789push@commit_spec,'--root',$hash;7790}7791open$fd,"-|", git_cmd(),"format-patch",@diff_opts,7792'--encoding=utf8','--stdout',@commit_spec7793or die_error(500,"Open git-format-patch failed");7794}else{7795 die_error(400,"Unknown commitdiff format");7796}77977798# non-textual hash id's can be cached7799my$expires;7800if($hash=~m/^[0-9a-fA-F]{40}$/) {7801$expires="+1d";7802}78037804# write commit message7805if($formateq'html') {7806my$refs= git_get_references();7807my$ref= format_ref_marker($refs,$co{'id'});78087809 git_header_html(undef,$expires);7810 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);7811 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);7812print"<div class=\"title_text\">\n".7813"<table class=\"object_header\">\n";7814 git_print_authorship_rows(\%co);7815print"</table>".7816"</div>\n";7817print"<div class=\"page_body\">\n";7818if(@{$co{'comment'}} >1) {7819print"<div class=\"log\">\n";7820 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);7821print"</div>\n";# class="log"7822}78237824}elsif($formateq'plain') {7825my$refs= git_get_references("tags");7826my$tagname= git_get_rev_name_tags($hash);7827my$filename= basename($project) ."-$hash.patch";78287829print$cgi->header(7830-type =>'text/plain',7831-charset =>'utf-8',7832-expires =>$expires,7833-content_disposition =>'inline; filename="'."$filename".'"');7834my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});7835print"From: ". to_utf8($co{'author'}) ."\n";7836print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";7837print"Subject: ". to_utf8($co{'title'}) ."\n";78387839print"X-Git-Tag:$tagname\n"if$tagname;7840print"X-Git-Url: ".$cgi->self_url() ."\n\n";78417842foreachmy$line(@{$co{'comment'}}) {7843print to_utf8($line) ."\n";7844}7845print"---\n\n";7846}elsif($formateq'patch') {7847my$filename= basename($project) ."-$hash.patch";78487849print$cgi->header(7850-type =>'text/plain',7851-charset =>'utf-8',7852-expires =>$expires,7853-content_disposition =>'inline; filename="'."$filename".'"');7854}78557856# write patch7857if($formateq'html') {7858my$use_parents= !defined$hash_parent||7859$hash_parenteq'-c'||$hash_parenteq'--cc';7860 git_difftree_body(\@difftree,$hash,7861$use_parents? @{$co{'parents'}} :$hash_parent);7862print"<br/>\n";78637864 git_patchset_body($fd,$diff_style,7865 \@difftree,$hash,7866$use_parents? @{$co{'parents'}} :$hash_parent);7867close$fd;7868print"</div>\n";# class="page_body"7869 git_footer_html();78707871}elsif($formateq'plain') {7872local$/=undef;7873print<$fd>;7874close$fd7875or print"Reading git-diff-tree failed\n";7876}elsif($formateq'patch') {7877local$/=undef;7878print<$fd>;7879close$fd7880or print"Reading git-format-patch failed\n";7881}7882}78837884sub git_commitdiff_plain {7885 git_commitdiff(-format =>'plain');7886}78877888# format-patch-style patches7889sub git_patch {7890 git_commitdiff(-format =>'patch', -single =>1);7891}78927893sub git_patches {7894 git_commitdiff(-format =>'patch');7895}78967897sub git_history {7898 git_log_generic('history', \&git_history_body,7899$hash_base,$hash_parent_base,7900$file_name,$hash);7901}79027903sub git_search {7904$searchtype||='commit';79057906# check if appropriate features are enabled7907 gitweb_check_feature('search')7908or die_error(403,"Search is disabled");7909if($searchtypeeq'pickaxe') {7910# pickaxe may take all resources of your box and run for several minutes7911# with every query - so decide by yourself how public you make this feature7912 gitweb_check_feature('pickaxe')7913or die_error(403,"Pickaxe search is disabled");7914}7915if($searchtypeeq'grep') {7916# grep search might be potentially CPU-intensive, too7917 gitweb_check_feature('grep')7918or die_error(403,"Grep search is disabled");7919}79207921if(!defined$searchtext) {7922 die_error(400,"Text field is empty");7923}7924if(!defined$hash) {7925$hash= git_get_head_hash($project);7926}7927my%co= parse_commit($hash);7928if(!%co) {7929 die_error(404,"Unknown commit object");7930}7931if(!defined$page) {7932$page=0;7933}79347935if($searchtypeeq'commit'||7936$searchtypeeq'author'||7937$searchtypeeq'committer') {7938 git_search_message(%co);7939}elsif($searchtypeeq'pickaxe') {7940 git_search_changes(%co);7941}elsif($searchtypeeq'grep') {7942 git_search_files(%co);7943}else{7944 die_error(400,"Unknown search type");7945}7946}79477948sub git_search_help {7949 git_header_html();7950 git_print_page_nav('','',$hash,$hash,$hash);7951print<<EOT;7952<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without7953regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,7954the pattern entered is recognized as the POSIX extended7955<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case7956insensitive).</p>7957<dl>7958<dt><b>commit</b></dt>7959<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>7960EOT7961my$have_grep= gitweb_check_feature('grep');7962if($have_grep) {7963print<<EOT;7964<dt><b>grep</b></dt>7965<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing7966 a different one) are searched for the given pattern. On large trees, this search can take7967a while and put some strain on the server, so please use it with some consideration. Note that7968due to git-grep peculiarity, currently if regexp mode is turned off, the matches are7969case-sensitive.</dd>7970EOT7971}7972print<<EOT;7973<dt><b>author</b></dt>7974<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>7975<dt><b>committer</b></dt>7976<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>7977EOT7978my$have_pickaxe= gitweb_check_feature('pickaxe');7979if($have_pickaxe) {7980print<<EOT;7981<dt><b>pickaxe</b></dt>7982<dd>All commits that caused the string to appear or disappear from any file (changes that7983added, removed or "modified" the string) will be listed. This search can take a while and7984takes a lot of strain on the server, so please use it wisely. Note that since you may be7985interested even in changes just changing the case as well, this search is case sensitive.</dd>7986EOT7987}7988print"</dl>\n";7989 git_footer_html();7990}79917992sub git_shortlog {7993 git_log_generic('shortlog', \&git_shortlog_body,7994$hash,$hash_parent);7995}79967997## ......................................................................7998## feeds (RSS, Atom; OPML)79998000sub git_feed {8001my$format=shift||'atom';8002my$have_blame= gitweb_check_feature('blame');80038004# Atom: http://www.atomenabled.org/developers/syndication/8005# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ8006if($formatne'rss'&&$formatne'atom') {8007 die_error(400,"Unknown web feed format");8008}80098010# log/feed of current (HEAD) branch, log of given branch, history of file/directory8011my$head=$hash||'HEAD';8012my@commitlist= parse_commits($head,150,0,$file_name);80138014my%latest_commit;8015my%latest_date;8016my$content_type="application/$format+xml";8017if(defined$cgi->http('HTTP_ACCEPT') &&8018$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {8019# browser (feed reader) prefers text/xml8020$content_type='text/xml';8021}8022if(defined($commitlist[0])) {8023%latest_commit= %{$commitlist[0]};8024my$latest_epoch=$latest_commit{'committer_epoch'};8025 exit_if_unmodified_since($latest_epoch);8026%latest_date= parse_date($latest_epoch,$latest_commit{'comitter_tz'});8027}8028print$cgi->header(8029-type =>$content_type,8030-charset =>'utf-8',8031%latest_date? (-last_modified =>$latest_date{'rfc2822'}) : (),8032-status =>'200 OK');80338034# Optimization: skip generating the body if client asks only8035# for Last-Modified date.8036return if($cgi->request_method()eq'HEAD');80378038# header variables8039my$title="$site_name-$project/$action";8040my$feed_type='log';8041if(defined$hash) {8042$title.=" - '$hash'";8043$feed_type='branch log';8044if(defined$file_name) {8045$title.=" ::$file_name";8046$feed_type='history';8047}8048}elsif(defined$file_name) {8049$title.=" -$file_name";8050$feed_type='history';8051}8052$title.="$feed_type";8053my$descr= git_get_project_description($project);8054if(defined$descr) {8055$descr= esc_html($descr);8056}else{8057$descr="$project".8058($formateq'rss'?'RSS':'Atom') .8059" feed";8060}8061my$owner= git_get_project_owner($project);8062$owner= esc_html($owner);80638064#header8065my$alt_url;8066if(defined$file_name) {8067$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);8068}elsif(defined$hash) {8069$alt_url= href(-full=>1, action=>"log", hash=>$hash);8070}else{8071$alt_url= href(-full=>1, action=>"summary");8072}8073print qq!<?xml version="1.0" encoding="utf-8"?>\n!;8074if($formateq'rss') {8075print<<XML;8076<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">8077<channel>8078XML8079print"<title>$title</title>\n".8080"<link>$alt_url</link>\n".8081"<description>$descr</description>\n".8082"<language>en</language>\n".8083# project owner is responsible for 'editorial' content8084"<managingEditor>$owner</managingEditor>\n";8085if(defined$logo||defined$favicon) {8086# prefer the logo to the favicon, since RSS8087# doesn't allow both8088my$img= esc_url($logo||$favicon);8089print"<image>\n".8090"<url>$img</url>\n".8091"<title>$title</title>\n".8092"<link>$alt_url</link>\n".8093"</image>\n";8094}8095if(%latest_date) {8096print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";8097print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";8098}8099print"<generator>gitweb v.$version/$git_version</generator>\n";8100}elsif($formateq'atom') {8101print<<XML;8102<feed xmlns="http://www.w3.org/2005/Atom">8103XML8104print"<title>$title</title>\n".8105"<subtitle>$descr</subtitle>\n".8106'<link rel="alternate" type="text/html" href="'.8107$alt_url.'" />'."\n".8108'<link rel="self" type="'.$content_type.'" href="'.8109$cgi->self_url() .'" />'."\n".8110"<id>". href(-full=>1) ."</id>\n".8111# use project owner for feed author8112"<author><name>$owner</name></author>\n";8113if(defined$favicon) {8114print"<icon>". esc_url($favicon) ."</icon>\n";8115}8116if(defined$logo) {8117# not twice as wide as tall: 72 x 27 pixels8118print"<logo>". esc_url($logo) ."</logo>\n";8119}8120if(!%latest_date) {8121# dummy date to keep the feed valid until commits trickle in:8122print"<updated>1970-01-01T00:00:00Z</updated>\n";8123}else{8124print"<updated>$latest_date{'iso-8601'}</updated>\n";8125}8126print"<generator version='$version/$git_version'>gitweb</generator>\n";8127}81288129# contents8130for(my$i=0;$i<=$#commitlist;$i++) {8131my%co= %{$commitlist[$i]};8132my$commit=$co{'id'};8133# we read 150, we always show 30 and the ones more recent than 48 hours8134if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {8135last;8136}8137my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});81388139# get list of changed files8140open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,8141$co{'parent'} ||"--root",8142$co{'id'},"--", (defined$file_name?$file_name: ())8143ornext;8144my@difftree=map{chomp;$_} <$fd>;8145close$fd8146ornext;81478148# print element (entry, item)8149my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);8150if($formateq'rss') {8151print"<item>\n".8152"<title>". esc_html($co{'title'}) ."</title>\n".8153"<author>". esc_html($co{'author'}) ."</author>\n".8154"<pubDate>$cd{'rfc2822'}</pubDate>\n".8155"<guid isPermaLink=\"true\">$co_url</guid>\n".8156"<link>$co_url</link>\n".8157"<description>". esc_html($co{'title'}) ."</description>\n".8158"<content:encoded>".8159"<![CDATA[\n";8160}elsif($formateq'atom') {8161print"<entry>\n".8162"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".8163"<updated>$cd{'iso-8601'}</updated>\n".8164"<author>\n".8165" <name>". esc_html($co{'author_name'}) ."</name>\n";8166if($co{'author_email'}) {8167print" <email>". esc_html($co{'author_email'}) ."</email>\n";8168}8169print"</author>\n".8170# use committer for contributor8171"<contributor>\n".8172" <name>". esc_html($co{'committer_name'}) ."</name>\n";8173if($co{'committer_email'}) {8174print" <email>". esc_html($co{'committer_email'}) ."</email>\n";8175}8176print"</contributor>\n".8177"<published>$cd{'iso-8601'}</published>\n".8178"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".8179"<id>$co_url</id>\n".8180"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".8181"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";8182}8183my$comment=$co{'comment'};8184print"<pre>\n";8185foreachmy$line(@$comment) {8186$line= esc_html($line);8187print"$line\n";8188}8189print"</pre><ul>\n";8190foreachmy$difftree_line(@difftree) {8191my%difftree= parse_difftree_raw_line($difftree_line);8192next if!$difftree{'from_id'};81938194my$file=$difftree{'file'} ||$difftree{'to_file'};81958196print"<li>".8197"[".8198$cgi->a({-href => href(-full=>1, action=>"blobdiff",8199 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},8200 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},8201 file_name=>$file, file_parent=>$difftree{'from_file'}),8202-title =>"diff"},'D');8203if($have_blame) {8204print$cgi->a({-href => href(-full=>1, action=>"blame",8205 file_name=>$file, hash_base=>$commit),8206-title =>"blame"},'B');8207}8208# if this is not a feed of a file history8209if(!defined$file_name||$file_namene$file) {8210print$cgi->a({-href => href(-full=>1, action=>"history",8211 file_name=>$file, hash=>$commit),8212-title =>"history"},'H');8213}8214$file= esc_path($file);8215print"] ".8216"$file</li>\n";8217}8218if($formateq'rss') {8219print"</ul>]]>\n".8220"</content:encoded>\n".8221"</item>\n";8222}elsif($formateq'atom') {8223print"</ul>\n</div>\n".8224"</content>\n".8225"</entry>\n";8226}8227}82288229# end of feed8230if($formateq'rss') {8231print"</channel>\n</rss>\n";8232}elsif($formateq'atom') {8233print"</feed>\n";8234}8235}82368237sub git_rss {8238 git_feed('rss');8239}82408241sub git_atom {8242 git_feed('atom');8243}82448245sub git_opml {8246my@list= git_get_projects_list($project_filter,$strict_export);8247if(!@list) {8248 die_error(404,"No projects found");8249}82508251print$cgi->header(8252-type =>'text/xml',8253-charset =>'utf-8',8254-content_disposition =>'inline; filename="opml.xml"');82558256my$title= esc_html($site_name);8257my$filter=" within subdirectory ";8258if(defined$project_filter) {8259$filter.= esc_html($project_filter);8260}else{8261$filter="";8262}8263print<<XML;8264<?xml version="1.0" encoding="utf-8"?>8265<opml version="1.0">8266<head>8267 <title>$titleOPML Export$filter</title>8268</head>8269<body>8270<outline text="git RSS feeds">8271XML82728273foreachmy$pr(@list) {8274my%proj=%$pr;8275my$head= git_get_head_hash($proj{'path'});8276if(!defined$head) {8277next;8278}8279$git_dir="$projectroot/$proj{'path'}";8280my%co= parse_commit($head);8281if(!%co) {8282next;8283}82848285my$path= esc_html(chop_str($proj{'path'},25,5));8286my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);8287my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);8288print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";8289}8290print<<XML;8291</outline>8292</body>8293</opml>8294XML8295}