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$signoff=0;4488my$empty=0;4489foreachmy$line(@$log) {4490if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {4491$signoff=1;4492$empty=0;4493if(!$opts{'-remove_signoff'}) {4494print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4495next;4496}else{4497# remove signoff lines4498next;4499}4500}else{4501$signoff=0;4502}45034504# print only one empty line4505# do not print empty line after signoff4506if($lineeq"") {4507next if($empty||$signoff);4508$empty=1;4509}else{4510$empty=0;4511}45124513print format_log_line_html($line) ."<br/>\n";4514}45154516if($opts{'-final_empty_line'}) {4517# end with single empty line4518print"<br/>\n"unless$empty;4519}4520}45214522# return link target (what link points to)4523sub git_get_link_target {4524my$hash=shift;4525my$link_target;45264527# read link4528open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4529orreturn;4530{4531local$/=undef;4532$link_target= <$fd>;4533}4534close$fd4535orreturn;45364537return$link_target;4538}45394540# given link target, and the directory (basedir) the link is in,4541# return target of link relative to top directory (top tree);4542# return undef if it is not possible (including absolute links).4543sub normalize_link_target {4544my($link_target,$basedir) =@_;45454546# absolute symlinks (beginning with '/') cannot be normalized4547return if(substr($link_target,0,1)eq'/');45484549# normalize link target to path from top (root) tree (dir)4550my$path;4551if($basedir) {4552$path=$basedir.'/'.$link_target;4553}else{4554# we are in top (root) tree (dir)4555$path=$link_target;4556}45574558# remove //, /./, and /../4559my@path_parts;4560foreachmy$part(split('/',$path)) {4561# discard '.' and ''4562next if(!$part||$parteq'.');4563# handle '..'4564if($parteq'..') {4565if(@path_parts) {4566pop@path_parts;4567}else{4568# link leads outside repository (outside top dir)4569return;4570}4571}else{4572push@path_parts,$part;4573}4574}4575$path=join('/',@path_parts);45764577return$path;4578}45794580# print tree entry (row of git_tree), but without encompassing <tr> element4581sub git_print_tree_entry {4582my($t,$basedir,$hash_base,$have_blame) =@_;45834584my%base_key= ();4585$base_key{'hash_base'} =$hash_baseifdefined$hash_base;45864587# The format of a table row is: mode list link. Where mode is4588# the mode of the entry, list is the name of the entry, an href,4589# and link is the action links of the entry.45904591print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4592if(exists$t->{'size'}) {4593print"<td class=\"size\">$t->{'size'}</td>\n";4594}4595if($t->{'type'}eq"blob") {4596print"<td class=\"list\">".4597$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4598 file_name=>"$basedir$t->{'name'}",%base_key),4599-class=>"list"}, esc_path($t->{'name'}));4600if(S_ISLNK(oct$t->{'mode'})) {4601my$link_target= git_get_link_target($t->{'hash'});4602if($link_target) {4603my$norm_target= normalize_link_target($link_target,$basedir);4604if(defined$norm_target) {4605print" -> ".4606$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4607 file_name=>$norm_target),4608-title =>$norm_target}, esc_path($link_target));4609}else{4610print" -> ". esc_path($link_target);4611}4612}4613}4614print"</td>\n";4615print"<td class=\"link\">";4616print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4617 file_name=>"$basedir$t->{'name'}",%base_key)},4618"blob");4619if($have_blame) {4620print" | ".4621$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4622 file_name=>"$basedir$t->{'name'}",%base_key)},4623"blame");4624}4625if(defined$hash_base) {4626print" | ".4627$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4628 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4629"history");4630}4631print" | ".4632$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4633 file_name=>"$basedir$t->{'name'}")},4634"raw");4635print"</td>\n";46364637}elsif($t->{'type'}eq"tree") {4638print"<td class=\"list\">";4639print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4640 file_name=>"$basedir$t->{'name'}",4641%base_key)},4642 esc_path($t->{'name'}));4643print"</td>\n";4644print"<td class=\"link\">";4645print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4646 file_name=>"$basedir$t->{'name'}",4647%base_key)},4648"tree");4649if(defined$hash_base) {4650print" | ".4651$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4652 file_name=>"$basedir$t->{'name'}")},4653"history");4654}4655print"</td>\n";4656}else{4657# unknown object: we can only present history for it4658# (this includes 'commit' object, i.e. submodule support)4659print"<td class=\"list\">".4660 esc_path($t->{'name'}) .4661"</td>\n";4662print"<td class=\"link\">";4663if(defined$hash_base) {4664print$cgi->a({-href => href(action=>"history",4665 hash_base=>$hash_base,4666 file_name=>"$basedir$t->{'name'}")},4667"history");4668}4669print"</td>\n";4670}4671}46724673## ......................................................................4674## functions printing large fragments of HTML46754676# get pre-image filenames for merge (combined) diff4677sub fill_from_file_info {4678my($diff,@parents) =@_;46794680$diff->{'from_file'} = [ ];4681$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4682for(my$i=0;$i<$diff->{'nparents'};$i++) {4683if($diff->{'status'}[$i]eq'R'||4684$diff->{'status'}[$i]eq'C') {4685$diff->{'from_file'}[$i] =4686 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4687}4688}46894690return$diff;4691}46924693# is current raw difftree line of file deletion4694sub is_deleted {4695my$diffinfo=shift;46964697return$diffinfo->{'to_id'}eq('0' x 40);4698}46994700# does patch correspond to [previous] difftree raw line4701# $diffinfo - hashref of parsed raw diff format4702# $patchinfo - hashref of parsed patch diff format4703# (the same keys as in $diffinfo)4704sub is_patch_split {4705my($diffinfo,$patchinfo) =@_;47064707returndefined$diffinfo&&defined$patchinfo4708&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4709}471047114712sub git_difftree_body {4713my($difftree,$hash,@parents) =@_;4714my($parent) =$parents[0];4715my$have_blame= gitweb_check_feature('blame');4716print"<div class=\"list_head\">\n";4717if($#{$difftree} >10) {4718print(($#{$difftree} +1) ." files changed:\n");4719}4720print"</div>\n";47214722print"<table class=\"".4723(@parents>1?"combined ":"") .4724"diff_tree\">\n";47254726# header only for combined diff in 'commitdiff' view4727my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4728if($has_header) {4729# table header4730print"<thead><tr>\n".4731"<th></th><th></th>\n";# filename, patchN link4732for(my$i=0;$i<@parents;$i++) {4733my$par=$parents[$i];4734print"<th>".4735$cgi->a({-href => href(action=>"commitdiff",4736 hash=>$hash, hash_parent=>$par),4737-title =>'commitdiff to parent number '.4738($i+1) .': '.substr($par,0,7)},4739$i+1) .4740" </th>\n";4741}4742print"</tr></thead>\n<tbody>\n";4743}47444745my$alternate=1;4746my$patchno=0;4747foreachmy$line(@{$difftree}) {4748my$diff= parsed_difftree_line($line);47494750if($alternate) {4751print"<tr class=\"dark\">\n";4752}else{4753print"<tr class=\"light\">\n";4754}4755$alternate^=1;47564757if(exists$diff->{'nparents'}) {# combined diff47584759 fill_from_file_info($diff,@parents)4760unlessexists$diff->{'from_file'};47614762if(!is_deleted($diff)) {4763# file exists in the result (child) commit4764print"<td>".4765$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4766 file_name=>$diff->{'to_file'},4767 hash_base=>$hash),4768-class=>"list"}, esc_path($diff->{'to_file'})) .4769"</td>\n";4770}else{4771print"<td>".4772 esc_path($diff->{'to_file'}) .4773"</td>\n";4774}47754776if($actioneq'commitdiff') {4777# link to patch4778$patchno++;4779print"<td class=\"link\">".4780$cgi->a({-href => href(-anchor=>"patch$patchno")},4781"patch") .4782" | ".4783"</td>\n";4784}47854786my$has_history=0;4787my$not_deleted=0;4788for(my$i=0;$i<$diff->{'nparents'};$i++) {4789my$hash_parent=$parents[$i];4790my$from_hash=$diff->{'from_id'}[$i];4791my$from_path=$diff->{'from_file'}[$i];4792my$status=$diff->{'status'}[$i];47934794$has_history||= ($statusne'A');4795$not_deleted||= ($statusne'D');47964797if($statuseq'A') {4798print"<td class=\"link\"align=\"right\"> | </td>\n";4799}elsif($statuseq'D') {4800print"<td class=\"link\">".4801$cgi->a({-href => href(action=>"blob",4802 hash_base=>$hash,4803 hash=>$from_hash,4804 file_name=>$from_path)},4805"blob". ($i+1)) .4806" | </td>\n";4807}else{4808if($diff->{'to_id'}eq$from_hash) {4809print"<td class=\"link nochange\">";4810}else{4811print"<td class=\"link\">";4812}4813print$cgi->a({-href => href(action=>"blobdiff",4814 hash=>$diff->{'to_id'},4815 hash_parent=>$from_hash,4816 hash_base=>$hash,4817 hash_parent_base=>$hash_parent,4818 file_name=>$diff->{'to_file'},4819 file_parent=>$from_path)},4820"diff". ($i+1)) .4821" | </td>\n";4822}4823}48244825print"<td class=\"link\">";4826if($not_deleted) {4827print$cgi->a({-href => href(action=>"blob",4828 hash=>$diff->{'to_id'},4829 file_name=>$diff->{'to_file'},4830 hash_base=>$hash)},4831"blob");4832print" | "if($has_history);4833}4834if($has_history) {4835print$cgi->a({-href => href(action=>"history",4836 file_name=>$diff->{'to_file'},4837 hash_base=>$hash)},4838"history");4839}4840print"</td>\n";48414842print"</tr>\n";4843next;# instead of 'else' clause, to avoid extra indent4844}4845# else ordinary diff48464847my($to_mode_oct,$to_mode_str,$to_file_type);4848my($from_mode_oct,$from_mode_str,$from_file_type);4849if($diff->{'to_mode'}ne('0' x 6)) {4850$to_mode_oct=oct$diff->{'to_mode'};4851if(S_ISREG($to_mode_oct)) {# only for regular file4852$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4853}4854$to_file_type= file_type($diff->{'to_mode'});4855}4856if($diff->{'from_mode'}ne('0' x 6)) {4857$from_mode_oct=oct$diff->{'from_mode'};4858if(S_ISREG($from_mode_oct)) {# only for regular file4859$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4860}4861$from_file_type= file_type($diff->{'from_mode'});4862}48634864if($diff->{'status'}eq"A") {# created4865my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4866$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4867$mode_chng.="]</span>";4868print"<td>";4869print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4870 hash_base=>$hash, file_name=>$diff->{'file'}),4871-class=>"list"}, esc_path($diff->{'file'}));4872print"</td>\n";4873print"<td>$mode_chng</td>\n";4874print"<td class=\"link\">";4875if($actioneq'commitdiff') {4876# link to patch4877$patchno++;4878print$cgi->a({-href => href(-anchor=>"patch$patchno")},4879"patch") .4880" | ";4881}4882print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4883 hash_base=>$hash, file_name=>$diff->{'file'})},4884"blob");4885print"</td>\n";48864887}elsif($diff->{'status'}eq"D") {# deleted4888my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4889print"<td>";4890print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4891 hash_base=>$parent, file_name=>$diff->{'file'}),4892-class=>"list"}, esc_path($diff->{'file'}));4893print"</td>\n";4894print"<td>$mode_chng</td>\n";4895print"<td class=\"link\">";4896if($actioneq'commitdiff') {4897# link to patch4898$patchno++;4899print$cgi->a({-href => href(-anchor=>"patch$patchno")},4900"patch") .4901" | ";4902}4903print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4904 hash_base=>$parent, file_name=>$diff->{'file'})},4905"blob") ." | ";4906if($have_blame) {4907print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4908 file_name=>$diff->{'file'})},4909"blame") ." | ";4910}4911print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4912 file_name=>$diff->{'file'})},4913"history");4914print"</td>\n";49154916}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4917my$mode_chnge="";4918if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4919$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4920if($from_file_typene$to_file_type) {4921$mode_chnge.=" from$from_file_typeto$to_file_type";4922}4923if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4924if($from_mode_str&&$to_mode_str) {4925$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4926}elsif($to_mode_str) {4927$mode_chnge.=" mode:$to_mode_str";4928}4929}4930$mode_chnge.="]</span>\n";4931}4932print"<td>";4933print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4934 hash_base=>$hash, file_name=>$diff->{'file'}),4935-class=>"list"}, esc_path($diff->{'file'}));4936print"</td>\n";4937print"<td>$mode_chnge</td>\n";4938print"<td class=\"link\">";4939if($actioneq'commitdiff') {4940# link to patch4941$patchno++;4942print$cgi->a({-href => href(-anchor=>"patch$patchno")},4943"patch") .4944" | ";4945}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4946# "commit" view and modified file (not onlu mode changed)4947print$cgi->a({-href => href(action=>"blobdiff",4948 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4949 hash_base=>$hash, hash_parent_base=>$parent,4950 file_name=>$diff->{'file'})},4951"diff") .4952" | ";4953}4954print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4955 hash_base=>$hash, file_name=>$diff->{'file'})},4956"blob") ." | ";4957if($have_blame) {4958print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4959 file_name=>$diff->{'file'})},4960"blame") ." | ";4961}4962print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4963 file_name=>$diff->{'file'})},4964"history");4965print"</td>\n";49664967}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4968my%status_name= ('R'=>'moved','C'=>'copied');4969my$nstatus=$status_name{$diff->{'status'}};4970my$mode_chng="";4971if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4972# mode also for directories, so we cannot use $to_mode_str4973$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4974}4975print"<td>".4976$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4977 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4978-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4979"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4980$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4981 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4982-class=>"list"}, esc_path($diff->{'from_file'})) .4983" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4984"<td class=\"link\">";4985if($actioneq'commitdiff') {4986# link to patch4987$patchno++;4988print$cgi->a({-href => href(-anchor=>"patch$patchno")},4989"patch") .4990" | ";4991}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4992# "commit" view and modified file (not only pure rename or copy)4993print$cgi->a({-href => href(action=>"blobdiff",4994 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4995 hash_base=>$hash, hash_parent_base=>$parent,4996 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4997"diff") .4998" | ";4999}5000print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},5001 hash_base=>$parent, file_name=>$diff->{'to_file'})},5002"blob") ." | ";5003if($have_blame) {5004print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,5005 file_name=>$diff->{'to_file'})},5006"blame") ." | ";5007}5008print$cgi->a({-href => href(action=>"history", hash_base=>$hash,5009 file_name=>$diff->{'to_file'})},5010"history");5011print"</td>\n";50125013}# we should not encounter Unmerged (U) or Unknown (X) status5014print"</tr>\n";5015}5016print"</tbody>"if$has_header;5017print"</table>\n";5018}50195020# Print context lines and then rem/add lines in a side-by-side manner.5021sub print_sidebyside_diff_lines {5022my($ctx,$rem,$add) =@_;50235024# print context block before add/rem block5025if(@$ctx) {5026print join'',5027'<div class="chunk_block ctx">',5028'<div class="old">',5029@$ctx,5030'</div>',5031'<div class="new">',5032@$ctx,5033'</div>',5034'</div>';5035}50365037if(!@$add) {5038# pure removal5039print join'',5040'<div class="chunk_block rem">',5041'<div class="old">',5042@$rem,5043'</div>',5044'</div>';5045}elsif(!@$rem) {5046# pure addition5047print join'',5048'<div class="chunk_block add">',5049'<div class="new">',5050@$add,5051'</div>',5052'</div>';5053}else{5054print join'',5055'<div class="chunk_block chg">',5056'<div class="old">',5057@$rem,5058'</div>',5059'<div class="new">',5060@$add,5061'</div>',5062'</div>';5063}5064}50655066# Print context lines and then rem/add lines in inline manner.5067sub print_inline_diff_lines {5068my($ctx,$rem,$add) =@_;50695070print@$ctx,@$rem,@$add;5071}50725073# Format removed and added line, mark changed part and HTML-format them.5074# Implementation is based on contrib/diff-highlight5075sub format_rem_add_lines_pair {5076my($rem,$add,$num_parents) =@_;50775078# We need to untabify lines before split()'ing them;5079# otherwise offsets would be invalid.5080chomp$rem;5081chomp$add;5082$rem= untabify($rem);5083$add= untabify($add);50845085my@rem=split(//,$rem);5086my@add=split(//,$add);5087my($esc_rem,$esc_add);5088# Ignore leading +/- characters for each parent.5089my($prefix_len,$suffix_len) = ($num_parents,0);5090my($prefix_has_nonspace,$suffix_has_nonspace);50915092my$shorter= (@rem<@add) ?@rem:@add;5093while($prefix_len<$shorter) {5094last if($rem[$prefix_len]ne$add[$prefix_len]);50955096$prefix_has_nonspace=1if($rem[$prefix_len] !~/\s/);5097$prefix_len++;5098}50995100while($prefix_len+$suffix_len<$shorter) {5101last if($rem[-1-$suffix_len]ne$add[-1-$suffix_len]);51025103$suffix_has_nonspace=1if($rem[-1-$suffix_len] !~/\s/);5104$suffix_len++;5105}51065107# Mark lines that are different from each other, but have some common5108# part that isn't whitespace. If lines are completely different, don't5109# mark them because that would make output unreadable, especially if5110# diff consists of multiple lines.5111if($prefix_has_nonspace||$suffix_has_nonspace) {5112$esc_rem= esc_html_hl_regions($rem,'marked',5113[$prefix_len,@rem-$suffix_len], -nbsp=>1);5114$esc_add= esc_html_hl_regions($add,'marked',5115[$prefix_len,@add-$suffix_len], -nbsp=>1);5116}else{5117$esc_rem= esc_html($rem, -nbsp=>1);5118$esc_add= esc_html($add, -nbsp=>1);5119}51205121return format_diff_line(\$esc_rem,'rem'),5122 format_diff_line(\$esc_add,'add');5123}51245125# HTML-format diff context, removed and added lines.5126sub format_ctx_rem_add_lines {5127my($ctx,$rem,$add,$num_parents) =@_;5128my(@new_ctx,@new_rem,@new_add);5129my$can_highlight=0;5130my$is_combined= ($num_parents>1);51315132# Highlight if every removed line has a corresponding added line.5133if(@$add>0&&@$add==@$rem) {5134$can_highlight=1;51355136# Highlight lines in combined diff only if the chunk contains5137# diff between the same version, e.g.5138#5139# - a5140# - b5141# + c5142# + d5143#5144# Otherwise the highlightling would be confusing.5145if($is_combined) {5146for(my$i=0;$i<@$add;$i++) {5147my$prefix_rem=substr($rem->[$i],0,$num_parents);5148my$prefix_add=substr($add->[$i],0,$num_parents);51495150$prefix_rem=~s/-/+/g;51515152if($prefix_remne$prefix_add) {5153$can_highlight=0;5154last;5155}5156}5157}5158}51595160if($can_highlight) {5161for(my$i=0;$i<@$add;$i++) {5162my($line_rem,$line_add) = format_rem_add_lines_pair(5163$rem->[$i],$add->[$i],$num_parents);5164push@new_rem,$line_rem;5165push@new_add,$line_add;5166}5167}else{5168@new_rem=map{ format_diff_line($_,'rem') }@$rem;5169@new_add=map{ format_diff_line($_,'add') }@$add;5170}51715172@new_ctx=map{ format_diff_line($_,'ctx') }@$ctx;51735174return(\@new_ctx, \@new_rem, \@new_add);5175}51765177# Print context lines and then rem/add lines.5178sub print_diff_lines {5179my($ctx,$rem,$add,$diff_style,$num_parents) =@_;5180my$is_combined=$num_parents>1;51815182($ctx,$rem,$add) = format_ctx_rem_add_lines($ctx,$rem,$add,5183$num_parents);51845185if($diff_styleeq'sidebyside'&& !$is_combined) {5186 print_sidebyside_diff_lines($ctx,$rem,$add);5187}else{5188# default 'inline' style and unknown styles5189 print_inline_diff_lines($ctx,$rem,$add);5190}5191}51925193sub print_diff_chunk {5194my($diff_style,$num_parents,$from,$to,@chunk) =@_;5195my(@ctx,@rem,@add);51965197# The class of the previous line.5198my$prev_class='';51995200return unless@chunk;52015202# incomplete last line might be among removed or added lines,5203# or both, or among context lines: find which5204for(my$i=1;$i<@chunk;$i++) {5205if($chunk[$i][0]eq'incomplete') {5206$chunk[$i][0] =$chunk[$i-1][0];5207}5208}52095210# guardian5211push@chunk, ["",""];52125213foreachmy$line_info(@chunk) {5214my($class,$line) =@$line_info;52155216# print chunk headers5217if($class&&$classeq'chunk_header') {5218print format_diff_line($line,$class,$from,$to);5219next;5220}52215222## print from accumulator when have some add/rem lines or end5223# of chunk (flush context lines), or when have add and rem5224# lines and new block is reached (otherwise add/rem lines could5225# be reordered)5226if(!$class|| ((@rem||@add) &&$classeq'ctx') ||5227(@rem&&@add&&$classne$prev_class)) {5228 print_diff_lines(\@ctx, \@rem, \@add,5229$diff_style,$num_parents);5230@ctx=@rem=@add= ();5231}52325233## adding lines to accumulator5234# guardian value5235last unless$line;5236# rem, add or change5237if($classeq'rem') {5238push@rem,$line;5239}elsif($classeq'add') {5240push@add,$line;5241}5242# context line5243if($classeq'ctx') {5244push@ctx,$line;5245}52465247$prev_class=$class;5248}5249}52505251sub git_patchset_body {5252my($fd,$diff_style,$difftree,$hash,@hash_parents) =@_;5253my($hash_parent) =$hash_parents[0];52545255my$is_combined= (@hash_parents>1);5256my$patch_idx=0;5257my$patch_number=0;5258my$patch_line;5259my$diffinfo;5260my$to_name;5261my(%from,%to);5262my@chunk;# for side-by-side diff52635264print"<div class=\"patchset\">\n";52655266# skip to first patch5267while($patch_line= <$fd>) {5268chomp$patch_line;52695270last if($patch_line=~m/^diff /);5271}52725273 PATCH:5274while($patch_line) {52755276# parse "git diff" header line5277if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {5278# $1 is from_name, which we do not use5279$to_name= unquote($2);5280$to_name=~s!^b/!!;5281}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {5282# $1 is 'cc' or 'combined', which we do not use5283$to_name= unquote($2);5284}else{5285$to_name=undef;5286}52875288# check if current patch belong to current raw line5289# and parse raw git-diff line if needed5290if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {5291# this is continuation of a split patch5292print"<div class=\"patch cont\">\n";5293}else{5294# advance raw git-diff output if needed5295$patch_idx++ifdefined$diffinfo;52965297# read and prepare patch information5298$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);52995300# compact combined diff output can have some patches skipped5301# find which patch (using pathname of result) we are at now;5302if($is_combined) {5303while($to_namene$diffinfo->{'to_file'}) {5304print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5305 format_diff_cc_simplified($diffinfo,@hash_parents) .5306"</div>\n";# class="patch"53075308$patch_idx++;5309$patch_number++;53105311last if$patch_idx>$#$difftree;5312$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);5313}5314}53155316# modifies %from, %to hashes5317 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);53185319# this is first patch for raw difftree line with $patch_idx index5320# we index @$difftree array from 0, but number patches from 15321print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";5322}53235324# git diff header5325#assert($patch_line =~ m/^diff /) if DEBUG;5326#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed5327$patch_number++;5328# print "git diff" header5329print format_git_diff_header_line($patch_line,$diffinfo,5330 \%from, \%to);53315332# print extended diff header5333print"<div class=\"diff extended_header\">\n";5334 EXTENDED_HEADER:5335while($patch_line= <$fd>) {5336chomp$patch_line;53375338last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);53395340print format_extended_diff_header_line($patch_line,$diffinfo,5341 \%from, \%to);5342}5343print"</div>\n";# class="diff extended_header"53445345# from-file/to-file diff header5346if(!$patch_line) {5347print"</div>\n";# class="patch"5348last PATCH;5349}5350next PATCH if($patch_line=~m/^diff /);5351#assert($patch_line =~ m/^---/) if DEBUG;53525353my$last_patch_line=$patch_line;5354$patch_line= <$fd>;5355chomp$patch_line;5356#assert($patch_line =~ m/^\+\+\+/) if DEBUG;53575358print format_diff_from_to_header($last_patch_line,$patch_line,5359$diffinfo, \%from, \%to,5360@hash_parents);53615362# the patch itself5363 LINE:5364while($patch_line= <$fd>) {5365chomp$patch_line;53665367next PATCH if($patch_line=~m/^diff /);53685369my$class= diff_line_class($patch_line, \%from, \%to);53705371if($classeq'chunk_header') {5372 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5373@chunk= ();5374}53755376push@chunk, [$class,$patch_line];5377}53785379}continue{5380if(@chunk) {5381 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5382@chunk= ();5383}5384print"</div>\n";# class="patch"5385}53865387# for compact combined (--cc) format, with chunk and patch simplification5388# the patchset might be empty, but there might be unprocessed raw lines5389for(++$patch_idxif$patch_number>0;5390$patch_idx<@$difftree;5391++$patch_idx) {5392# read and prepare patch information5393$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);53945395# generate anchor for "patch" links in difftree / whatchanged part5396print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5397 format_diff_cc_simplified($diffinfo,@hash_parents) .5398"</div>\n";# class="patch"53995400$patch_number++;5401}54025403if($patch_number==0) {5404if(@hash_parents>1) {5405print"<div class=\"diff nodifferences\">Trivial merge</div>\n";5406}else{5407print"<div class=\"diff nodifferences\">No differences found</div>\n";5408}5409}54105411print"</div>\n";# class="patchset"5412}54135414# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .54155416sub git_project_search_form {5417my($searchtext,$search_use_regexp) =@_;54185419my$limit='';5420if($project_filter) {5421$limit=" in '$project_filter/'";5422}54235424print"<div class=\"projsearch\">\n";5425print$cgi->startform(-method=>'get', -action =>$my_uri) .5426$cgi->hidden(-name =>'a', -value =>'project_list') ."\n";5427print$cgi->hidden(-name =>'pf', -value =>$project_filter)."\n"5428if(defined$project_filter);5429print$cgi->textfield(-name =>'s', -value =>$searchtext,5430-title =>"Search project by name and description$limit",5431-size =>60) ."\n".5432"<span title=\"Extended regular expression\">".5433$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',5434-checked =>$search_use_regexp) .5435"</span>\n".5436$cgi->submit(-name =>'btnS', -value =>'Search') .5437$cgi->end_form() ."\n".5438$cgi->a({-href => href(project =>undef, searchtext =>undef,5439 project_filter =>$project_filter)},5440 esc_html("List all projects$limit")) ."<br />\n";5441print"</div>\n";5442}54435444# entry for given @keys needs filling if at least one of keys in list5445# is not present in %$project_info5446sub project_info_needs_filling {5447my($project_info,@keys) =@_;54485449# return List::MoreUtils::any { !exists $project_info->{$_} } @keys;5450foreachmy$key(@keys) {5451if(!exists$project_info->{$key}) {5452return1;5453}5454}5455return;5456}54575458# fills project list info (age, description, owner, category, forks, etc.)5459# for each project in the list, removing invalid projects from5460# returned list, or fill only specified info.5461#5462# Invalid projects are removed from the returned list if and only if you5463# ask 'age' or 'age_string' to be filled, because they are the only fields5464# that run unconditionally git command that requires repository, and5465# therefore do always check if project repository is invalid.5466#5467# USAGE:5468# * fill_project_list_info(\@project_list, 'descr_long', 'ctags')5469# ensures that 'descr_long' and 'ctags' fields are filled5470# * @project_list = fill_project_list_info(\@project_list)5471# ensures that all fields are filled (and invalid projects removed)5472#5473# NOTE: modifies $projlist, but does not remove entries from it5474sub fill_project_list_info {5475my($projlist,@wanted_keys) =@_;5476my@projects;5477my$filter_set=sub{return@_; };5478if(@wanted_keys) {5479my%wanted_keys=map{$_=>1}@wanted_keys;5480$filter_set=sub{returngrep{$wanted_keys{$_} }@_; };5481}54825483my$show_ctags= gitweb_check_feature('ctags');5484 PROJECT:5485foreachmy$pr(@$projlist) {5486if(project_info_needs_filling($pr,$filter_set->('age','age_string'))) {5487my(@activity) = git_get_last_activity($pr->{'path'});5488unless(@activity) {5489next PROJECT;5490}5491($pr->{'age'},$pr->{'age_string'}) =@activity;5492}5493if(project_info_needs_filling($pr,$filter_set->('descr','descr_long'))) {5494my$descr= git_get_project_description($pr->{'path'}) ||"";5495$descr= to_utf8($descr);5496$pr->{'descr_long'} =$descr;5497$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);5498}5499if(project_info_needs_filling($pr,$filter_set->('owner'))) {5500$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";5501}5502if($show_ctags&&5503 project_info_needs_filling($pr,$filter_set->('ctags'))) {5504$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});5505}5506if($projects_list_group_categories&&5507 project_info_needs_filling($pr,$filter_set->('category'))) {5508my$cat= git_get_project_category($pr->{'path'}) ||5509$project_list_default_category;5510$pr->{'category'} = to_utf8($cat);5511}55125513push@projects,$pr;5514}55155516return@projects;5517}55185519sub sort_projects_list {5520my($projlist,$order) =@_;5521my@projects;55225523my%order_info= (5524 project => { key =>'path', type =>'str'},5525 descr => { key =>'descr_long', type =>'str'},5526 owner => { key =>'owner', type =>'str'},5527 age => { key =>'age', type =>'num'}5528);5529my$oi=$order_info{$order};5530return@$projlistunlessdefined$oi;5531if($oi->{'type'}eq'str') {5532@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@$projlist;5533}else{5534@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@$projlist;5535}55365537return@projects;5538}55395540# returns a hash of categories, containing the list of project5541# belonging to each category5542sub build_projlist_by_category {5543my($projlist,$from,$to) =@_;5544my%categories;55455546$from=0unlessdefined$from;5547$to=$#$projlistif(!defined$to||$#$projlist<$to);55485549for(my$i=$from;$i<=$to;$i++) {5550my$pr=$projlist->[$i];5551push@{$categories{$pr->{'category'} }},$pr;5552}55535554returnwantarray?%categories: \%categories;5555}55565557# print 'sort by' <th> element, generating 'sort by $name' replay link5558# if that order is not selected5559sub print_sort_th {5560print format_sort_th(@_);5561}55625563sub format_sort_th {5564my($name,$order,$header) =@_;5565my$sort_th="";5566$header||=ucfirst($name);55675568if($ordereq$name) {5569$sort_th.="<th>$header</th>\n";5570}else{5571$sort_th.="<th>".5572$cgi->a({-href => href(-replay=>1, order=>$name),5573-class=>"header"},$header) .5574"</th>\n";5575}55765577return$sort_th;5578}55795580sub git_project_list_rows {5581my($projlist,$from,$to,$check_forks) =@_;55825583$from=0unlessdefined$from;5584$to=$#$projlistif(!defined$to||$#$projlist<$to);55855586my$alternate=1;5587for(my$i=$from;$i<=$to;$i++) {5588my$pr=$projlist->[$i];55895590if($alternate) {5591print"<tr class=\"dark\">\n";5592}else{5593print"<tr class=\"light\">\n";5594}5595$alternate^=1;55965597if($check_forks) {5598print"<td>";5599if($pr->{'forks'}) {5600my$nforks=scalar@{$pr->{'forks'}};5601if($nforks>0) {5602print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5603-title =>"$nforksforks"},"+");5604}else{5605print$cgi->span({-title =>"$nforksforks"},"+");5606}5607}5608print"</td>\n";5609}5610print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5611-class=>"list"},5612 esc_html_match_hl($pr->{'path'},$search_regexp)) .5613"</td>\n".5614"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5615-class=>"list",5616-title =>$pr->{'descr_long'}},5617$search_regexp5618? esc_html_match_hl_chopped($pr->{'descr_long'},5619$pr->{'descr'},$search_regexp)5620: esc_html($pr->{'descr'})) .5621"</td>\n";5622unless($omit_owner) {5623print"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5624}5625unless($omit_age_column) {5626print"<td class=\"". age_class($pr->{'age'}) ."\">".5627(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n";5628}5629print"<td class=\"link\">".5630$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5631$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5632$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5633$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5634($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5635"</td>\n".5636"</tr>\n";5637}5638}56395640sub git_project_list_body {5641# actually uses global variable $project5642my($projlist,$order,$from,$to,$extra,$no_header) =@_;5643my@projects=@$projlist;56445645my$check_forks= gitweb_check_feature('forks');5646my$show_ctags= gitweb_check_feature('ctags');5647my$tagfilter=$show_ctags?$input_params{'ctag'} :undef;5648$check_forks=undef5649if($tagfilter||$search_regexp);56505651# filtering out forks before filling info allows to do less work5652@projects= filter_forks_from_projects_list(\@projects)5653if($check_forks);5654# search_projects_list pre-fills required info5655@projects= search_projects_list(\@projects,5656'search_regexp'=>$search_regexp,5657'tagfilter'=>$tagfilter)5658if($tagfilter||$search_regexp);5659# fill the rest5660my@all_fields= ('descr','descr_long','ctags','category');5661push@all_fields, ('age','age_string')unless($omit_age_column);5662push@all_fields,'owner'unless($omit_owner);5663@projects= fill_project_list_info(\@projects,@all_fields);56645665$order||=$default_projects_order;5666$from=0unlessdefined$from;5667$to=$#projectsif(!defined$to||$#projects<$to);56685669# short circuit5670if($from>$to) {5671print"<center>\n".5672"<b>No such projects found</b><br />\n".5673"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5674"</center>\n<br />\n";5675return;5676}56775678@projects= sort_projects_list(\@projects,$order);56795680if($show_ctags) {5681my$ctags= git_gather_all_ctags(\@projects);5682my$cloud= git_populate_project_tagcloud($ctags);5683print git_show_project_tagcloud($cloud,64);5684}56855686print"<table class=\"project_list\">\n";5687unless($no_header) {5688print"<tr>\n";5689if($check_forks) {5690print"<th></th>\n";5691}5692 print_sort_th('project',$order,'Project');5693 print_sort_th('descr',$order,'Description');5694 print_sort_th('owner',$order,'Owner')unless$omit_owner;5695 print_sort_th('age',$order,'Last Change')unless$omit_age_column;5696print"<th></th>\n".# for links5697"</tr>\n";5698}56995700if($projects_list_group_categories) {5701# only display categories with projects in the $from-$to window5702@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5703my%categories= build_projlist_by_category(\@projects,$from,$to);5704foreachmy$cat(sort keys%categories) {5705unless($cateq"") {5706print"<tr>\n";5707if($check_forks) {5708print"<td></td>\n";5709}5710print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5711print"</tr>\n";5712}57135714 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5715}5716}else{5717 git_project_list_rows(\@projects,$from,$to,$check_forks);5718}57195720if(defined$extra) {5721print"<tr>\n";5722if($check_forks) {5723print"<td></td>\n";5724}5725print"<td colspan=\"5\">$extra</td>\n".5726"</tr>\n";5727}5728print"</table>\n";5729}57305731sub git_log_body {5732# uses global variable $project5733my($commitlist,$from,$to,$refs,$extra) =@_;57345735$from=0unlessdefined$from;5736$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);57375738for(my$i=0;$i<=$to;$i++) {5739my%co= %{$commitlist->[$i]};5740next if!%co;5741my$commit=$co{'id'};5742my$ref= format_ref_marker($refs,$commit);5743 git_print_header_div('commit',5744"<span class=\"age\">$co{'age_string'}</span>".5745 esc_html($co{'title'}) .$ref,5746$commit);5747print"<div class=\"title_text\">\n".5748"<div class=\"log_link\">\n".5749$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5750" | ".5751$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5752" | ".5753$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5754"<br/>\n".5755"</div>\n";5756 git_print_authorship(\%co, -tag =>'span');5757print"<br/>\n</div>\n";57585759print"<div class=\"log_body\">\n";5760 git_print_log($co{'comment'}, -final_empty_line=>1);5761print"</div>\n";5762}5763if($extra) {5764print"<div class=\"page_nav\">\n";5765print"$extra\n";5766print"</div>\n";5767}5768}57695770sub git_shortlog_body {5771# uses global variable $project5772my($commitlist,$from,$to,$refs,$extra) =@_;57735774$from=0unlessdefined$from;5775$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);57765777print"<table class=\"shortlog\">\n";5778my$alternate=1;5779for(my$i=$from;$i<=$to;$i++) {5780my%co= %{$commitlist->[$i]};5781my$commit=$co{'id'};5782my$ref= format_ref_marker($refs,$commit);5783if($alternate) {5784print"<tr class=\"dark\">\n";5785}else{5786print"<tr class=\"light\">\n";5787}5788$alternate^=1;5789# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5790print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5791 format_author_html('td', \%co,10) ."<td>";5792print format_subject_html($co{'title'},$co{'title_short'},5793 href(action=>"commit", hash=>$commit),$ref);5794print"</td>\n".5795"<td class=\"link\">".5796$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5797$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5798$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5799my$snapshot_links= format_snapshot_links($commit);5800if(defined$snapshot_links) {5801print" | ".$snapshot_links;5802}5803print"</td>\n".5804"</tr>\n";5805}5806if(defined$extra) {5807print"<tr>\n".5808"<td colspan=\"4\">$extra</td>\n".5809"</tr>\n";5810}5811print"</table>\n";5812}58135814sub git_history_body {5815# Warning: assumes constant type (blob or tree) during history5816my($commitlist,$from,$to,$refs,$extra,5817$file_name,$file_hash,$ftype) =@_;58185819$from=0unlessdefined$from;5820$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});58215822print"<table class=\"history\">\n";5823my$alternate=1;5824for(my$i=$from;$i<=$to;$i++) {5825my%co= %{$commitlist->[$i]};5826if(!%co) {5827next;5828}5829my$commit=$co{'id'};58305831my$ref= format_ref_marker($refs,$commit);58325833if($alternate) {5834print"<tr class=\"dark\">\n";5835}else{5836print"<tr class=\"light\">\n";5837}5838$alternate^=1;5839print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5840# shortlog: format_author_html('td', \%co, 10)5841 format_author_html('td', \%co,15,3) ."<td>";5842# originally git_history used chop_str($co{'title'}, 50)5843print format_subject_html($co{'title'},$co{'title_short'},5844 href(action=>"commit", hash=>$commit),$ref);5845print"</td>\n".5846"<td class=\"link\">".5847$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5848$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");58495850if($ftypeeq'blob') {5851my$blob_current=$file_hash;5852my$blob_parent= git_get_hash_by_path($commit,$file_name);5853if(defined$blob_current&&defined$blob_parent&&5854$blob_currentne$blob_parent) {5855print" | ".5856$cgi->a({-href => href(action=>"blobdiff",5857 hash=>$blob_current, hash_parent=>$blob_parent,5858 hash_base=>$hash_base, hash_parent_base=>$commit,5859 file_name=>$file_name)},5860"diff to current");5861}5862}5863print"</td>\n".5864"</tr>\n";5865}5866if(defined$extra) {5867print"<tr>\n".5868"<td colspan=\"4\">$extra</td>\n".5869"</tr>\n";5870}5871print"</table>\n";5872}58735874sub git_tags_body {5875# uses global variable $project5876my($taglist,$from,$to,$extra) =@_;5877$from=0unlessdefined$from;5878$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);58795880print"<table class=\"tags\">\n";5881my$alternate=1;5882for(my$i=$from;$i<=$to;$i++) {5883my$entry=$taglist->[$i];5884my%tag=%$entry;5885my$comment=$tag{'subject'};5886my$comment_short;5887if(defined$comment) {5888$comment_short= chop_str($comment,30,5);5889}5890if($alternate) {5891print"<tr class=\"dark\">\n";5892}else{5893print"<tr class=\"light\">\n";5894}5895$alternate^=1;5896if(defined$tag{'age'}) {5897print"<td><i>$tag{'age'}</i></td>\n";5898}else{5899print"<td></td>\n";5900}5901print"<td>".5902$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5903-class=>"list name"}, esc_html($tag{'name'})) .5904"</td>\n".5905"<td>";5906if(defined$comment) {5907print format_subject_html($comment,$comment_short,5908 href(action=>"tag", hash=>$tag{'id'}));5909}5910print"</td>\n".5911"<td class=\"selflink\">";5912if($tag{'type'}eq"tag") {5913print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");5914}else{5915print" ";5916}5917print"</td>\n".5918"<td class=\"link\">"." | ".5919$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});5920if($tag{'reftype'}eq"commit") {5921print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .5922" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");5923}elsif($tag{'reftype'}eq"blob") {5924print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");5925}5926print"</td>\n".5927"</tr>";5928}5929if(defined$extra) {5930print"<tr>\n".5931"<td colspan=\"5\">$extra</td>\n".5932"</tr>\n";5933}5934print"</table>\n";5935}59365937sub git_heads_body {5938# uses global variable $project5939my($headlist,$head_at,$from,$to,$extra) =@_;5940$from=0unlessdefined$from;5941$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);59425943print"<table class=\"heads\">\n";5944my$alternate=1;5945for(my$i=$from;$i<=$to;$i++) {5946my$entry=$headlist->[$i];5947my%ref=%$entry;5948my$curr=defined$head_at&&$ref{'id'}eq$head_at;5949if($alternate) {5950print"<tr class=\"dark\">\n";5951}else{5952print"<tr class=\"light\">\n";5953}5954$alternate^=1;5955print"<td><i>$ref{'age'}</i></td>\n".5956($curr?"<td class=\"current_head\">":"<td>") .5957$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),5958-class=>"list name"},esc_html($ref{'name'})) .5959"</td>\n".5960"<td class=\"link\">".5961$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".5962$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".5963$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .5964"</td>\n".5965"</tr>";5966}5967if(defined$extra) {5968print"<tr>\n".5969"<td colspan=\"3\">$extra</td>\n".5970"</tr>\n";5971}5972print"</table>\n";5973}59745975# Display a single remote block5976sub git_remote_block {5977my($remote,$rdata,$limit,$head) =@_;59785979my$heads=$rdata->{'heads'};5980my$fetch=$rdata->{'fetch'};5981my$push=$rdata->{'push'};59825983my$urls_table="<table class=\"projects_list\">\n";59845985if(defined$fetch) {5986if($fetcheq$push) {5987$urls_table.= format_repo_url("URL",$fetch);5988}else{5989$urls_table.= format_repo_url("Fetch URL",$fetch);5990$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;5991}5992}elsif(defined$push) {5993$urls_table.= format_repo_url("Push URL",$push);5994}else{5995$urls_table.= format_repo_url("","No remote URL");5996}59975998$urls_table.="</table>\n";59996000my$dots;6001if(defined$limit&&$limit<@$heads) {6002$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");6003}60046005print$urls_table;6006 git_heads_body($heads,$head,0,$limit,$dots);6007}60086009# Display a list of remote names with the respective fetch and push URLs6010sub git_remotes_list {6011my($remotedata,$limit) =@_;6012print"<table class=\"heads\">\n";6013my$alternate=1;6014my@remotes=sort keys%$remotedata;60156016my$limited=$limit&&$limit<@remotes;60176018$#remotes=$limit-1if$limited;60196020while(my$remote=shift@remotes) {6021my$rdata=$remotedata->{$remote};6022my$fetch=$rdata->{'fetch'};6023my$push=$rdata->{'push'};6024if($alternate) {6025print"<tr class=\"dark\">\n";6026}else{6027print"<tr class=\"light\">\n";6028}6029$alternate^=1;6030print"<td>".6031$cgi->a({-href=> href(action=>'remotes', hash=>$remote),6032-class=>"list name"},esc_html($remote)) .6033"</td>";6034print"<td class=\"link\">".6035(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .6036" | ".6037(defined$push?$cgi->a({-href=>$push},"push") :"push") .6038"</td>";60396040print"</tr>\n";6041}60426043if($limited) {6044print"<tr>\n".6045"<td colspan=\"3\">".6046$cgi->a({-href => href(action=>"remotes")},"...") .6047"</td>\n"."</tr>\n";6048}60496050print"</table>";6051}60526053# Display remote heads grouped by remote, unless there are too many6054# remotes, in which case we only display the remote names6055sub git_remotes_body {6056my($remotedata,$limit,$head) =@_;6057if($limitand$limit<keys%$remotedata) {6058 git_remotes_list($remotedata,$limit);6059}else{6060 fill_remote_heads($remotedata);6061while(my($remote,$rdata) =each%$remotedata) {6062 git_print_section({-class=>"remote", -id=>$remote},6063["remotes",$remote,$remote],sub{6064 git_remote_block($remote,$rdata,$limit,$head);6065});6066}6067}6068}60696070sub git_search_message {6071my%co=@_;60726073my$greptype;6074if($searchtypeeq'commit') {6075$greptype="--grep=";6076}elsif($searchtypeeq'author') {6077$greptype="--author=";6078}elsif($searchtypeeq'committer') {6079$greptype="--committer=";6080}6081$greptype.=$searchtext;6082my@commitlist= parse_commits($hash,101, (100*$page),undef,6083$greptype,'--regexp-ignore-case',6084$search_use_regexp?'--extended-regexp':'--fixed-strings');60856086my$paging_nav='';6087if($page>0) {6088$paging_nav.=6089$cgi->a({-href => href(-replay=>1, page=>undef)},6090"first") .6091" ⋅ ".6092$cgi->a({-href => href(-replay=>1, page=>$page-1),6093-accesskey =>"p", -title =>"Alt-p"},"prev");6094}else{6095$paging_nav.="first ⋅ prev";6096}6097my$next_link='';6098if($#commitlist>=100) {6099$next_link=6100$cgi->a({-href => href(-replay=>1, page=>$page+1),6101-accesskey =>"n", -title =>"Alt-n"},"next");6102$paging_nav.=" ⋅$next_link";6103}else{6104$paging_nav.=" ⋅ next";6105}61066107 git_header_html();61086109 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);6110 git_print_header_div('commit', esc_html($co{'title'}),$hash);6111if($page==0&& !@commitlist) {6112print"<p>No match.</p>\n";6113}else{6114 git_search_grep_body(\@commitlist,0,99,$next_link);6115}61166117 git_footer_html();6118}61196120sub git_search_changes {6121my%co=@_;61226123local$/="\n";6124open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,6125'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",6126($search_use_regexp?'--pickaxe-regex': ())6127or die_error(500,"Open git-log failed");61286129 git_header_html();61306131 git_print_page_nav('','',$hash,$co{'tree'},$hash);6132 git_print_header_div('commit', esc_html($co{'title'}),$hash);61336134print"<table class=\"pickaxe search\">\n";6135my$alternate=1;6136undef%co;6137my@files;6138while(my$line= <$fd>) {6139chomp$line;6140next unless$line;61416142my%set= parse_difftree_raw_line($line);6143if(defined$set{'commit'}) {6144# finish previous commit6145if(%co) {6146print"</td>\n".6147"<td class=\"link\">".6148$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6149"commit") .6150" | ".6151$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6152 hash_base=>$co{'id'})},6153"tree") .6154"</td>\n".6155"</tr>\n";6156}61576158if($alternate) {6159print"<tr class=\"dark\">\n";6160}else{6161print"<tr class=\"light\">\n";6162}6163$alternate^=1;6164%co= parse_commit($set{'commit'});6165my$author= chop_and_escape_str($co{'author_name'},15,5);6166print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6167"<td><i>$author</i></td>\n".6168"<td>".6169$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6170-class=>"list subject"},6171 chop_and_escape_str($co{'title'},50) ."<br/>");6172}elsif(defined$set{'to_id'}) {6173next if($set{'to_id'} =~m/^0{40}$/);61746175print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},6176 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),6177-class=>"list"},6178"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .6179"<br/>\n";6180}6181}6182close$fd;61836184# finish last commit (warning: repetition!)6185if(%co) {6186print"</td>\n".6187"<td class=\"link\">".6188$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6189"commit") .6190" | ".6191$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6192 hash_base=>$co{'id'})},6193"tree") .6194"</td>\n".6195"</tr>\n";6196}61976198print"</table>\n";61996200 git_footer_html();6201}62026203sub git_search_files {6204my%co=@_;62056206local$/="\n";6207open my$fd,"-|", git_cmd(),'grep','-n','-z',6208$search_use_regexp? ('-E','-i') :'-F',6209$searchtext,$co{'tree'}6210or die_error(500,"Open git-grep failed");62116212 git_header_html();62136214 git_print_page_nav('','',$hash,$co{'tree'},$hash);6215 git_print_header_div('commit', esc_html($co{'title'}),$hash);62166217print"<table class=\"grep_search\">\n";6218my$alternate=1;6219my$matches=0;6220my$lastfile='';6221my$file_href;6222while(my$line= <$fd>) {6223chomp$line;6224my($file,$lno,$ltext,$binary);6225last if($matches++>1000);6226if($line=~/^Binary file (.+) matches$/) {6227$file=$1;6228$binary=1;6229}else{6230($file,$lno,$ltext) =split(/\0/,$line,3);6231$file=~s/^$co{'tree'}://;6232}6233if($filene$lastfile) {6234$lastfileand print"</td></tr>\n";6235if($alternate++) {6236print"<tr class=\"dark\">\n";6237}else{6238print"<tr class=\"light\">\n";6239}6240$file_href= href(action=>"blob", hash_base=>$co{'id'},6241 file_name=>$file);6242print"<td class=\"list\">".6243$cgi->a({-href =>$file_href, -class=>"list"}, esc_path($file));6244print"</td><td>\n";6245$lastfile=$file;6246}6247if($binary) {6248print"<div class=\"binary\">Binary file</div>\n";6249}else{6250$ltext= untabify($ltext);6251if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6252$ltext= esc_html($1, -nbsp=>1);6253$ltext.='<span class="match">';6254$ltext.= esc_html($2, -nbsp=>1);6255$ltext.='</span>';6256$ltext.= esc_html($3, -nbsp=>1);6257}else{6258$ltext= esc_html($ltext, -nbsp=>1);6259}6260print"<div class=\"pre\">".6261$cgi->a({-href =>$file_href.'#l'.$lno,6262-class=>"linenr"},sprintf('%4i',$lno)) .6263' '.$ltext."</div>\n";6264}6265}6266if($lastfile) {6267print"</td></tr>\n";6268if($matches>1000) {6269print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6270}6271}else{6272print"<div class=\"diff nodifferences\">No matches found</div>\n";6273}6274close$fd;62756276print"</table>\n";62776278 git_footer_html();6279}62806281sub git_search_grep_body {6282my($commitlist,$from,$to,$extra) =@_;6283$from=0unlessdefined$from;6284$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);62856286print"<table class=\"commit_search\">\n";6287my$alternate=1;6288for(my$i=$from;$i<=$to;$i++) {6289my%co= %{$commitlist->[$i]};6290if(!%co) {6291next;6292}6293my$commit=$co{'id'};6294if($alternate) {6295print"<tr class=\"dark\">\n";6296}else{6297print"<tr class=\"light\">\n";6298}6299$alternate^=1;6300print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6301 format_author_html('td', \%co,15,5) .6302"<td>".6303$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6304-class=>"list subject"},6305 chop_and_escape_str($co{'title'},50) ."<br/>");6306my$comment=$co{'comment'};6307foreachmy$line(@$comment) {6308if($line=~m/^(.*?)($search_regexp)(.*)$/i) {6309my($lead,$match,$trail) = ($1,$2,$3);6310$match= chop_str($match,70,5,'center');6311my$contextlen=int((80-length($match))/2);6312$contextlen=30if($contextlen>30);6313$lead= chop_str($lead,$contextlen,10,'left');6314$trail= chop_str($trail,$contextlen,10,'right');63156316$lead= esc_html($lead);6317$match= esc_html($match);6318$trail= esc_html($trail);63196320print"$lead<span class=\"match\">$match</span>$trail<br />";6321}6322}6323print"</td>\n".6324"<td class=\"link\">".6325$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6326" | ".6327$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .6328" | ".6329$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6330print"</td>\n".6331"</tr>\n";6332}6333if(defined$extra) {6334print"<tr>\n".6335"<td colspan=\"3\">$extra</td>\n".6336"</tr>\n";6337}6338print"</table>\n";6339}63406341## ======================================================================6342## ======================================================================6343## actions63446345sub git_project_list {6346my$order=$input_params{'order'};6347if(defined$order&&$order!~m/none|project|descr|owner|age/) {6348 die_error(400,"Unknown order parameter");6349}63506351my@list= git_get_projects_list($project_filter,$strict_export);6352if(!@list) {6353 die_error(404,"No projects found");6354}63556356 git_header_html();6357if(defined$home_text&& -f $home_text) {6358print"<div class=\"index_include\">\n";6359 insert_file($home_text);6360print"</div>\n";6361}63626363 git_project_search_form($searchtext,$search_use_regexp);6364 git_project_list_body(\@list,$order);6365 git_footer_html();6366}63676368sub git_forks {6369my$order=$input_params{'order'};6370if(defined$order&&$order!~m/none|project|descr|owner|age/) {6371 die_error(400,"Unknown order parameter");6372}63736374my$filter=$project;6375$filter=~s/\.git$//;6376my@list= git_get_projects_list($filter);6377if(!@list) {6378 die_error(404,"No forks found");6379}63806381 git_header_html();6382 git_print_page_nav('','');6383 git_print_header_div('summary',"$projectforks");6384 git_project_list_body(\@list,$order);6385 git_footer_html();6386}63876388sub git_project_index {6389my@projects= git_get_projects_list($project_filter,$strict_export);6390if(!@projects) {6391 die_error(404,"No projects found");6392}63936394print$cgi->header(6395-type =>'text/plain',6396-charset =>'utf-8',6397-content_disposition =>'inline; filename="index.aux"');63986399foreachmy$pr(@projects) {6400if(!exists$pr->{'owner'}) {6401$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");6402}64036404my($path,$owner) = ($pr->{'path'},$pr->{'owner'});6405# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '6406$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6407$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6408$path=~s/ /\+/g;6409$owner=~s/ /\+/g;64106411print"$path$owner\n";6412}6413}64146415sub git_summary {6416my$descr= git_get_project_description($project) ||"none";6417my%co= parse_commit("HEAD");6418my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();6419my$head=$co{'id'};6420my$remote_heads= gitweb_check_feature('remote_heads');64216422my$owner= git_get_project_owner($project);64236424my$refs= git_get_references();6425# These get_*_list functions return one more to allow us to see if6426# there are more ...6427my@taglist= git_get_tags_list(16);6428my@headlist= git_get_heads_list(16);6429my%remotedata=$remote_heads? git_get_remotes_list() : ();6430my@forklist;6431my$check_forks= gitweb_check_feature('forks');64326433if($check_forks) {6434# find forks of a project6435my$filter=$project;6436$filter=~s/\.git$//;6437@forklist= git_get_projects_list($filter);6438# filter out forks of forks6439@forklist= filter_forks_from_projects_list(\@forklist)6440if(@forklist);6441}64426443 git_header_html();6444 git_print_page_nav('summary','',$head);64456446print"<div class=\"title\"> </div>\n";6447print"<table class=\"projects_list\">\n".6448"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n";6449unless($omit_owner) {6450print"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";6451}6452if(defined$cd{'rfc2822'}) {6453print"<tr id=\"metadata_lchange\"><td>last change</td>".6454"<td>".format_timestamp_html(\%cd)."</td></tr>\n";6455}64566457# use per project git URL list in $projectroot/$project/cloneurl6458# or make project git URL from git base URL and project name6459my$url_tag="URL";6460my@url_list= git_get_project_url_list($project);6461@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;6462foreachmy$git_url(@url_list) {6463next unless$git_url;6464print format_repo_url($url_tag,$git_url);6465$url_tag="";6466}64676468# Tag cloud6469my$show_ctags= gitweb_check_feature('ctags');6470if($show_ctags) {6471my$ctags= git_get_project_ctags($project);6472if(%$ctags) {6473# without ability to add tags, don't show if there are none6474my$cloud= git_populate_project_tagcloud($ctags);6475print"<tr id=\"metadata_ctags\">".6476"<td>content tags</td>".6477"<td>".git_show_project_tagcloud($cloud,48)."</td>".6478"</tr>\n";6479}6480}64816482print"</table>\n";64836484# If XSS prevention is on, we don't include README.html.6485# TODO: Allow a readme in some safe format.6486if(!$prevent_xss&& -s "$projectroot/$project/README.html") {6487print"<div class=\"title\">readme</div>\n".6488"<div class=\"readme\">\n";6489 insert_file("$projectroot/$project/README.html");6490print"\n</div>\n";# class="readme"6491}64926493# we need to request one more than 16 (0..15) to check if6494# those 16 are all6495my@commitlist=$head? parse_commits($head,17) : ();6496if(@commitlist) {6497 git_print_header_div('shortlog');6498 git_shortlog_body(\@commitlist,0,15,$refs,6499$#commitlist<=15?undef:6500$cgi->a({-href => href(action=>"shortlog")},"..."));6501}65026503if(@taglist) {6504 git_print_header_div('tags');6505 git_tags_body(\@taglist,0,15,6506$#taglist<=15?undef:6507$cgi->a({-href => href(action=>"tags")},"..."));6508}65096510if(@headlist) {6511 git_print_header_div('heads');6512 git_heads_body(\@headlist,$head,0,15,6513$#headlist<=15?undef:6514$cgi->a({-href => href(action=>"heads")},"..."));6515}65166517if(%remotedata) {6518 git_print_header_div('remotes');6519 git_remotes_body(\%remotedata,15,$head);6520}65216522if(@forklist) {6523 git_print_header_div('forks');6524 git_project_list_body(\@forklist,'age',0,15,6525$#forklist<=15?undef:6526$cgi->a({-href => href(action=>"forks")},"..."),6527'no_header');6528}65296530 git_footer_html();6531}65326533sub git_tag {6534my%tag= parse_tag($hash);65356536if(!%tag) {6537 die_error(404,"Unknown tag object");6538}65396540my$head= git_get_head_hash($project);6541 git_header_html();6542 git_print_page_nav('','',$head,undef,$head);6543 git_print_header_div('commit', esc_html($tag{'name'}),$hash);6544print"<div class=\"title_text\">\n".6545"<table class=\"object_header\">\n".6546"<tr>\n".6547"<td>object</td>\n".6548"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6549$tag{'object'}) ."</td>\n".6550"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6551$tag{'type'}) ."</td>\n".6552"</tr>\n";6553if(defined($tag{'author'})) {6554 git_print_authorship_rows(\%tag,'author');6555}6556print"</table>\n\n".6557"</div>\n";6558print"<div class=\"page_body\">";6559my$comment=$tag{'comment'};6560foreachmy$line(@$comment) {6561chomp$line;6562print esc_html($line, -nbsp=>1) ."<br/>\n";6563}6564print"</div>\n";6565 git_footer_html();6566}65676568sub git_blame_common {6569my$format=shift||'porcelain';6570if($formateq'porcelain'&&$input_params{'javascript'}) {6571$format='incremental';6572$action='blame_incremental';# for page title etc6573}65746575# permissions6576 gitweb_check_feature('blame')6577or die_error(403,"Blame view not allowed");65786579# error checking6580 die_error(400,"No file name given")unless$file_name;6581$hash_base||= git_get_head_hash($project);6582 die_error(404,"Couldn't find base commit")unless$hash_base;6583my%co= parse_commit($hash_base)6584or die_error(404,"Commit not found");6585my$ftype="blob";6586if(!defined$hash) {6587$hash= git_get_hash_by_path($hash_base,$file_name,"blob")6588or die_error(404,"Error looking up file");6589}else{6590$ftype= git_get_type($hash);6591if($ftype!~"blob") {6592 die_error(400,"Object is not a blob");6593}6594}65956596my$fd;6597if($formateq'incremental') {6598# get file contents (as base)6599open$fd,"-|", git_cmd(),'cat-file','blob',$hash6600or die_error(500,"Open git-cat-file failed");6601}elsif($formateq'data') {6602# run git-blame --incremental6603open$fd,"-|", git_cmd(),"blame","--incremental",6604$hash_base,"--",$file_name6605or die_error(500,"Open git-blame --incremental failed");6606}else{6607# run git-blame --porcelain6608open$fd,"-|", git_cmd(),"blame",'-p',6609$hash_base,'--',$file_name6610or die_error(500,"Open git-blame --porcelain failed");6611}66126613# incremental blame data returns early6614if($formateq'data') {6615print$cgi->header(6616-type=>"text/plain", -charset =>"utf-8",6617-status=>"200 OK");6618local$| =1;# output autoflush6619while(my$line= <$fd>) {6620print to_utf8($line);6621}6622close$fd6623or print"ERROR$!\n";66246625print'END';6626if(defined$t0&& gitweb_check_feature('timed')) {6627print' '.6628 tv_interval($t0, [ gettimeofday() ]).6629' '.$number_of_git_cmds;6630}6631print"\n";66326633return;6634}66356636# page header6637 git_header_html();6638my$formats_nav=6639$cgi->a({-href => href(action=>"blob", -replay=>1)},6640"blob") .6641" | ";6642if($formateq'incremental') {6643$formats_nav.=6644$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},6645"blame") ." (non-incremental)";6646}else{6647$formats_nav.=6648$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},6649"blame") ." (incremental)";6650}6651$formats_nav.=6652" | ".6653$cgi->a({-href => href(action=>"history", -replay=>1)},6654"history") .6655" | ".6656$cgi->a({-href => href(action=>$action, file_name=>$file_name)},6657"HEAD");6658 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6659 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6660 git_print_page_path($file_name,$ftype,$hash_base);66616662# page body6663if($formateq'incremental') {6664print"<noscript>\n<div class=\"error\"><center><b>\n".6665"This page requires JavaScript to run.\nUse ".6666$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},6667'this page').6668" instead.\n".6669"</b></center></div>\n</noscript>\n";66706671print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;6672}66736674print qq!<div class="page_body">\n!;6675print qq!<div id="progress_info">.../ ...</div>\n!6676if($formateq'incremental');6677print qq!<table id="blame_table"class="blame" width="100%">\n!.6678#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.6679 qq!<thead>\n!.6680 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.6681 qq!</thead>\n!.6682 qq!<tbody>\n!;66836684my@rev_color=qw(light dark);6685my$num_colors=scalar(@rev_color);6686my$current_color=0;66876688if($formateq'incremental') {6689my$color_class=$rev_color[$current_color];66906691#contents of a file6692my$linenr=0;6693 LINE:6694while(my$line= <$fd>) {6695chomp$line;6696$linenr++;66976698print qq!<tr id="l$linenr"class="$color_class">!.6699 qq!<td class="sha1"><a href=""> </a></td>!.6700 qq!<td class="linenr">!.6701 qq!<a class="linenr" href="">$linenr</a></td>!;6702print qq!<td class="pre">! . esc_html($line) ."</td>\n";6703print qq!</tr>\n!;6704}67056706}else{# porcelain, i.e. ordinary blame6707my%metainfo= ();# saves information about commits67086709# blame data6710 LINE:6711while(my$line= <$fd>) {6712chomp$line;6713# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]6714# no <lines in group> for subsequent lines in group of lines6715my($full_rev,$orig_lineno,$lineno,$group_size) =6716($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);6717if(!exists$metainfo{$full_rev}) {6718$metainfo{$full_rev} = {'nprevious'=>0};6719}6720my$meta=$metainfo{$full_rev};6721my$data;6722while($data= <$fd>) {6723chomp$data;6724last if($data=~s/^\t//);# contents of line6725if($data=~/^(\S+)(?: (.*))?$/) {6726$meta->{$1} =$2unlessexists$meta->{$1};6727}6728if($data=~/^previous /) {6729$meta->{'nprevious'}++;6730}6731}6732my$short_rev=substr($full_rev,0,8);6733my$author=$meta->{'author'};6734my%date=6735 parse_date($meta->{'author-time'},$meta->{'author-tz'});6736my$date=$date{'iso-tz'};6737if($group_size) {6738$current_color= ($current_color+1) %$num_colors;6739}6740my$tr_class=$rev_color[$current_color];6741$tr_class.=' boundary'if(exists$meta->{'boundary'});6742$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);6743$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);6744print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";6745if($group_size) {6746print"<td class=\"sha1\"";6747print" title=\"". esc_html($author) .",$date\"";6748print" rowspan=\"$group_size\""if($group_size>1);6749print">";6750print$cgi->a({-href => href(action=>"commit",6751 hash=>$full_rev,6752 file_name=>$file_name)},6753 esc_html($short_rev));6754if($group_size>=2) {6755my@author_initials= ($author=~/\b([[:upper:]])\B/g);6756if(@author_initials) {6757print"<br />".6758 esc_html(join('',@author_initials));6759# or join('.', ...)6760}6761}6762print"</td>\n";6763}6764# 'previous' <sha1 of parent commit> <filename at commit>6765if(exists$meta->{'previous'} &&6766$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {6767$meta->{'parent'} =$1;6768$meta->{'file_parent'} = unquote($2);6769}6770my$linenr_commit=6771exists($meta->{'parent'}) ?6772$meta->{'parent'} :$full_rev;6773my$linenr_filename=6774exists($meta->{'file_parent'}) ?6775$meta->{'file_parent'} : unquote($meta->{'filename'});6776my$blamed= href(action =>'blame',6777 file_name =>$linenr_filename,6778 hash_base =>$linenr_commit);6779print"<td class=\"linenr\">";6780print$cgi->a({ -href =>"$blamed#l$orig_lineno",6781-class=>"linenr"},6782 esc_html($lineno));6783print"</td>";6784print"<td class=\"pre\">". esc_html($data) ."</td>\n";6785print"</tr>\n";6786}# end while67876788}67896790# footer6791print"</tbody>\n".6792"</table>\n";# class="blame"6793print"</div>\n";# class="blame_body"6794close$fd6795or print"Reading blob failed\n";67966797 git_footer_html();6798}67996800sub git_blame {6801 git_blame_common();6802}68036804sub git_blame_incremental {6805 git_blame_common('incremental');6806}68076808sub git_blame_data {6809 git_blame_common('data');6810}68116812sub git_tags {6813my$head= git_get_head_hash($project);6814 git_header_html();6815 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6816 git_print_header_div('summary',$project);68176818my@tagslist= git_get_tags_list();6819if(@tagslist) {6820 git_tags_body(\@tagslist);6821}6822 git_footer_html();6823}68246825sub git_heads {6826my$head= git_get_head_hash($project);6827 git_header_html();6828 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6829 git_print_header_div('summary',$project);68306831my@headslist= git_get_heads_list();6832if(@headslist) {6833 git_heads_body(\@headslist,$head);6834}6835 git_footer_html();6836}68376838# used both for single remote view and for list of all the remotes6839sub git_remotes {6840 gitweb_check_feature('remote_heads')6841or die_error(403,"Remote heads view is disabled");68426843my$head= git_get_head_hash($project);6844my$remote=$input_params{'hash'};68456846my$remotedata= git_get_remotes_list($remote);6847 die_error(500,"Unable to get remote information")unlessdefined$remotedata;68486849unless(%$remotedata) {6850 die_error(404,defined$remote?6851"Remote$remotenot found":6852"No remotes found");6853}68546855 git_header_html(undef,undef, -action_extra =>$remote);6856 git_print_page_nav('','',$head,undef,$head,6857 format_ref_views($remote?'':'remotes'));68586859 fill_remote_heads($remotedata);6860if(defined$remote) {6861 git_print_header_div('remotes',"$remoteremote for$project");6862 git_remote_block($remote,$remotedata->{$remote},undef,$head);6863}else{6864 git_print_header_div('summary',"$projectremotes");6865 git_remotes_body($remotedata,undef,$head);6866}68676868 git_footer_html();6869}68706871sub git_blob_plain {6872my$type=shift;6873my$expires;68746875if(!defined$hash) {6876if(defined$file_name) {6877my$base=$hash_base|| git_get_head_hash($project);6878$hash= git_get_hash_by_path($base,$file_name,"blob")6879or die_error(404,"Cannot find file");6880}else{6881 die_error(400,"No file name defined");6882}6883}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6884# blobs defined by non-textual hash id's can be cached6885$expires="+1d";6886}68876888open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6889or die_error(500,"Open git-cat-file blob '$hash' failed");68906891# content-type (can include charset)6892$type= blob_contenttype($fd,$file_name,$type);68936894# "save as" filename, even when no $file_name is given6895my$save_as="$hash";6896if(defined$file_name) {6897$save_as=$file_name;6898}elsif($type=~m/^text\//) {6899$save_as.='.txt';6900}69016902# With XSS prevention on, blobs of all types except a few known safe6903# ones are served with "Content-Disposition: attachment" to make sure6904# they don't run in our security domain. For certain image types,6905# blob view writes an <img> tag referring to blob_plain view, and we6906# want to be sure not to break that by serving the image as an6907# attachment (though Firefox 3 doesn't seem to care).6908my$sandbox=$prevent_xss&&6909$type!~m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;69106911# serve text/* as text/plain6912if($prevent_xss&&6913($type=~m!^text/[a-z]+\b(.*)$!||6914($type=~m!^[a-z]+/[a-z]\+xml\b(.*)$!&& -T $fd))) {6915my$rest=$1;6916$rest=defined$rest?$rest:'';6917$type="text/plain$rest";6918}69196920print$cgi->header(6921-type =>$type,6922-expires =>$expires,6923-content_disposition =>6924($sandbox?'attachment':'inline')6925.'; filename="'.$save_as.'"');6926local$/=undef;6927binmode STDOUT,':raw';6928print<$fd>;6929binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6930close$fd;6931}69326933sub git_blob {6934my$expires;69356936if(!defined$hash) {6937if(defined$file_name) {6938my$base=$hash_base|| git_get_head_hash($project);6939$hash= git_get_hash_by_path($base,$file_name,"blob")6940or die_error(404,"Cannot find file");6941}else{6942 die_error(400,"No file name defined");6943}6944}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6945# blobs defined by non-textual hash id's can be cached6946$expires="+1d";6947}69486949my$have_blame= gitweb_check_feature('blame');6950open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6951or die_error(500,"Couldn't cat$file_name,$hash");6952my$mimetype= blob_mimetype($fd,$file_name);6953# use 'blob_plain' (aka 'raw') view for files that cannot be displayed6954if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {6955close$fd;6956return git_blob_plain($mimetype);6957}6958# we can have blame only for text/* mimetype6959$have_blame&&= ($mimetype=~m!^text/!);69606961my$highlight= gitweb_check_feature('highlight');6962my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);6963$fd= run_highlighter($fd,$highlight,$syntax)6964if$syntax;69656966 git_header_html(undef,$expires);6967my$formats_nav='';6968if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6969if(defined$file_name) {6970if($have_blame) {6971$formats_nav.=6972$cgi->a({-href => href(action=>"blame", -replay=>1)},6973"blame") .6974" | ";6975}6976$formats_nav.=6977$cgi->a({-href => href(action=>"history", -replay=>1)},6978"history") .6979" | ".6980$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6981"raw") .6982" | ".6983$cgi->a({-href => href(action=>"blob",6984 hash_base=>"HEAD", file_name=>$file_name)},6985"HEAD");6986}else{6987$formats_nav.=6988$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6989"raw");6990}6991 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6992 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6993}else{6994print"<div class=\"page_nav\">\n".6995"<br/><br/></div>\n".6996"<div class=\"title\">".esc_html($hash)."</div>\n";6997}6998 git_print_page_path($file_name,"blob",$hash_base);6999print"<div class=\"page_body\">\n";7000if($mimetype=~m!^image/!) {7001print qq!<img type="!.esc_attr($mimetype).qq!"!;7002if($file_name) {7003print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;7004}7005print qq! src="! .7006 href(action=>"blob_plain", hash=>$hash,7007 hash_base=>$hash_base, file_name=>$file_name) .7008 qq!"/>\n!;7009}else{7010my$nr;7011while(my$line= <$fd>) {7012chomp$line;7013$nr++;7014$line= untabify($line);7015printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,7016$nr, esc_attr(href(-replay =>1)),$nr,$nr,7017$syntax? sanitize($line) : esc_html($line, -nbsp=>1);7018}7019}7020close$fd7021or print"Reading blob failed.\n";7022print"</div>";7023 git_footer_html();7024}70257026sub git_tree {7027if(!defined$hash_base) {7028$hash_base="HEAD";7029}7030if(!defined$hash) {7031if(defined$file_name) {7032$hash= git_get_hash_by_path($hash_base,$file_name,"tree");7033}else{7034$hash=$hash_base;7035}7036}7037 die_error(404,"No such tree")unlessdefined($hash);70387039my$show_sizes= gitweb_check_feature('show-sizes');7040my$have_blame= gitweb_check_feature('blame');70417042my@entries= ();7043{7044local$/="\0";7045open my$fd,"-|", git_cmd(),"ls-tree",'-z',7046($show_sizes?'-l': ()),@extra_options,$hash7047or die_error(500,"Open git-ls-tree failed");7048@entries=map{chomp;$_} <$fd>;7049close$fd7050or die_error(404,"Reading tree failed");7051}70527053my$refs= git_get_references();7054my$ref= format_ref_marker($refs,$hash_base);7055 git_header_html();7056my$basedir='';7057if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7058my@views_nav= ();7059if(defined$file_name) {7060push@views_nav,7061$cgi->a({-href => href(action=>"history", -replay=>1)},7062"history"),7063$cgi->a({-href => href(action=>"tree",7064 hash_base=>"HEAD", file_name=>$file_name)},7065"HEAD"),7066}7067my$snapshot_links= format_snapshot_links($hash);7068if(defined$snapshot_links) {7069# FIXME: Should be available when we have no hash base as well.7070push@views_nav,$snapshot_links;7071}7072 git_print_page_nav('tree','',$hash_base,undef,undef,7073join(' | ',@views_nav));7074 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);7075}else{7076undef$hash_base;7077print"<div class=\"page_nav\">\n";7078print"<br/><br/></div>\n";7079print"<div class=\"title\">".esc_html($hash)."</div>\n";7080}7081if(defined$file_name) {7082$basedir=$file_name;7083if($basedirne''&&substr($basedir, -1)ne'/') {7084$basedir.='/';7085}7086 git_print_page_path($file_name,'tree',$hash_base);7087}7088print"<div class=\"page_body\">\n";7089print"<table class=\"tree\">\n";7090my$alternate=1;7091# '..' (top directory) link if possible7092if(defined$hash_base&&7093defined$file_name&&$file_name=~m![^/]+$!) {7094if($alternate) {7095print"<tr class=\"dark\">\n";7096}else{7097print"<tr class=\"light\">\n";7098}7099$alternate^=1;71007101my$up=$file_name;7102$up=~s!/?[^/]+$!!;7103undef$upunless$up;7104# based on git_print_tree_entry7105print'<td class="mode">'. mode_str('040000') ."</td>\n";7106print'<td class="size"> </td>'."\n"if$show_sizes;7107print'<td class="list">';7108print$cgi->a({-href => href(action=>"tree",7109 hash_base=>$hash_base,7110 file_name=>$up)},7111"..");7112print"</td>\n";7113print"<td class=\"link\"></td>\n";71147115print"</tr>\n";7116}7117foreachmy$line(@entries) {7118my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);71197120if($alternate) {7121print"<tr class=\"dark\">\n";7122}else{7123print"<tr class=\"light\">\n";7124}7125$alternate^=1;71267127 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);71287129print"</tr>\n";7130}7131print"</table>\n".7132"</div>";7133 git_footer_html();7134}71357136sub snapshot_name {7137my($project,$hash) =@_;71387139# path/to/project.git -> project7140# path/to/project/.git -> project7141my$name= to_utf8($project);7142$name=~ s,([^/])/*\.git$,$1,;7143$name= basename($name);7144# sanitize name7145$name=~s/[[:cntrl:]]/?/g;71467147my$ver=$hash;7148if($hash=~/^[0-9a-fA-F]+$/) {7149# shorten SHA-1 hash7150my$full_hash= git_get_full_hash($project,$hash);7151if($full_hash=~/^$hash/&&length($hash) >7) {7152$ver= git_get_short_hash($project,$hash);7153}7154}elsif($hash=~m!^refs/tags/(.*)$!) {7155# tags don't need shortened SHA-1 hash7156$ver=$1;7157}else{7158# branches and other need shortened SHA-1 hash7159if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {7160$ver=$1;7161}7162$ver.='-'. git_get_short_hash($project,$hash);7163}7164# in case of hierarchical branch names7165$ver=~s!/!.!g;71667167# name = project-version_string7168$name="$name-$ver";71697170returnwantarray? ($name,$name) :$name;7171}71727173sub exit_if_unmodified_since {7174my($latest_epoch) =@_;7175our$cgi;71767177my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7178if(defined$if_modified) {7179my$since;7180if(eval{require HTTP::Date;1; }) {7181$since= HTTP::Date::str2time($if_modified);7182}elsif(eval{require Time::ParseDate;1; }) {7183$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7184}7185if(defined$since&&$latest_epoch<=$since) {7186my%latest_date= parse_date($latest_epoch);7187print$cgi->header(7188-last_modified =>$latest_date{'rfc2822'},7189-status =>'304 Not Modified');7190goto DONE_GITWEB;7191}7192}7193}71947195sub git_snapshot {7196my$format=$input_params{'snapshot_format'};7197if(!@snapshot_fmts) {7198 die_error(403,"Snapshots not allowed");7199}7200# default to first supported snapshot format7201$format||=$snapshot_fmts[0];7202if($format!~m/^[a-z0-9]+$/) {7203 die_error(400,"Invalid snapshot format parameter");7204}elsif(!exists($known_snapshot_formats{$format})) {7205 die_error(400,"Unknown snapshot format");7206}elsif($known_snapshot_formats{$format}{'disabled'}) {7207 die_error(403,"Snapshot format not allowed");7208}elsif(!grep($_eq$format,@snapshot_fmts)) {7209 die_error(403,"Unsupported snapshot format");7210}72117212my$type= git_get_type("$hash^{}");7213if(!$type) {7214 die_error(404,'Object does not exist');7215}elsif($typeeq'blob') {7216 die_error(400,'Object is not a tree-ish');7217}72187219my($name,$prefix) = snapshot_name($project,$hash);7220my$filename="$name$known_snapshot_formats{$format}{'suffix'}";72217222my%co= parse_commit($hash);7223 exit_if_unmodified_since($co{'committer_epoch'})if%co;72247225my$cmd= quote_command(7226 git_cmd(),'archive',7227"--format=$known_snapshot_formats{$format}{'format'}",7228"--prefix=$prefix/",$hash);7229if(exists$known_snapshot_formats{$format}{'compressor'}) {7230$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});7231}72327233$filename=~s/(["\\])/\\$1/g;7234my%latest_date;7235if(%co) {7236%latest_date= parse_date($co{'committer_epoch'},$co{'committer_tz'});7237}72387239print$cgi->header(7240-type =>$known_snapshot_formats{$format}{'type'},7241-content_disposition =>'inline; filename="'.$filename.'"',7242%co? (-last_modified =>$latest_date{'rfc2822'}) : (),7243-status =>'200 OK');72447245open my$fd,"-|",$cmd7246or die_error(500,"Execute git-archive failed");7247binmode STDOUT,':raw';7248print<$fd>;7249binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi7250close$fd;7251}72527253sub git_log_generic {7254my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;72557256my$head= git_get_head_hash($project);7257if(!defined$base) {7258$base=$head;7259}7260if(!defined$page) {7261$page=0;7262}7263my$refs= git_get_references();72647265my$commit_hash=$base;7266if(defined$parent) {7267$commit_hash="$parent..$base";7268}7269my@commitlist=7270 parse_commits($commit_hash,101, (100*$page),7271defined$file_name? ($file_name,"--full-history") : ());72727273my$ftype;7274if(!defined$file_hash&&defined$file_name) {7275# some commits could have deleted file in question,7276# and not have it in tree, but one of them has to have it7277for(my$i=0;$i<@commitlist;$i++) {7278$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);7279last ifdefined$file_hash;7280}7281}7282if(defined$file_hash) {7283$ftype= git_get_type($file_hash);7284}7285if(defined$file_name&& !defined$ftype) {7286 die_error(500,"Unknown type of object");7287}7288my%co;7289if(defined$file_name) {7290%co= parse_commit($base)7291or die_error(404,"Unknown commit object");7292}729372947295my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);7296my$next_link='';7297if($#commitlist>=100) {7298$next_link=7299$cgi->a({-href => href(-replay=>1, page=>$page+1),7300-accesskey =>"n", -title =>"Alt-n"},"next");7301}7302my$patch_max= gitweb_get_feature('patches');7303if($patch_max&& !defined$file_name) {7304if($patch_max<0||@commitlist<=$patch_max) {7305$paging_nav.=" ⋅ ".7306$cgi->a({-href => href(action=>"patches", -replay=>1)},7307"patches");7308}7309}73107311 git_header_html();7312 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);7313if(defined$file_name) {7314 git_print_header_div('commit', esc_html($co{'title'}),$base);7315}else{7316 git_print_header_div('summary',$project)7317}7318 git_print_page_path($file_name,$ftype,$hash_base)7319if(defined$file_name);73207321$body_subr->(\@commitlist,0,99,$refs,$next_link,7322$file_name,$file_hash,$ftype);73237324 git_footer_html();7325}73267327sub git_log {7328 git_log_generic('log', \&git_log_body,7329$hash,$hash_parent);7330}73317332sub git_commit {7333$hash||=$hash_base||"HEAD";7334my%co= parse_commit($hash)7335or die_error(404,"Unknown commit object");73367337my$parent=$co{'parent'};7338my$parents=$co{'parents'};# listref73397340# we need to prepare $formats_nav before any parameter munging7341my$formats_nav;7342if(!defined$parent) {7343# --root commitdiff7344$formats_nav.='(initial)';7345}elsif(@$parents==1) {7346# single parent commit7347$formats_nav.=7348'(parent: '.7349$cgi->a({-href => href(action=>"commit",7350 hash=>$parent)},7351 esc_html(substr($parent,0,7))) .7352')';7353}else{7354# merge commit7355$formats_nav.=7356'(merge: '.7357join(' ',map{7358$cgi->a({-href => href(action=>"commit",7359 hash=>$_)},7360 esc_html(substr($_,0,7)));7361}@$parents) .7362')';7363}7364if(gitweb_check_feature('patches') &&@$parents<=1) {7365$formats_nav.=" | ".7366$cgi->a({-href => href(action=>"patch", -replay=>1)},7367"patch");7368}73697370if(!defined$parent) {7371$parent="--root";7372}7373my@difftree;7374open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",7375@diff_opts,7376(@$parents<=1?$parent:'-c'),7377$hash,"--"7378or die_error(500,"Open git-diff-tree failed");7379@difftree=map{chomp;$_} <$fd>;7380close$fdor die_error(404,"Reading git-diff-tree failed");73817382# non-textual hash id's can be cached7383my$expires;7384if($hash=~m/^[0-9a-fA-F]{40}$/) {7385$expires="+1d";7386}7387my$refs= git_get_references();7388my$ref= format_ref_marker($refs,$co{'id'});73897390 git_header_html(undef,$expires);7391 git_print_page_nav('commit','',7392$hash,$co{'tree'},$hash,7393$formats_nav);73947395if(defined$co{'parent'}) {7396 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);7397}else{7398 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);7399}7400print"<div class=\"title_text\">\n".7401"<table class=\"object_header\">\n";7402 git_print_authorship_rows(\%co);7403print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";7404print"<tr>".7405"<td>tree</td>".7406"<td class=\"sha1\">".7407$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),7408class=>"list"},$co{'tree'}) .7409"</td>".7410"<td class=\"link\">".7411$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},7412"tree");7413my$snapshot_links= format_snapshot_links($hash);7414if(defined$snapshot_links) {7415print" | ".$snapshot_links;7416}7417print"</td>".7418"</tr>\n";74197420foreachmy$par(@$parents) {7421print"<tr>".7422"<td>parent</td>".7423"<td class=\"sha1\">".7424$cgi->a({-href => href(action=>"commit", hash=>$par),7425class=>"list"},$par) .7426"</td>".7427"<td class=\"link\">".7428$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .7429" | ".7430$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .7431"</td>".7432"</tr>\n";7433}7434print"</table>".7435"</div>\n";74367437print"<div class=\"page_body\">\n";7438 git_print_log($co{'comment'});7439print"</div>\n";74407441 git_difftree_body(\@difftree,$hash,@$parents);74427443 git_footer_html();7444}74457446sub git_object {7447# object is defined by:7448# - hash or hash_base alone7449# - hash_base and file_name7450my$type;74517452# - hash or hash_base alone7453if($hash|| ($hash_base&& !defined$file_name)) {7454my$object_id=$hash||$hash_base;74557456open my$fd,"-|", quote_command(7457 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'7458or die_error(404,"Object does not exist");7459$type= <$fd>;7460chomp$type;7461close$fd7462or die_error(404,"Object does not exist");74637464# - hash_base and file_name7465}elsif($hash_base&&defined$file_name) {7466$file_name=~ s,/+$,,;74677468system(git_cmd(),"cat-file",'-e',$hash_base) ==07469or die_error(404,"Base object does not exist");74707471# here errors should not hapen7472open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name7473or die_error(500,"Open git-ls-tree failed");7474my$line= <$fd>;7475close$fd;74767477#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'7478unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {7479 die_error(404,"File or directory for given base does not exist");7480}7481$type=$2;7482$hash=$3;7483}else{7484 die_error(400,"Not enough information to find object");7485}74867487print$cgi->redirect(-uri => href(action=>$type, -full=>1,7488 hash=>$hash, hash_base=>$hash_base,7489 file_name=>$file_name),7490-status =>'302 Found');7491}74927493sub git_blobdiff {7494my$format=shift||'html';7495my$diff_style=$input_params{'diff_style'} ||'inline';74967497my$fd;7498my@difftree;7499my%diffinfo;7500my$expires;75017502# preparing $fd and %diffinfo for git_patchset_body7503# new style URI7504if(defined$hash_base&&defined$hash_parent_base) {7505if(defined$file_name) {7506# read raw output7507open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7508$hash_parent_base,$hash_base,7509"--", (defined$file_parent?$file_parent: ()),$file_name7510or die_error(500,"Open git-diff-tree failed");7511@difftree=map{chomp;$_} <$fd>;7512close$fd7513or die_error(404,"Reading git-diff-tree failed");7514@difftree7515or die_error(404,"Blob diff not found");75167517}elsif(defined$hash&&7518$hash=~/[0-9a-fA-F]{40}/) {7519# try to find filename from $hash75207521# read filtered raw output7522open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7523$hash_parent_base,$hash_base,"--"7524or die_error(500,"Open git-diff-tree failed");7525@difftree=7526# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'7527# $hash == to_id7528grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}7529map{chomp;$_} <$fd>;7530close$fd7531or die_error(404,"Reading git-diff-tree failed");7532@difftree7533or die_error(404,"Blob diff not found");75347535}else{7536 die_error(400,"Missing one of the blob diff parameters");7537}75387539if(@difftree>1) {7540 die_error(400,"Ambiguous blob diff specification");7541}75427543%diffinfo= parse_difftree_raw_line($difftree[0]);7544$file_parent||=$diffinfo{'from_file'} ||$file_name;7545$file_name||=$diffinfo{'to_file'};75467547$hash_parent||=$diffinfo{'from_id'};7548$hash||=$diffinfo{'to_id'};75497550# non-textual hash id's can be cached7551if($hash_base=~m/^[0-9a-fA-F]{40}$/&&7552$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {7553$expires='+1d';7554}75557556# open patch output7557open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7558'-p', ($formateq'html'?"--full-index": ()),7559$hash_parent_base,$hash_base,7560"--", (defined$file_parent?$file_parent: ()),$file_name7561or die_error(500,"Open git-diff-tree failed");7562}75637564# old/legacy style URI -- not generated anymore since 1.4.3.7565if(!%diffinfo) {7566 die_error('404 Not Found',"Missing one of the blob diff parameters")7567}75687569# header7570if($formateq'html') {7571my$formats_nav=7572$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},7573"raw");7574$formats_nav.= diff_style_nav($diff_style);7575 git_header_html(undef,$expires);7576if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7577 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7578 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7579}else{7580print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";7581print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";7582}7583if(defined$file_name) {7584 git_print_page_path($file_name,"blob",$hash_base);7585}else{7586print"<div class=\"page_path\"></div>\n";7587}75887589}elsif($formateq'plain') {7590print$cgi->header(7591-type =>'text/plain',7592-charset =>'utf-8',7593-expires =>$expires,7594-content_disposition =>'inline; filename="'."$file_name".'.patch"');75957596print"X-Git-Url: ".$cgi->self_url() ."\n\n";75977598}else{7599 die_error(400,"Unknown blobdiff format");7600}76017602# patch7603if($formateq'html') {7604print"<div class=\"page_body\">\n";76057606 git_patchset_body($fd,$diff_style,7607[ \%diffinfo],$hash_base,$hash_parent_base);7608close$fd;76097610print"</div>\n";# class="page_body"7611 git_footer_html();76127613}else{7614while(my$line= <$fd>) {7615$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;7616$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;76177618print$line;76197620last if$line=~m!^\+\+\+!;7621}7622local$/=undef;7623print<$fd>;7624close$fd;7625}7626}76277628sub git_blobdiff_plain {7629 git_blobdiff('plain');7630}76317632# assumes that it is added as later part of already existing navigation,7633# so it returns "| foo | bar" rather than just "foo | bar"7634sub diff_style_nav {7635my($diff_style,$is_combined) =@_;7636$diff_style||='inline';76377638return""if($is_combined);76397640my@styles= (inline =>'inline','sidebyside'=>'side by side');7641my%styles=@styles;7642@styles=7643@styles[map{$_*2}0..$#styles/2];76447645returnjoin'',7646map{" | ".$_}7647map{7648$_eq$diff_style?$styles{$_} :7649$cgi->a({-href => href(-replay=>1, diff_style =>$_)},$styles{$_})7650}@styles;7651}76527653sub git_commitdiff {7654my%params=@_;7655my$format=$params{-format} ||'html';7656my$diff_style=$input_params{'diff_style'} ||'inline';76577658my($patch_max) = gitweb_get_feature('patches');7659if($formateq'patch') {7660 die_error(403,"Patch view not allowed")unless$patch_max;7661}76627663$hash||=$hash_base||"HEAD";7664my%co= parse_commit($hash)7665or die_error(404,"Unknown commit object");76667667# choose format for commitdiff for merge7668if(!defined$hash_parent&& @{$co{'parents'}} >1) {7669$hash_parent='--cc';7670}7671# we need to prepare $formats_nav before almost any parameter munging7672my$formats_nav;7673if($formateq'html') {7674$formats_nav=7675$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},7676"raw");7677if($patch_max&& @{$co{'parents'}} <=1) {7678$formats_nav.=" | ".7679$cgi->a({-href => href(action=>"patch", -replay=>1)},7680"patch");7681}7682$formats_nav.= diff_style_nav($diff_style, @{$co{'parents'}} >1);76837684if(defined$hash_parent&&7685$hash_parentne'-c'&&$hash_parentne'--cc') {7686# commitdiff with two commits given7687my$hash_parent_short=$hash_parent;7688if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {7689$hash_parent_short=substr($hash_parent,0,7);7690}7691$formats_nav.=7692' (from';7693for(my$i=0;$i< @{$co{'parents'}};$i++) {7694if($co{'parents'}[$i]eq$hash_parent) {7695$formats_nav.=' parent '. ($i+1);7696last;7697}7698}7699$formats_nav.=': '.7700$cgi->a({-href => href(-replay=>1,7701 hash=>$hash_parent, hash_base=>undef)},7702 esc_html($hash_parent_short)) .7703')';7704}elsif(!$co{'parent'}) {7705# --root commitdiff7706$formats_nav.=' (initial)';7707}elsif(scalar@{$co{'parents'}} ==1) {7708# single parent commit7709$formats_nav.=7710' (parent: '.7711$cgi->a({-href => href(-replay=>1,7712 hash=>$co{'parent'}, hash_base=>undef)},7713 esc_html(substr($co{'parent'},0,7))) .7714')';7715}else{7716# merge commit7717if($hash_parenteq'--cc') {7718$formats_nav.=' | '.7719$cgi->a({-href => href(-replay=>1,7720 hash=>$hash, hash_parent=>'-c')},7721'combined');7722}else{# $hash_parent eq '-c'7723$formats_nav.=' | '.7724$cgi->a({-href => href(-replay=>1,7725 hash=>$hash, hash_parent=>'--cc')},7726'compact');7727}7728$formats_nav.=7729' (merge: '.7730join(' ',map{7731$cgi->a({-href => href(-replay=>1,7732 hash=>$_, hash_base=>undef)},7733 esc_html(substr($_,0,7)));7734} @{$co{'parents'}} ) .7735')';7736}7737}77387739my$hash_parent_param=$hash_parent;7740if(!defined$hash_parent_param) {7741# --cc for multiple parents, --root for parentless7742$hash_parent_param=7743@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';7744}77457746# read commitdiff7747my$fd;7748my@difftree;7749if($formateq'html') {7750open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7751"--no-commit-id","--patch-with-raw","--full-index",7752$hash_parent_param,$hash,"--"7753or die_error(500,"Open git-diff-tree failed");77547755while(my$line= <$fd>) {7756chomp$line;7757# empty line ends raw part of diff-tree output7758last unless$line;7759push@difftree,scalar parse_difftree_raw_line($line);7760}77617762}elsif($formateq'plain') {7763open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7764'-p',$hash_parent_param,$hash,"--"7765or die_error(500,"Open git-diff-tree failed");7766}elsif($formateq'patch') {7767# For commit ranges, we limit the output to the number of7768# patches specified in the 'patches' feature.7769# For single commits, we limit the output to a single patch,7770# diverging from the git-format-patch default.7771my@commit_spec= ();7772if($hash_parent) {7773if($patch_max>0) {7774push@commit_spec,"-$patch_max";7775}7776push@commit_spec,'-n',"$hash_parent..$hash";7777}else{7778if($params{-single}) {7779push@commit_spec,'-1';7780}else{7781if($patch_max>0) {7782push@commit_spec,"-$patch_max";7783}7784push@commit_spec,"-n";7785}7786push@commit_spec,'--root',$hash;7787}7788open$fd,"-|", git_cmd(),"format-patch",@diff_opts,7789'--encoding=utf8','--stdout',@commit_spec7790or die_error(500,"Open git-format-patch failed");7791}else{7792 die_error(400,"Unknown commitdiff format");7793}77947795# non-textual hash id's can be cached7796my$expires;7797if($hash=~m/^[0-9a-fA-F]{40}$/) {7798$expires="+1d";7799}78007801# write commit message7802if($formateq'html') {7803my$refs= git_get_references();7804my$ref= format_ref_marker($refs,$co{'id'});78057806 git_header_html(undef,$expires);7807 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);7808 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);7809print"<div class=\"title_text\">\n".7810"<table class=\"object_header\">\n";7811 git_print_authorship_rows(\%co);7812print"</table>".7813"</div>\n";7814print"<div class=\"page_body\">\n";7815if(@{$co{'comment'}} >1) {7816print"<div class=\"log\">\n";7817 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);7818print"</div>\n";# class="log"7819}78207821}elsif($formateq'plain') {7822my$refs= git_get_references("tags");7823my$tagname= git_get_rev_name_tags($hash);7824my$filename= basename($project) ."-$hash.patch";78257826print$cgi->header(7827-type =>'text/plain',7828-charset =>'utf-8',7829-expires =>$expires,7830-content_disposition =>'inline; filename="'."$filename".'"');7831my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});7832print"From: ". to_utf8($co{'author'}) ."\n";7833print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";7834print"Subject: ". to_utf8($co{'title'}) ."\n";78357836print"X-Git-Tag:$tagname\n"if$tagname;7837print"X-Git-Url: ".$cgi->self_url() ."\n\n";78387839foreachmy$line(@{$co{'comment'}}) {7840print to_utf8($line) ."\n";7841}7842print"---\n\n";7843}elsif($formateq'patch') {7844my$filename= basename($project) ."-$hash.patch";78457846print$cgi->header(7847-type =>'text/plain',7848-charset =>'utf-8',7849-expires =>$expires,7850-content_disposition =>'inline; filename="'."$filename".'"');7851}78527853# write patch7854if($formateq'html') {7855my$use_parents= !defined$hash_parent||7856$hash_parenteq'-c'||$hash_parenteq'--cc';7857 git_difftree_body(\@difftree,$hash,7858$use_parents? @{$co{'parents'}} :$hash_parent);7859print"<br/>\n";78607861 git_patchset_body($fd,$diff_style,7862 \@difftree,$hash,7863$use_parents? @{$co{'parents'}} :$hash_parent);7864close$fd;7865print"</div>\n";# class="page_body"7866 git_footer_html();78677868}elsif($formateq'plain') {7869local$/=undef;7870print<$fd>;7871close$fd7872or print"Reading git-diff-tree failed\n";7873}elsif($formateq'patch') {7874local$/=undef;7875print<$fd>;7876close$fd7877or print"Reading git-format-patch failed\n";7878}7879}78807881sub git_commitdiff_plain {7882 git_commitdiff(-format =>'plain');7883}78847885# format-patch-style patches7886sub git_patch {7887 git_commitdiff(-format =>'patch', -single =>1);7888}78897890sub git_patches {7891 git_commitdiff(-format =>'patch');7892}78937894sub git_history {7895 git_log_generic('history', \&git_history_body,7896$hash_base,$hash_parent_base,7897$file_name,$hash);7898}78997900sub git_search {7901$searchtype||='commit';79027903# check if appropriate features are enabled7904 gitweb_check_feature('search')7905or die_error(403,"Search is disabled");7906if($searchtypeeq'pickaxe') {7907# pickaxe may take all resources of your box and run for several minutes7908# with every query - so decide by yourself how public you make this feature7909 gitweb_check_feature('pickaxe')7910or die_error(403,"Pickaxe search is disabled");7911}7912if($searchtypeeq'grep') {7913# grep search might be potentially CPU-intensive, too7914 gitweb_check_feature('grep')7915or die_error(403,"Grep search is disabled");7916}79177918if(!defined$searchtext) {7919 die_error(400,"Text field is empty");7920}7921if(!defined$hash) {7922$hash= git_get_head_hash($project);7923}7924my%co= parse_commit($hash);7925if(!%co) {7926 die_error(404,"Unknown commit object");7927}7928if(!defined$page) {7929$page=0;7930}79317932if($searchtypeeq'commit'||7933$searchtypeeq'author'||7934$searchtypeeq'committer') {7935 git_search_message(%co);7936}elsif($searchtypeeq'pickaxe') {7937 git_search_changes(%co);7938}elsif($searchtypeeq'grep') {7939 git_search_files(%co);7940}else{7941 die_error(400,"Unknown search type");7942}7943}79447945sub git_search_help {7946 git_header_html();7947 git_print_page_nav('','',$hash,$hash,$hash);7948print<<EOT;7949<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without7950regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,7951the pattern entered is recognized as the POSIX extended7952<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case7953insensitive).</p>7954<dl>7955<dt><b>commit</b></dt>7956<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>7957EOT7958my$have_grep= gitweb_check_feature('grep');7959if($have_grep) {7960print<<EOT;7961<dt><b>grep</b></dt>7962<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing7963 a different one) are searched for the given pattern. On large trees, this search can take7964a while and put some strain on the server, so please use it with some consideration. Note that7965due to git-grep peculiarity, currently if regexp mode is turned off, the matches are7966case-sensitive.</dd>7967EOT7968}7969print<<EOT;7970<dt><b>author</b></dt>7971<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>7972<dt><b>committer</b></dt>7973<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>7974EOT7975my$have_pickaxe= gitweb_check_feature('pickaxe');7976if($have_pickaxe) {7977print<<EOT;7978<dt><b>pickaxe</b></dt>7979<dd>All commits that caused the string to appear or disappear from any file (changes that7980added, removed or "modified" the string) will be listed. This search can take a while and7981takes a lot of strain on the server, so please use it wisely. Note that since you may be7982interested even in changes just changing the case as well, this search is case sensitive.</dd>7983EOT7984}7985print"</dl>\n";7986 git_footer_html();7987}79887989sub git_shortlog {7990 git_log_generic('shortlog', \&git_shortlog_body,7991$hash,$hash_parent);7992}79937994## ......................................................................7995## feeds (RSS, Atom; OPML)79967997sub git_feed {7998my$format=shift||'atom';7999my$have_blame= gitweb_check_feature('blame');80008001# Atom: http://www.atomenabled.org/developers/syndication/8002# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ8003if($formatne'rss'&&$formatne'atom') {8004 die_error(400,"Unknown web feed format");8005}80068007# log/feed of current (HEAD) branch, log of given branch, history of file/directory8008my$head=$hash||'HEAD';8009my@commitlist= parse_commits($head,150,0,$file_name);80108011my%latest_commit;8012my%latest_date;8013my$content_type="application/$format+xml";8014if(defined$cgi->http('HTTP_ACCEPT') &&8015$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {8016# browser (feed reader) prefers text/xml8017$content_type='text/xml';8018}8019if(defined($commitlist[0])) {8020%latest_commit= %{$commitlist[0]};8021my$latest_epoch=$latest_commit{'committer_epoch'};8022 exit_if_unmodified_since($latest_epoch);8023%latest_date= parse_date($latest_epoch,$latest_commit{'comitter_tz'});8024}8025print$cgi->header(8026-type =>$content_type,8027-charset =>'utf-8',8028%latest_date? (-last_modified =>$latest_date{'rfc2822'}) : (),8029-status =>'200 OK');80308031# Optimization: skip generating the body if client asks only8032# for Last-Modified date.8033return if($cgi->request_method()eq'HEAD');80348035# header variables8036my$title="$site_name-$project/$action";8037my$feed_type='log';8038if(defined$hash) {8039$title.=" - '$hash'";8040$feed_type='branch log';8041if(defined$file_name) {8042$title.=" ::$file_name";8043$feed_type='history';8044}8045}elsif(defined$file_name) {8046$title.=" -$file_name";8047$feed_type='history';8048}8049$title.="$feed_type";8050my$descr= git_get_project_description($project);8051if(defined$descr) {8052$descr= esc_html($descr);8053}else{8054$descr="$project".8055($formateq'rss'?'RSS':'Atom') .8056" feed";8057}8058my$owner= git_get_project_owner($project);8059$owner= esc_html($owner);80608061#header8062my$alt_url;8063if(defined$file_name) {8064$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);8065}elsif(defined$hash) {8066$alt_url= href(-full=>1, action=>"log", hash=>$hash);8067}else{8068$alt_url= href(-full=>1, action=>"summary");8069}8070print qq!<?xml version="1.0" encoding="utf-8"?>\n!;8071if($formateq'rss') {8072print<<XML;8073<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">8074<channel>8075XML8076print"<title>$title</title>\n".8077"<link>$alt_url</link>\n".8078"<description>$descr</description>\n".8079"<language>en</language>\n".8080# project owner is responsible for 'editorial' content8081"<managingEditor>$owner</managingEditor>\n";8082if(defined$logo||defined$favicon) {8083# prefer the logo to the favicon, since RSS8084# doesn't allow both8085my$img= esc_url($logo||$favicon);8086print"<image>\n".8087"<url>$img</url>\n".8088"<title>$title</title>\n".8089"<link>$alt_url</link>\n".8090"</image>\n";8091}8092if(%latest_date) {8093print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";8094print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";8095}8096print"<generator>gitweb v.$version/$git_version</generator>\n";8097}elsif($formateq'atom') {8098print<<XML;8099<feed xmlns="http://www.w3.org/2005/Atom">8100XML8101print"<title>$title</title>\n".8102"<subtitle>$descr</subtitle>\n".8103'<link rel="alternate" type="text/html" href="'.8104$alt_url.'" />'."\n".8105'<link rel="self" type="'.$content_type.'" href="'.8106$cgi->self_url() .'" />'."\n".8107"<id>". href(-full=>1) ."</id>\n".8108# use project owner for feed author8109"<author><name>$owner</name></author>\n";8110if(defined$favicon) {8111print"<icon>". esc_url($favicon) ."</icon>\n";8112}8113if(defined$logo) {8114# not twice as wide as tall: 72 x 27 pixels8115print"<logo>". esc_url($logo) ."</logo>\n";8116}8117if(!%latest_date) {8118# dummy date to keep the feed valid until commits trickle in:8119print"<updated>1970-01-01T00:00:00Z</updated>\n";8120}else{8121print"<updated>$latest_date{'iso-8601'}</updated>\n";8122}8123print"<generator version='$version/$git_version'>gitweb</generator>\n";8124}81258126# contents8127for(my$i=0;$i<=$#commitlist;$i++) {8128my%co= %{$commitlist[$i]};8129my$commit=$co{'id'};8130# we read 150, we always show 30 and the ones more recent than 48 hours8131if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {8132last;8133}8134my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});81358136# get list of changed files8137open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,8138$co{'parent'} ||"--root",8139$co{'id'},"--", (defined$file_name?$file_name: ())8140ornext;8141my@difftree=map{chomp;$_} <$fd>;8142close$fd8143ornext;81448145# print element (entry, item)8146my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);8147if($formateq'rss') {8148print"<item>\n".8149"<title>". esc_html($co{'title'}) ."</title>\n".8150"<author>". esc_html($co{'author'}) ."</author>\n".8151"<pubDate>$cd{'rfc2822'}</pubDate>\n".8152"<guid isPermaLink=\"true\">$co_url</guid>\n".8153"<link>$co_url</link>\n".8154"<description>". esc_html($co{'title'}) ."</description>\n".8155"<content:encoded>".8156"<![CDATA[\n";8157}elsif($formateq'atom') {8158print"<entry>\n".8159"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".8160"<updated>$cd{'iso-8601'}</updated>\n".8161"<author>\n".8162" <name>". esc_html($co{'author_name'}) ."</name>\n";8163if($co{'author_email'}) {8164print" <email>". esc_html($co{'author_email'}) ."</email>\n";8165}8166print"</author>\n".8167# use committer for contributor8168"<contributor>\n".8169" <name>". esc_html($co{'committer_name'}) ."</name>\n";8170if($co{'committer_email'}) {8171print" <email>". esc_html($co{'committer_email'}) ."</email>\n";8172}8173print"</contributor>\n".8174"<published>$cd{'iso-8601'}</published>\n".8175"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".8176"<id>$co_url</id>\n".8177"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".8178"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";8179}8180my$comment=$co{'comment'};8181print"<pre>\n";8182foreachmy$line(@$comment) {8183$line= esc_html($line);8184print"$line\n";8185}8186print"</pre><ul>\n";8187foreachmy$difftree_line(@difftree) {8188my%difftree= parse_difftree_raw_line($difftree_line);8189next if!$difftree{'from_id'};81908191my$file=$difftree{'file'} ||$difftree{'to_file'};81928193print"<li>".8194"[".8195$cgi->a({-href => href(-full=>1, action=>"blobdiff",8196 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},8197 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},8198 file_name=>$file, file_parent=>$difftree{'from_file'}),8199-title =>"diff"},'D');8200if($have_blame) {8201print$cgi->a({-href => href(-full=>1, action=>"blame",8202 file_name=>$file, hash_base=>$commit),8203-title =>"blame"},'B');8204}8205# if this is not a feed of a file history8206if(!defined$file_name||$file_namene$file) {8207print$cgi->a({-href => href(-full=>1, action=>"history",8208 file_name=>$file, hash=>$commit),8209-title =>"history"},'H');8210}8211$file= esc_path($file);8212print"] ".8213"$file</li>\n";8214}8215if($formateq'rss') {8216print"</ul>]]>\n".8217"</content:encoded>\n".8218"</item>\n";8219}elsif($formateq'atom') {8220print"</ul>\n</div>\n".8221"</content>\n".8222"</entry>\n";8223}8224}82258226# end of feed8227if($formateq'rss') {8228print"</channel>\n</rss>\n";8229}elsif($formateq'atom') {8230print"</feed>\n";8231}8232}82338234sub git_rss {8235 git_feed('rss');8236}82378238sub git_atom {8239 git_feed('atom');8240}82418242sub git_opml {8243my@list= git_get_projects_list($project_filter,$strict_export);8244if(!@list) {8245 die_error(404,"No projects found");8246}82478248print$cgi->header(8249-type =>'text/xml',8250-charset =>'utf-8',8251-content_disposition =>'inline; filename="opml.xml"');82528253my$title= esc_html($site_name);8254my$filter=" within subdirectory ";8255if(defined$project_filter) {8256$filter.= esc_html($project_filter);8257}else{8258$filter="";8259}8260print<<XML;8261<?xml version="1.0" encoding="utf-8"?>8262<opml version="1.0">8263<head>8264 <title>$titleOPML Export$filter</title>8265</head>8266<body>8267<outline text="git RSS feeds">8268XML82698270foreachmy$pr(@list) {8271my%proj=%$pr;8272my$head= git_get_head_hash($proj{'path'});8273if(!defined$head) {8274next;8275}8276$git_dir="$projectroot/$proj{'path'}";8277my%co= parse_commit($head);8278if(!%co) {8279next;8280}82818282my$path= esc_html(chop_str($proj{'path'},25,5));8283my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);8284my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);8285print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";8286}8287print<<XML;8288</outline>8289</body>8290</opml>8291XML8292}