1#!/usr/bin/perl 2 3# gitweb - simple web interface to track changes in git repositories 4# 5# (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org> 6# (C) 2005, Christian Gierke 7# 8# This program is licensed under the GPLv2 9 10use5.008; 11use strict; 12use warnings; 13use CGI qw(:standard :escapeHTML -nosticky); 14use CGI::Util qw(unescape); 15use CGI::Carp qw(fatalsToBrowser set_message); 16use Encode; 17use Fcntl ':mode'; 18use File::Find qw(); 19use File::Basename qw(basename); 20use Time::HiRes qw(gettimeofday tv_interval); 21binmode STDOUT,':utf8'; 22 23our$t0= [ gettimeofday() ]; 24our$number_of_git_cmds=0; 25 26BEGIN{ 27 CGI->compile()if$ENV{'MOD_PERL'}; 28} 29 30our$version="++GIT_VERSION++"; 31 32our($my_url,$my_uri,$base_url,$path_info,$home_link); 33sub evaluate_uri { 34our$cgi; 35 36our$my_url=$cgi->url(); 37our$my_uri=$cgi->url(-absolute =>1); 38 39# Base URL for relative URLs in gitweb ($logo, $favicon, ...), 40# needed and used only for URLs with nonempty PATH_INFO 41our$base_url=$my_url; 42 43# When the script is used as DirectoryIndex, the URL does not contain the name 44# of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we 45# have to do it ourselves. We make $path_info global because it's also used 46# later on. 47# 48# Another issue with the script being the DirectoryIndex is that the resulting 49# $my_url data is not the full script URL: this is good, because we want 50# generated links to keep implying the script name if it wasn't explicitly 51# indicated in the URL we're handling, but it means that $my_url cannot be used 52# as base URL. 53# Therefore, if we needed to strip PATH_INFO, then we know that we have 54# to build the base URL ourselves: 55our$path_info=$ENV{"PATH_INFO"}; 56if($path_info) { 57if($my_url=~ s,\Q$path_info\E$,, && 58$my_uri=~ s,\Q$path_info\E$,, && 59defined$ENV{'SCRIPT_NAME'}) { 60$base_url=$cgi->url(-base =>1) .$ENV{'SCRIPT_NAME'}; 61} 62} 63 64# target of the home link on top of all pages 65our$home_link=$my_uri||"/"; 66} 67 68# core git executable to use 69# this can just be "git" if your webserver has a sensible PATH 70our$GIT="++GIT_BINDIR++/git"; 71 72# absolute fs-path which will be prepended to the project path 73#our $projectroot = "/pub/scm"; 74our$projectroot="++GITWEB_PROJECTROOT++"; 75 76# fs traversing limit for getting project list 77# the number is relative to the projectroot 78our$project_maxdepth="++GITWEB_PROJECT_MAXDEPTH++"; 79 80# string of the home link on top of all pages 81our$home_link_str="++GITWEB_HOME_LINK_STR++"; 82 83# name of your site or organization to appear in page titles 84# replace this with something more descriptive for clearer bookmarks 85our$site_name="++GITWEB_SITENAME++" 86|| ($ENV{'SERVER_NAME'} ||"Untitled") ." Git"; 87 88# filename of html text to include at top of each page 89our$site_header="++GITWEB_SITE_HEADER++"; 90# html text to include at home page 91our$home_text="++GITWEB_HOMETEXT++"; 92# filename of html text to include at bottom of each page 93our$site_footer="++GITWEB_SITE_FOOTER++"; 94 95# URI of stylesheets 96our@stylesheets= ("++GITWEB_CSS++"); 97# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG. 98our$stylesheet=undef; 99# URI of GIT logo (72x27 size) 100our$logo="++GITWEB_LOGO++"; 101# URI of GIT favicon, assumed to be image/png type 102our$favicon="++GITWEB_FAVICON++"; 103# URI of gitweb.js (JavaScript code for gitweb) 104our$javascript="++GITWEB_JS++"; 105 106# URI and label (title) of GIT logo link 107#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/"; 108#our $logo_label = "git documentation"; 109our$logo_url="http://git-scm.com/"; 110our$logo_label="git homepage"; 111 112# source of projects list 113our$projects_list="++GITWEB_LIST++"; 114 115# the width (in characters) of the projects list "Description" column 116our$projects_list_description_width=25; 117 118# group projects by category on the projects list 119# (enabled if this variable evaluates to true) 120our$projects_list_group_categories=0; 121 122# default category if none specified 123# (leave the empty string for no category) 124our$project_list_default_category=""; 125 126# default order of projects list 127# valid values are none, project, descr, owner, and age 128our$default_projects_order="project"; 129 130# show repository only if this file exists 131# (only effective if this variable evaluates to true) 132our$export_ok="++GITWEB_EXPORT_OK++"; 133 134# show repository only if this subroutine returns true 135# when given the path to the project, for example: 136# sub { return -e "$_[0]/git-daemon-export-ok"; } 137our$export_auth_hook=undef; 138 139# only allow viewing of repositories also shown on the overview page 140our$strict_export="++GITWEB_STRICT_EXPORT++"; 141 142# list of git base URLs used for URL to where fetch project from, 143# i.e. full URL is "$git_base_url/$project" 144our@git_base_url_list=grep{$_ne''} ("++GITWEB_BASE_URL++"); 145 146# default blob_plain mimetype and default charset for text/plain blob 147our$default_blob_plain_mimetype='text/plain'; 148our$default_text_plain_charset=undef; 149 150# file to use for guessing MIME types before trying /etc/mime.types 151# (relative to the current git repository) 152our$mimetypes_file=undef; 153 154# assume this charset if line contains non-UTF-8 characters; 155# it should be valid encoding (see Encoding::Supported(3pm) for list), 156# for which encoding all byte sequences are valid, for example 157# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it 158# could be even 'utf-8' for the old behavior) 159our$fallback_encoding='latin1'; 160 161# rename detection options for git-diff and git-diff-tree 162# - default is '-M', with the cost proportional to 163# (number of removed files) * (number of new files). 164# - more costly is '-C' (which implies '-M'), with the cost proportional to 165# (number of changed files + number of removed files) * (number of new files) 166# - even more costly is '-C', '--find-copies-harder' with cost 167# (number of files in the original tree) * (number of new files) 168# - one might want to include '-B' option, e.g. '-B', '-M' 169our@diff_opts= ('-M');# taken from git_commit 170 171# Disables features that would allow repository owners to inject script into 172# the gitweb domain. 173our$prevent_xss=0; 174 175# Path to the highlight executable to use (must be the one from 176# http://www.andre-simon.de due to assumptions about parameters and output). 177# Useful if highlight is not installed on your webserver's PATH. 178# [Default: highlight] 179our$highlight_bin="++HIGHLIGHT_BIN++"; 180 181# information about snapshot formats that gitweb is capable of serving 182our%known_snapshot_formats= ( 183# name => { 184# 'display' => display name, 185# 'type' => mime type, 186# 'suffix' => filename suffix, 187# 'format' => --format for git-archive, 188# 'compressor' => [compressor command and arguments] 189# (array reference, optional) 190# 'disabled' => boolean (optional)} 191# 192'tgz'=> { 193'display'=>'tar.gz', 194'type'=>'application/x-gzip', 195'suffix'=>'.tar.gz', 196'format'=>'tar', 197'compressor'=> ['gzip','-n']}, 198 199'tbz2'=> { 200'display'=>'tar.bz2', 201'type'=>'application/x-bzip2', 202'suffix'=>'.tar.bz2', 203'format'=>'tar', 204'compressor'=> ['bzip2']}, 205 206'txz'=> { 207'display'=>'tar.xz', 208'type'=>'application/x-xz', 209'suffix'=>'.tar.xz', 210'format'=>'tar', 211'compressor'=> ['xz'], 212'disabled'=>1}, 213 214'zip'=> { 215'display'=>'zip', 216'type'=>'application/x-zip', 217'suffix'=>'.zip', 218'format'=>'zip'}, 219); 220 221# Aliases so we understand old gitweb.snapshot values in repository 222# configuration. 223our%known_snapshot_format_aliases= ( 224'gzip'=>'tgz', 225'bzip2'=>'tbz2', 226'xz'=>'txz', 227 228# backward compatibility: legacy gitweb config support 229'x-gzip'=>undef,'gz'=>undef, 230'x-bzip2'=>undef,'bz2'=>undef, 231'x-zip'=>undef,''=>undef, 232); 233 234# Pixel sizes for icons and avatars. If the default font sizes or lineheights 235# are changed, it may be appropriate to change these values too via 236# $GITWEB_CONFIG. 237our%avatar_size= ( 238'default'=>16, 239'double'=>32 240); 241 242# Used to set the maximum load that we will still respond to gitweb queries. 243# If server load exceed this value then return "503 server busy" error. 244# If gitweb cannot determined server load, it is taken to be 0. 245# Leave it undefined (or set to 'undef') to turn off load checking. 246our$maxload=300; 247 248# configuration for 'highlight' (http://www.andre-simon.de/) 249# match by basename 250our%highlight_basename= ( 251#'Program' => 'py', 252#'Library' => 'py', 253'SConstruct'=>'py',# SCons equivalent of Makefile 254'Makefile'=>'make', 255); 256# match by extension 257our%highlight_ext= ( 258# main extensions, defining name of syntax; 259# see files in /usr/share/highlight/langDefs/ directory 260map{$_=>$_} 261qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl sql make), 262# alternate extensions, see /etc/highlight/filetypes.conf 263'h'=>'c', 264map{$_=>'sh'}qw(bash zsh ksh), 265map{$_=>'cpp'}qw(cxx c++ cc), 266map{$_=>'php'}qw(php3 php4 php5 phps), 267map{$_=>'pl'}qw(perl pm),# perhaps also 'cgi' 268map{$_=>'make'}qw(mak mk), 269map{$_=>'xml'}qw(xhtml html htm), 270); 271 272# You define site-wide feature defaults here; override them with 273# $GITWEB_CONFIG as necessary. 274our%feature= ( 275# feature => { 276# 'sub' => feature-sub (subroutine), 277# 'override' => allow-override (boolean), 278# 'default' => [ default options...] (array reference)} 279# 280# if feature is overridable (it means that allow-override has true value), 281# then feature-sub will be called with default options as parameters; 282# return value of feature-sub indicates if to enable specified feature 283# 284# if there is no 'sub' key (no feature-sub), then feature cannot be 285# overridden 286# 287# use gitweb_get_feature(<feature>) to retrieve the <feature> value 288# (an array) or gitweb_check_feature(<feature>) to check if <feature> 289# is enabled 290 291# Enable the 'blame' blob view, showing the last commit that modified 292# each line in the file. This can be very CPU-intensive. 293 294# To enable system wide have in $GITWEB_CONFIG 295# $feature{'blame'}{'default'} = [1]; 296# To have project specific config enable override in $GITWEB_CONFIG 297# $feature{'blame'}{'override'} = 1; 298# and in project config gitweb.blame = 0|1; 299'blame'=> { 300'sub'=>sub{ feature_bool('blame',@_) }, 301'override'=>0, 302'default'=> [0]}, 303 304# Enable the 'snapshot' link, providing a compressed archive of any 305# tree. This can potentially generate high traffic if you have large 306# project. 307 308# Value is a list of formats defined in %known_snapshot_formats that 309# you wish to offer. 310# To disable system wide have in $GITWEB_CONFIG 311# $feature{'snapshot'}{'default'} = []; 312# To have project specific config enable override in $GITWEB_CONFIG 313# $feature{'snapshot'}{'override'} = 1; 314# and in project config, a comma-separated list of formats or "none" 315# to disable. Example: gitweb.snapshot = tbz2,zip; 316'snapshot'=> { 317'sub'=> \&feature_snapshot, 318'override'=>0, 319'default'=> ['tgz']}, 320 321# Enable text search, which will list the commits which match author, 322# committer or commit text to a given string. Enabled by default. 323# Project specific override is not supported. 324'search'=> { 325'override'=>0, 326'default'=> [1]}, 327 328# Enable grep search, which will list the files in currently selected 329# tree containing the given string. Enabled by default. This can be 330# potentially CPU-intensive, of course. 331# Note that you need to have 'search' feature enabled too. 332 333# To enable system wide have in $GITWEB_CONFIG 334# $feature{'grep'}{'default'} = [1]; 335# To have project specific config enable override in $GITWEB_CONFIG 336# $feature{'grep'}{'override'} = 1; 337# and in project config gitweb.grep = 0|1; 338'grep'=> { 339'sub'=>sub{ feature_bool('grep',@_) }, 340'override'=>0, 341'default'=> [1]}, 342 343# Enable the pickaxe search, which will list the commits that modified 344# a given string in a file. This can be practical and quite faster 345# alternative to 'blame', but still potentially CPU-intensive. 346# Note that you need to have 'search' feature enabled too. 347 348# To enable system wide have in $GITWEB_CONFIG 349# $feature{'pickaxe'}{'default'} = [1]; 350# To have project specific config enable override in $GITWEB_CONFIG 351# $feature{'pickaxe'}{'override'} = 1; 352# and in project config gitweb.pickaxe = 0|1; 353'pickaxe'=> { 354'sub'=>sub{ feature_bool('pickaxe',@_) }, 355'override'=>0, 356'default'=> [1]}, 357 358# Enable showing size of blobs in a 'tree' view, in a separate 359# column, similar to what 'ls -l' does. This cost a bit of IO. 360 361# To disable system wide have in $GITWEB_CONFIG 362# $feature{'show-sizes'}{'default'} = [0]; 363# To have project specific config enable override in $GITWEB_CONFIG 364# $feature{'show-sizes'}{'override'} = 1; 365# and in project config gitweb.showsizes = 0|1; 366'show-sizes'=> { 367'sub'=>sub{ feature_bool('showsizes',@_) }, 368'override'=>0, 369'default'=> [1]}, 370 371# Make gitweb use an alternative format of the URLs which can be 372# more readable and natural-looking: project name is embedded 373# directly in the path and the query string contains other 374# auxiliary information. All gitweb installations recognize 375# URL in either format; this configures in which formats gitweb 376# generates links. 377 378# To enable system wide have in $GITWEB_CONFIG 379# $feature{'pathinfo'}{'default'} = [1]; 380# Project specific override is not supported. 381 382# Note that you will need to change the default location of CSS, 383# favicon, logo and possibly other files to an absolute URL. Also, 384# if gitweb.cgi serves as your indexfile, you will need to force 385# $my_uri to contain the script name in your $GITWEB_CONFIG. 386'pathinfo'=> { 387'override'=>0, 388'default'=> [0]}, 389 390# Make gitweb consider projects in project root subdirectories 391# to be forks of existing projects. Given project $projname.git, 392# projects matching $projname/*.git will not be shown in the main 393# projects list, instead a '+' mark will be added to $projname 394# there and a 'forks' view will be enabled for the project, listing 395# all the forks. If project list is taken from a file, forks have 396# to be listed after the main project. 397 398# To enable system wide have in $GITWEB_CONFIG 399# $feature{'forks'}{'default'} = [1]; 400# Project specific override is not supported. 401'forks'=> { 402'override'=>0, 403'default'=> [0]}, 404 405# Insert custom links to the action bar of all project pages. 406# This enables you mainly to link to third-party scripts integrating 407# into gitweb; e.g. git-browser for graphical history representation 408# or custom web-based repository administration interface. 409 410# The 'default' value consists of a list of triplets in the form 411# (label, link, position) where position is the label after which 412# to insert the link and link is a format string where %n expands 413# to the project name, %f to the project path within the filesystem, 414# %h to the current hash (h gitweb parameter) and %b to the current 415# hash base (hb gitweb parameter); %% expands to %. 416 417# To enable system wide have in $GITWEB_CONFIG e.g. 418# $feature{'actions'}{'default'} = [('graphiclog', 419# '/git-browser/by-commit.html?r=%n', 'summary')]; 420# Project specific override is not supported. 421'actions'=> { 422'override'=>0, 423'default'=> []}, 424 425# Allow gitweb scan project content tags of project repository, 426# and display the popular Web 2.0-ish "tag cloud" near the projects 427# list. Note that this is something COMPLETELY different from the 428# normal Git tags. 429 430# gitweb by itself can show existing tags, but it does not handle 431# tagging itself; you need to do it externally, outside gitweb. 432# The format is described in git_get_project_ctags() subroutine. 433# You may want to install the HTML::TagCloud Perl module to get 434# a pretty tag cloud instead of just a list of tags. 435 436# To enable system wide have in $GITWEB_CONFIG 437# $feature{'ctags'}{'default'} = [1]; 438# Project specific override is not supported. 439 440# In the future whether ctags editing is enabled might depend 441# on the value, but using 1 should always mean no editing of ctags. 442'ctags'=> { 443'override'=>0, 444'default'=> [0]}, 445 446# The maximum number of patches in a patchset generated in patch 447# view. Set this to 0 or undef to disable patch view, or to a 448# negative number to remove any limit. 449 450# To disable system wide have in $GITWEB_CONFIG 451# $feature{'patches'}{'default'} = [0]; 452# To have project specific config enable override in $GITWEB_CONFIG 453# $feature{'patches'}{'override'} = 1; 454# and in project config gitweb.patches = 0|n; 455# where n is the maximum number of patches allowed in a patchset. 456'patches'=> { 457'sub'=> \&feature_patches, 458'override'=>0, 459'default'=> [16]}, 460 461# Avatar support. When this feature is enabled, views such as 462# shortlog or commit will display an avatar associated with 463# the email of the committer(s) and/or author(s). 464 465# Currently available providers are gravatar and picon. 466# If an unknown provider is specified, the feature is disabled. 467 468# Gravatar depends on Digest::MD5. 469# Picon currently relies on the indiana.edu database. 470 471# To enable system wide have in $GITWEB_CONFIG 472# $feature{'avatar'}{'default'} = ['<provider>']; 473# where <provider> is either gravatar or picon. 474# To have project specific config enable override in $GITWEB_CONFIG 475# $feature{'avatar'}{'override'} = 1; 476# and in project config gitweb.avatar = <provider>; 477'avatar'=> { 478'sub'=> \&feature_avatar, 479'override'=>0, 480'default'=> ['']}, 481 482# Enable displaying how much time and how many git commands 483# it took to generate and display page. Disabled by default. 484# Project specific override is not supported. 485'timed'=> { 486'override'=>0, 487'default'=> [0]}, 488 489# Enable turning some links into links to actions which require 490# JavaScript to run (like 'blame_incremental'). Not enabled by 491# default. Project specific override is currently not supported. 492'javascript-actions'=> { 493'override'=>0, 494'default'=> [0]}, 495 496# Enable and configure ability to change common timezone for dates 497# in gitweb output via JavaScript. Enabled by default. 498# Project specific override is not supported. 499'javascript-timezone'=> { 500'override'=>0, 501'default'=> [ 502'local',# default timezone: 'utc', 'local', or '(-|+)HHMM' format, 503# or undef to turn off this feature 504'gitweb_tz',# name of cookie where to store selected timezone 505'datetime',# CSS class used to mark up dates for manipulation 506]}, 507 508# Syntax highlighting support. This is based on Daniel Svensson's 509# and Sham Chukoury's work in gitweb-xmms2.git. 510# It requires the 'highlight' program present in $PATH, 511# and therefore is disabled by default. 512 513# To enable system wide have in $GITWEB_CONFIG 514# $feature{'highlight'}{'default'} = [1]; 515 516'highlight'=> { 517'sub'=>sub{ feature_bool('highlight',@_) }, 518'override'=>0, 519'default'=> [0]}, 520 521# Enable displaying of remote heads in the heads list 522 523# To enable system wide have in $GITWEB_CONFIG 524# $feature{'remote_heads'}{'default'} = [1]; 525# To have project specific config enable override in $GITWEB_CONFIG 526# $feature{'remote_heads'}{'override'} = 1; 527# and in project config gitweb.remote_heads = 0|1; 528'remote_heads'=> { 529'sub'=>sub{ feature_bool('remote_heads',@_) }, 530'override'=>0, 531'default'=> [0]}, 532); 533 534sub gitweb_get_feature { 535my($name) =@_; 536return unlessexists$feature{$name}; 537my($sub,$override,@defaults) = ( 538$feature{$name}{'sub'}, 539$feature{$name}{'override'}, 540@{$feature{$name}{'default'}}); 541# project specific override is possible only if we have project 542our$git_dir;# global variable, declared later 543if(!$override|| !defined$git_dir) { 544return@defaults; 545} 546if(!defined$sub) { 547warn"feature$nameis not overridable"; 548return@defaults; 549} 550return$sub->(@defaults); 551} 552 553# A wrapper to check if a given feature is enabled. 554# With this, you can say 555# 556# my $bool_feat = gitweb_check_feature('bool_feat'); 557# gitweb_check_feature('bool_feat') or somecode; 558# 559# instead of 560# 561# my ($bool_feat) = gitweb_get_feature('bool_feat'); 562# (gitweb_get_feature('bool_feat'))[0] or somecode; 563# 564sub gitweb_check_feature { 565return(gitweb_get_feature(@_))[0]; 566} 567 568 569sub feature_bool { 570my$key=shift; 571my($val) = git_get_project_config($key,'--bool'); 572 573if(!defined$val) { 574return($_[0]); 575}elsif($valeq'true') { 576return(1); 577}elsif($valeq'false') { 578return(0); 579} 580} 581 582sub feature_snapshot { 583my(@fmts) =@_; 584 585my($val) = git_get_project_config('snapshot'); 586 587if($val) { 588@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 589} 590 591return@fmts; 592} 593 594sub feature_patches { 595my@val= (git_get_project_config('patches','--int')); 596 597if(@val) { 598return@val; 599} 600 601return($_[0]); 602} 603 604sub feature_avatar { 605my@val= (git_get_project_config('avatar')); 606 607return@val?@val:@_; 608} 609 610# checking HEAD file with -e is fragile if the repository was 611# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 612# and then pruned. 613sub check_head_link { 614my($dir) =@_; 615my$headfile="$dir/HEAD"; 616return((-e $headfile) || 617(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 618} 619 620sub check_export_ok { 621my($dir) =@_; 622return(check_head_link($dir) && 623(!$export_ok|| -e "$dir/$export_ok") && 624(!$export_auth_hook||$export_auth_hook->($dir))); 625} 626 627# process alternate names for backward compatibility 628# filter out unsupported (unknown) snapshot formats 629sub filter_snapshot_fmts { 630my@fmts=@_; 631 632@fmts=map{ 633exists$known_snapshot_format_aliases{$_} ? 634$known_snapshot_format_aliases{$_} :$_}@fmts; 635@fmts=grep{ 636exists$known_snapshot_formats{$_} && 637!$known_snapshot_formats{$_}{'disabled'}}@fmts; 638} 639 640# If it is set to code reference, it is code that it is to be run once per 641# request, allowing updating configurations that change with each request, 642# while running other code in config file only once. 643# 644# Otherwise, if it is false then gitweb would process config file only once; 645# if it is true then gitweb config would be run for each request. 646our$per_request_config=1; 647 648# read and parse gitweb config file given by its parameter. 649# returns true on success, false on recoverable error, allowing 650# to chain this subroutine, using first file that exists. 651# dies on errors during parsing config file, as it is unrecoverable. 652sub read_config_file { 653my$filename=shift; 654return unlessdefined$filename; 655# die if there are errors parsing config file 656if(-e $filename) { 657do$filename; 658die$@if$@; 659return1; 660} 661return; 662} 663 664our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM,$GITWEB_CONFIG_COMMON); 665sub evaluate_gitweb_config { 666our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 667our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 668our$GITWEB_CONFIG_COMMON=$ENV{'GITWEB_CONFIG_COMMON'} ||"++GITWEB_CONFIG_COMMON++"; 669 670# Protect agains duplications of file names, to not read config twice. 671# Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so 672# there possibility of duplication of filename there doesn't matter. 673$GITWEB_CONFIG=""if($GITWEB_CONFIGeq$GITWEB_CONFIG_COMMON); 674$GITWEB_CONFIG_SYSTEM=""if($GITWEB_CONFIG_SYSTEMeq$GITWEB_CONFIG_COMMON); 675 676# Common system-wide settings for convenience. 677# Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM. 678 read_config_file($GITWEB_CONFIG_COMMON); 679 680# Use first config file that exists. This means use the per-instance 681# GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG. 682 read_config_file($GITWEB_CONFIG)andreturn; 683 read_config_file($GITWEB_CONFIG_SYSTEM); 684} 685 686# Get loadavg of system, to compare against $maxload. 687# Currently it requires '/proc/loadavg' present to get loadavg; 688# if it is not present it returns 0, which means no load checking. 689sub get_loadavg { 690if( -e '/proc/loadavg'){ 691open my$fd,'<','/proc/loadavg' 692orreturn0; 693my@load=split(/\s+/,scalar<$fd>); 694close$fd; 695 696# The first three columns measure CPU and IO utilization of the last one, 697# five, and 10 minute periods. The fourth column shows the number of 698# currently running processes and the total number of processes in the m/n 699# format. The last column displays the last process ID used. 700return$load[0] ||0; 701} 702# additional checks for load average should go here for things that don't export 703# /proc/loadavg 704 705return0; 706} 707 708# version of the core git binary 709our$git_version; 710sub evaluate_git_version { 711our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 712$number_of_git_cmds++; 713} 714 715sub check_loadavg { 716if(defined$maxload&& get_loadavg() >$maxload) { 717 die_error(503,"The load average on the server is too high"); 718} 719} 720 721# ====================================================================== 722# input validation and dispatch 723 724# input parameters can be collected from a variety of sources (presently, CGI 725# and PATH_INFO), so we define an %input_params hash that collects them all 726# together during validation: this allows subsequent uses (e.g. href()) to be 727# agnostic of the parameter origin 728 729our%input_params= (); 730 731# input parameters are stored with the long parameter name as key. This will 732# also be used in the href subroutine to convert parameters to their CGI 733# equivalent, and since the href() usage is the most frequent one, we store 734# the name -> CGI key mapping here, instead of the reverse. 735# 736# XXX: Warning: If you touch this, check the search form for updating, 737# too. 738 739our@cgi_param_mapping= ( 740 project =>"p", 741 action =>"a", 742 file_name =>"f", 743 file_parent =>"fp", 744 hash =>"h", 745 hash_parent =>"hp", 746 hash_base =>"hb", 747 hash_parent_base =>"hpb", 748 page =>"pg", 749 order =>"o", 750 searchtext =>"s", 751 searchtype =>"st", 752 snapshot_format =>"sf", 753 extra_options =>"opt", 754 search_use_regexp =>"sr", 755 ctag =>"by_tag", 756# this must be last entry (for manipulation from JavaScript) 757 javascript =>"js" 758); 759our%cgi_param_mapping=@cgi_param_mapping; 760 761# we will also need to know the possible actions, for validation 762our%actions= ( 763"blame"=> \&git_blame, 764"blame_incremental"=> \&git_blame_incremental, 765"blame_data"=> \&git_blame_data, 766"blobdiff"=> \&git_blobdiff, 767"blobdiff_plain"=> \&git_blobdiff_plain, 768"blob"=> \&git_blob, 769"blob_plain"=> \&git_blob_plain, 770"commitdiff"=> \&git_commitdiff, 771"commitdiff_plain"=> \&git_commitdiff_plain, 772"commit"=> \&git_commit, 773"forks"=> \&git_forks, 774"heads"=> \&git_heads, 775"history"=> \&git_history, 776"log"=> \&git_log, 777"patch"=> \&git_patch, 778"patches"=> \&git_patches, 779"remotes"=> \&git_remotes, 780"rss"=> \&git_rss, 781"atom"=> \&git_atom, 782"search"=> \&git_search, 783"search_help"=> \&git_search_help, 784"shortlog"=> \&git_shortlog, 785"summary"=> \&git_summary, 786"tag"=> \&git_tag, 787"tags"=> \&git_tags, 788"tree"=> \&git_tree, 789"snapshot"=> \&git_snapshot, 790"object"=> \&git_object, 791# those below don't need $project 792"opml"=> \&git_opml, 793"project_list"=> \&git_project_list, 794"project_index"=> \&git_project_index, 795); 796 797# finally, we have the hash of allowed extra_options for the commands that 798# allow them 799our%allowed_options= ( 800"--no-merges"=> [qw(rss atom log shortlog history)], 801); 802 803# fill %input_params with the CGI parameters. All values except for 'opt' 804# should be single values, but opt can be an array. We should probably 805# build an array of parameters that can be multi-valued, but since for the time 806# being it's only this one, we just single it out 807sub evaluate_query_params { 808our$cgi; 809 810while(my($name,$symbol) =each%cgi_param_mapping) { 811if($symboleq'opt') { 812$input_params{$name} = [$cgi->param($symbol) ]; 813}else{ 814$input_params{$name} =$cgi->param($symbol); 815} 816} 817} 818 819# now read PATH_INFO and update the parameter list for missing parameters 820sub evaluate_path_info { 821return ifdefined$input_params{'project'}; 822return if!$path_info; 823$path_info=~ s,^/+,,; 824return if!$path_info; 825 826# find which part of PATH_INFO is project 827my$project=$path_info; 828$project=~ s,/+$,,; 829while($project&& !check_head_link("$projectroot/$project")) { 830$project=~ s,/*[^/]*$,,; 831} 832return unless$project; 833$input_params{'project'} =$project; 834 835# do not change any parameters if an action is given using the query string 836return if$input_params{'action'}; 837$path_info=~ s,^\Q$project\E/*,,; 838 839# next, check if we have an action 840my$action=$path_info; 841$action=~ s,/.*$,,; 842if(exists$actions{$action}) { 843$path_info=~ s,^$action/*,,; 844$input_params{'action'} =$action; 845} 846 847# list of actions that want hash_base instead of hash, but can have no 848# pathname (f) parameter 849my@wants_base= ( 850'tree', 851'history', 852); 853 854# we want to catch, among others 855# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 856my($parentrefname,$parentpathname,$refname,$pathname) = 857($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/); 858 859# first, analyze the 'current' part 860if(defined$pathname) { 861# we got "branch:filename" or "branch:dir/" 862# we could use git_get_type(branch:pathname), but: 863# - it needs $git_dir 864# - it does a git() call 865# - the convention of terminating directories with a slash 866# makes it superfluous 867# - embedding the action in the PATH_INFO would make it even 868# more superfluous 869$pathname=~ s,^/+,,; 870if(!$pathname||substr($pathname, -1)eq"/") { 871$input_params{'action'} ||="tree"; 872$pathname=~ s,/$,,; 873}else{ 874# the default action depends on whether we had parent info 875# or not 876if($parentrefname) { 877$input_params{'action'} ||="blobdiff_plain"; 878}else{ 879$input_params{'action'} ||="blob_plain"; 880} 881} 882$input_params{'hash_base'} ||=$refname; 883$input_params{'file_name'} ||=$pathname; 884}elsif(defined$refname) { 885# we got "branch". In this case we have to choose if we have to 886# set hash or hash_base. 887# 888# Most of the actions without a pathname only want hash to be 889# set, except for the ones specified in @wants_base that want 890# hash_base instead. It should also be noted that hand-crafted 891# links having 'history' as an action and no pathname or hash 892# set will fail, but that happens regardless of PATH_INFO. 893if(defined$parentrefname) { 894# if there is parent let the default be 'shortlog' action 895# (for http://git.example.com/repo.git/A..B links); if there 896# is no parent, dispatch will detect type of object and set 897# action appropriately if required (if action is not set) 898$input_params{'action'} ||="shortlog"; 899} 900if($input_params{'action'} && 901grep{$_eq$input_params{'action'} }@wants_base) { 902$input_params{'hash_base'} ||=$refname; 903}else{ 904$input_params{'hash'} ||=$refname; 905} 906} 907 908# next, handle the 'parent' part, if present 909if(defined$parentrefname) { 910# a missing pathspec defaults to the 'current' filename, allowing e.g. 911# someproject/blobdiff/oldrev..newrev:/filename 912if($parentpathname) { 913$parentpathname=~ s,^/+,,; 914$parentpathname=~ s,/$,,; 915$input_params{'file_parent'} ||=$parentpathname; 916}else{ 917$input_params{'file_parent'} ||=$input_params{'file_name'}; 918} 919# we assume that hash_parent_base is wanted if a path was specified, 920# or if the action wants hash_base instead of hash 921if(defined$input_params{'file_parent'} || 922grep{$_eq$input_params{'action'} }@wants_base) { 923$input_params{'hash_parent_base'} ||=$parentrefname; 924}else{ 925$input_params{'hash_parent'} ||=$parentrefname; 926} 927} 928 929# for the snapshot action, we allow URLs in the form 930# $project/snapshot/$hash.ext 931# where .ext determines the snapshot and gets removed from the 932# passed $refname to provide the $hash. 933# 934# To be able to tell that $refname includes the format extension, we 935# require the following two conditions to be satisfied: 936# - the hash input parameter MUST have been set from the $refname part 937# of the URL (i.e. they must be equal) 938# - the snapshot format MUST NOT have been defined already (e.g. from 939# CGI parameter sf) 940# It's also useless to try any matching unless $refname has a dot, 941# so we check for that too 942if(defined$input_params{'action'} && 943$input_params{'action'}eq'snapshot'&& 944defined$refname&&index($refname,'.') != -1&& 945$refnameeq$input_params{'hash'} && 946!defined$input_params{'snapshot_format'}) { 947# We loop over the known snapshot formats, checking for 948# extensions. Allowed extensions are both the defined suffix 949# (which includes the initial dot already) and the snapshot 950# format key itself, with a prepended dot 951while(my($fmt,$opt) =each%known_snapshot_formats) { 952my$hash=$refname; 953unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 954next; 955} 956my$sfx=$1; 957# a valid suffix was found, so set the snapshot format 958# and reset the hash parameter 959$input_params{'snapshot_format'} =$fmt; 960$input_params{'hash'} =$hash; 961# we also set the format suffix to the one requested 962# in the URL: this way a request for e.g. .tgz returns 963# a .tgz instead of a .tar.gz 964$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 965last; 966} 967} 968} 969 970our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 971$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 972$searchtext,$search_regexp); 973sub evaluate_and_validate_params { 974our$action=$input_params{'action'}; 975if(defined$action) { 976if(!validate_action($action)) { 977 die_error(400,"Invalid action parameter"); 978} 979} 980 981# parameters which are pathnames 982our$project=$input_params{'project'}; 983if(defined$project) { 984if(!validate_project($project)) { 985undef$project; 986 die_error(404,"No such project"); 987} 988} 989 990our$file_name=$input_params{'file_name'}; 991if(defined$file_name) { 992if(!validate_pathname($file_name)) { 993 die_error(400,"Invalid file parameter"); 994} 995} 996 997our$file_parent=$input_params{'file_parent'}; 998if(defined$file_parent) { 999if(!validate_pathname($file_parent)) {1000 die_error(400,"Invalid file parent parameter");1001}1002}10031004# parameters which are refnames1005our$hash=$input_params{'hash'};1006if(defined$hash) {1007if(!validate_refname($hash)) {1008 die_error(400,"Invalid hash parameter");1009}1010}10111012our$hash_parent=$input_params{'hash_parent'};1013if(defined$hash_parent) {1014if(!validate_refname($hash_parent)) {1015 die_error(400,"Invalid hash parent parameter");1016}1017}10181019our$hash_base=$input_params{'hash_base'};1020if(defined$hash_base) {1021if(!validate_refname($hash_base)) {1022 die_error(400,"Invalid hash base parameter");1023}1024}10251026our@extra_options= @{$input_params{'extra_options'}};1027# @extra_options is always defined, since it can only be (currently) set from1028# CGI, and $cgi->param() returns the empty array in array context if the param1029# is not set1030foreachmy$opt(@extra_options) {1031if(not exists$allowed_options{$opt}) {1032 die_error(400,"Invalid option parameter");1033}1034if(not grep(/^$action$/, @{$allowed_options{$opt}})) {1035 die_error(400,"Invalid option parameter for this action");1036}1037}10381039our$hash_parent_base=$input_params{'hash_parent_base'};1040if(defined$hash_parent_base) {1041if(!validate_refname($hash_parent_base)) {1042 die_error(400,"Invalid hash parent base parameter");1043}1044}10451046# other parameters1047our$page=$input_params{'page'};1048if(defined$page) {1049if($page=~m/[^0-9]/) {1050 die_error(400,"Invalid page parameter");1051}1052}10531054our$searchtype=$input_params{'searchtype'};1055if(defined$searchtype) {1056if($searchtype=~m/[^a-z]/) {1057 die_error(400,"Invalid searchtype parameter");1058}1059}10601061our$search_use_regexp=$input_params{'search_use_regexp'};10621063our$searchtext=$input_params{'searchtext'};1064our$search_regexp;1065if(defined$searchtext) {1066if(length($searchtext) <2) {1067 die_error(403,"At least two characters are required for search parameter");1068}1069$search_regexp=$search_use_regexp?$searchtext:quotemeta$searchtext;1070}1071}10721073# path to the current git repository1074our$git_dir;1075sub evaluate_git_dir {1076our$git_dir="$projectroot/$project"if$project;1077}10781079our(@snapshot_fmts,$git_avatar);1080sub configure_gitweb_features {1081# list of supported snapshot formats1082our@snapshot_fmts= gitweb_get_feature('snapshot');1083@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);10841085# check that the avatar feature is set to a known provider name,1086# and for each provider check if the dependencies are satisfied.1087# if the provider name is invalid or the dependencies are not met,1088# reset $git_avatar to the empty string.1089our($git_avatar) = gitweb_get_feature('avatar');1090if($git_avatareq'gravatar') {1091$git_avatar=''unless(eval{require Digest::MD5;1; });1092}elsif($git_avatareq'picon') {1093# no dependencies1094}else{1095$git_avatar='';1096}1097}10981099# custom error handler: 'die <message>' is Internal Server Error1100sub handle_errors_html {1101my$msg=shift;# it is already HTML escaped11021103# to avoid infinite loop where error occurs in die_error,1104# change handler to default handler, disabling handle_errors_html1105 set_message("Error occured when inside die_error:\n$msg");11061107# you cannot jump out of die_error when called as error handler;1108# the subroutine set via CGI::Carp::set_message is called _after_1109# HTTP headers are already written, so it cannot write them itself1110 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1111}1112set_message(\&handle_errors_html);11131114# dispatch1115sub dispatch {1116if(!defined$action) {1117if(defined$hash) {1118$action= git_get_type($hash);1119}elsif(defined$hash_base&&defined$file_name) {1120$action= git_get_type("$hash_base:$file_name");1121}elsif(defined$project) {1122$action='summary';1123}else{1124$action='project_list';1125}1126}1127if(!defined($actions{$action})) {1128 die_error(400,"Unknown action");1129}1130if($action!~m/^(?:opml|project_list|project_index)$/&&1131!$project) {1132 die_error(400,"Project needed");1133}1134$actions{$action}->();1135}11361137sub reset_timer {1138our$t0= [ gettimeofday() ]1139ifdefined$t0;1140our$number_of_git_cmds=0;1141}11421143our$first_request=1;1144sub run_request {1145 reset_timer();11461147 evaluate_uri();1148if($first_request) {1149 evaluate_gitweb_config();1150 evaluate_git_version();1151}1152if($per_request_config) {1153if(ref($per_request_config)eq'CODE') {1154$per_request_config->();1155}elsif(!$first_request) {1156 evaluate_gitweb_config();1157}1158}1159 check_loadavg();11601161# $projectroot and $projects_list might be set in gitweb config file1162$projects_list||=$projectroot;11631164 evaluate_query_params();1165 evaluate_path_info();1166 evaluate_and_validate_params();1167 evaluate_git_dir();11681169 configure_gitweb_features();11701171 dispatch();1172}11731174our$is_last_request=sub{1};1175our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1176our$CGI='CGI';1177our$cgi;1178sub configure_as_fcgi {1179require CGI::Fast;1180our$CGI='CGI::Fast';11811182my$request_number=0;1183# let each child service 100 requests1184our$is_last_request=sub{ ++$request_number>100};1185}1186sub evaluate_argv {1187my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1188 configure_as_fcgi()1189if$script_name=~/\.fcgi$/;11901191return unless(@ARGV);11921193require Getopt::Long;1194 Getopt::Long::GetOptions(1195'fastcgi|fcgi|f'=> \&configure_as_fcgi,1196'nproc|n=i'=>sub{1197my($arg,$val) =@_;1198return unlesseval{require FCGI::ProcManager;1; };1199my$proc_manager= FCGI::ProcManager->new({1200 n_processes =>$val,1201});1202our$pre_listen_hook=sub{$proc_manager->pm_manage() };1203our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1204our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1205},1206);1207}12081209sub run {1210 evaluate_argv();12111212$first_request=1;1213$pre_listen_hook->()1214if$pre_listen_hook;12151216 REQUEST:1217while($cgi=$CGI->new()) {1218$pre_dispatch_hook->()1219if$pre_dispatch_hook;12201221 run_request();12221223$post_dispatch_hook->()1224if$post_dispatch_hook;1225$first_request=0;12261227last REQUEST if($is_last_request->());1228}12291230 DONE_GITWEB:12311;1232}12331234run();12351236if(defined caller) {1237# wrapped in a subroutine processing requests,1238# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1239return;1240}else{1241# pure CGI script, serving single request1242exit;1243}12441245## ======================================================================1246## action links12471248# possible values of extra options1249# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1250# -replay => 1 - start from a current view (replay with modifications)1251# -path_info => 0|1 - don't use/use path_info URL (if possible)1252# -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone1253sub href {1254my%params=@_;1255# default is to use -absolute url() i.e. $my_uri1256my$href=$params{-full} ?$my_url:$my_uri;12571258# implicit -replay, must be first of implicit params1259$params{-replay} =1if(keys%params==1&&$params{-anchor});12601261$params{'project'} =$projectunlessexists$params{'project'};12621263if($params{-replay}) {1264while(my($name,$symbol) =each%cgi_param_mapping) {1265if(!exists$params{$name}) {1266$params{$name} =$input_params{$name};1267}1268}1269}12701271my$use_pathinfo= gitweb_check_feature('pathinfo');1272if(defined$params{'project'} &&1273(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1274# try to put as many parameters as possible in PATH_INFO:1275# - project name1276# - action1277# - hash_parent or hash_parent_base:/file_parent1278# - hash or hash_base:/filename1279# - the snapshot_format as an appropriate suffix12801281# When the script is the root DirectoryIndex for the domain,1282# $href here would be something like http://gitweb.example.com/1283# Thus, we strip any trailing / from $href, to spare us double1284# slashes in the final URL1285$href=~ s,/$,,;12861287# Then add the project name, if present1288$href.="/".esc_path_info($params{'project'});1289delete$params{'project'};12901291# since we destructively absorb parameters, we keep this1292# boolean that remembers if we're handling a snapshot1293my$is_snapshot=$params{'action'}eq'snapshot';12941295# Summary just uses the project path URL, any other action is1296# added to the URL1297if(defined$params{'action'}) {1298$href.="/".esc_path_info($params{'action'})1299unless$params{'action'}eq'summary';1300delete$params{'action'};1301}13021303# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1304# stripping nonexistent or useless pieces1305$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1306||$params{'hash_parent'} ||$params{'hash'});1307if(defined$params{'hash_base'}) {1308if(defined$params{'hash_parent_base'}) {1309$href.= esc_path_info($params{'hash_parent_base'});1310# skip the file_parent if it's the same as the file_name1311if(defined$params{'file_parent'}) {1312if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1313delete$params{'file_parent'};1314}elsif($params{'file_parent'} !~/\.\./) {1315$href.=":/".esc_path_info($params{'file_parent'});1316delete$params{'file_parent'};1317}1318}1319$href.="..";1320delete$params{'hash_parent'};1321delete$params{'hash_parent_base'};1322}elsif(defined$params{'hash_parent'}) {1323$href.= esc_path_info($params{'hash_parent'})."..";1324delete$params{'hash_parent'};1325}13261327$href.= esc_path_info($params{'hash_base'});1328if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1329$href.=":/".esc_path_info($params{'file_name'});1330delete$params{'file_name'};1331}1332delete$params{'hash'};1333delete$params{'hash_base'};1334}elsif(defined$params{'hash'}) {1335$href.= esc_path_info($params{'hash'});1336delete$params{'hash'};1337}13381339# If the action was a snapshot, we can absorb the1340# snapshot_format parameter too1341if($is_snapshot) {1342my$fmt=$params{'snapshot_format'};1343# snapshot_format should always be defined when href()1344# is called, but just in case some code forgets, we1345# fall back to the default1346$fmt||=$snapshot_fmts[0];1347$href.=$known_snapshot_formats{$fmt}{'suffix'};1348delete$params{'snapshot_format'};1349}1350}13511352# now encode the parameters explicitly1353my@result= ();1354for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1355my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1356if(defined$params{$name}) {1357if(ref($params{$name})eq"ARRAY") {1358foreachmy$par(@{$params{$name}}) {1359push@result,$symbol."=". esc_param($par);1360}1361}else{1362push@result,$symbol."=". esc_param($params{$name});1363}1364}1365}1366$href.="?".join(';',@result)ifscalar@result;13671368# final transformation: trailing spaces must be escaped (URI-encoded)1369$href=~s/(\s+)$/CGI::escape($1)/e;13701371if($params{-anchor}) {1372$href.="#".esc_param($params{-anchor});1373}13741375return$href;1376}137713781379## ======================================================================1380## validation, quoting/unquoting and escaping13811382sub validate_action {1383my$input=shift||returnundef;1384returnundefunlessexists$actions{$input};1385return$input;1386}13871388sub validate_project {1389my$input=shift||returnundef;1390if(!validate_pathname($input) ||1391!(-d "$projectroot/$input") ||1392!check_export_ok("$projectroot/$input") ||1393($strict_export&& !project_in_list($input))) {1394returnundef;1395}else{1396return$input;1397}1398}13991400sub validate_pathname {1401my$input=shift||returnundef;14021403# no '.' or '..' as elements of path, i.e. no '.' nor '..'1404# at the beginning, at the end, and between slashes.1405# also this catches doubled slashes1406if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1407returnundef;1408}1409# no null characters1410if($input=~m!\0!) {1411returnundef;1412}1413return$input;1414}14151416sub validate_refname {1417my$input=shift||returnundef;14181419# textual hashes are O.K.1420if($input=~m/^[0-9a-fA-F]{40}$/) {1421return$input;1422}1423# it must be correct pathname1424$input= validate_pathname($input)1425orreturnundef;1426# restrictions on ref name according to git-check-ref-format1427if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1428returnundef;1429}1430return$input;1431}14321433# decode sequences of octets in utf8 into Perl's internal form,1434# which is utf-8 with utf8 flag set if needed. gitweb writes out1435# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1436sub to_utf8 {1437my$str=shift;1438returnundefunlessdefined$str;1439if(utf8::valid($str)) {1440 utf8::decode($str);1441return$str;1442}else{1443return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1444}1445}14461447# quote unsafe chars, but keep the slash, even when it's not1448# correct, but quoted slashes look too horrible in bookmarks1449sub esc_param {1450my$str=shift;1451returnundefunlessdefined$str;1452$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1453$str=~s/ /\+/g;1454return$str;1455}14561457# the quoting rules for path_info fragment are slightly different1458sub esc_path_info {1459my$str=shift;1460returnundefunlessdefined$str;14611462# path_info doesn't treat '+' as space (specially), but '?' must be escaped1463$str=~s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;14641465return$str;1466}14671468# quote unsafe chars in whole URL, so some characters cannot be quoted1469sub esc_url {1470my$str=shift;1471returnundefunlessdefined$str;1472$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1473$str=~s/ /\+/g;1474return$str;1475}14761477# quote unsafe characters in HTML attributes1478sub esc_attr {14791480# for XHTML conformance escaping '"' to '"' is not enough1481return esc_html(@_);1482}14831484# replace invalid utf8 character with SUBSTITUTION sequence1485sub esc_html {1486my$str=shift;1487my%opts=@_;14881489returnundefunlessdefined$str;14901491$str= to_utf8($str);1492$str=$cgi->escapeHTML($str);1493if($opts{'-nbsp'}) {1494$str=~s/ / /g;1495}1496$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1497return$str;1498}14991500# quote control characters and escape filename to HTML1501sub esc_path {1502my$str=shift;1503my%opts=@_;15041505returnundefunlessdefined$str;15061507$str= to_utf8($str);1508$str=$cgi->escapeHTML($str);1509if($opts{'-nbsp'}) {1510$str=~s/ / /g;1511}1512$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1513return$str;1514}15151516# Make control characters "printable", using character escape codes (CEC)1517sub quot_cec {1518my$cntrl=shift;1519my%opts=@_;1520my%es= (# character escape codes, aka escape sequences1521"\t"=>'\t',# tab (HT)1522"\n"=>'\n',# line feed (LF)1523"\r"=>'\r',# carrige return (CR)1524"\f"=>'\f',# form feed (FF)1525"\b"=>'\b',# backspace (BS)1526"\a"=>'\a',# alarm (bell) (BEL)1527"\e"=>'\e',# escape (ESC)1528"\013"=>'\v',# vertical tab (VT)1529"\000"=>'\0',# nul character (NUL)1530);1531my$chr= ( (exists$es{$cntrl})1532?$es{$cntrl}1533:sprintf('\%2x',ord($cntrl)) );1534if($opts{-nohtml}) {1535return$chr;1536}else{1537return"<span class=\"cntrl\">$chr</span>";1538}1539}15401541# Alternatively use unicode control pictures codepoints,1542# Unicode "printable representation" (PR)1543sub quot_upr {1544my$cntrl=shift;1545my%opts=@_;15461547my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1548if($opts{-nohtml}) {1549return$chr;1550}else{1551return"<span class=\"cntrl\">$chr</span>";1552}1553}15541555# git may return quoted and escaped filenames1556sub unquote {1557my$str=shift;15581559sub unq {1560my$seq=shift;1561my%es= (# character escape codes, aka escape sequences1562't'=>"\t",# tab (HT, TAB)1563'n'=>"\n",# newline (NL)1564'r'=>"\r",# return (CR)1565'f'=>"\f",# form feed (FF)1566'b'=>"\b",# backspace (BS)1567'a'=>"\a",# alarm (bell) (BEL)1568'e'=>"\e",# escape (ESC)1569'v'=>"\013",# vertical tab (VT)1570);15711572if($seq=~m/^[0-7]{1,3}$/) {1573# octal char sequence1574returnchr(oct($seq));1575}elsif(exists$es{$seq}) {1576# C escape sequence, aka character escape code1577return$es{$seq};1578}1579# quoted ordinary character1580return$seq;1581}15821583if($str=~m/^"(.*)"$/) {1584# needs unquoting1585$str=$1;1586$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1587}1588return$str;1589}15901591# escape tabs (convert tabs to spaces)1592sub untabify {1593my$line=shift;15941595while((my$pos=index($line,"\t")) != -1) {1596if(my$count= (8- ($pos%8))) {1597my$spaces=' ' x $count;1598$line=~s/\t/$spaces/;1599}1600}16011602return$line;1603}16041605sub project_in_list {1606my$project=shift;1607my@list= git_get_projects_list();1608return@list&&scalar(grep{$_->{'path'}eq$project}@list);1609}16101611## ----------------------------------------------------------------------1612## HTML aware string manipulation16131614# Try to chop given string on a word boundary between position1615# $len and $len+$add_len. If there is no word boundary there,1616# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1617# (marking chopped part) would be longer than given string.1618sub chop_str {1619my$str=shift;1620my$len=shift;1621my$add_len=shift||10;1622my$where=shift||'right';# 'left' | 'center' | 'right'16231624# Make sure perl knows it is utf8 encoded so we don't1625# cut in the middle of a utf8 multibyte char.1626$str= to_utf8($str);16271628# allow only $len chars, but don't cut a word if it would fit in $add_len1629# if it doesn't fit, cut it if it's still longer than the dots we would add1630# remove chopped character entities entirely16311632# when chopping in the middle, distribute $len into left and right part1633# return early if chopping wouldn't make string shorter1634if($whereeq'center') {1635return$strif($len+5>=length($str));# filler is length 51636$len=int($len/2);1637}else{1638return$strif($len+4>=length($str));# filler is length 41639}16401641# regexps: ending and beginning with word part up to $add_len1642my$endre=qr/.{$len}\w{0,$add_len}/;1643my$begre=qr/\w{0,$add_len}.{$len}/;16441645if($whereeq'left') {1646$str=~m/^(.*?)($begre)$/;1647my($lead,$body) = ($1,$2);1648if(length($lead) >4) {1649$lead=" ...";1650}1651return"$lead$body";16521653}elsif($whereeq'center') {1654$str=~m/^($endre)(.*)$/;1655my($left,$str) = ($1,$2);1656$str=~m/^(.*?)($begre)$/;1657my($mid,$right) = ($1,$2);1658if(length($mid) >5) {1659$mid=" ... ";1660}1661return"$left$mid$right";16621663}else{1664$str=~m/^($endre)(.*)$/;1665my$body=$1;1666my$tail=$2;1667if(length($tail) >4) {1668$tail="... ";1669}1670return"$body$tail";1671}1672}16731674# takes the same arguments as chop_str, but also wraps a <span> around the1675# result with a title attribute if it does get chopped. Additionally, the1676# string is HTML-escaped.1677sub chop_and_escape_str {1678my($str) =@_;16791680my$chopped= chop_str(@_);1681if($choppedeq$str) {1682return esc_html($chopped);1683}else{1684$str=~s/[[:cntrl:]]/?/g;1685return$cgi->span({-title=>$str}, esc_html($chopped));1686}1687}16881689## ----------------------------------------------------------------------1690## functions returning short strings16911692# CSS class for given age value (in seconds)1693sub age_class {1694my$age=shift;16951696if(!defined$age) {1697return"noage";1698}elsif($age<60*60*2) {1699return"age0";1700}elsif($age<60*60*24*2) {1701return"age1";1702}else{1703return"age2";1704}1705}17061707# convert age in seconds to "nn units ago" string1708sub age_string {1709my$age=shift;1710my$age_str;17111712if($age>60*60*24*365*2) {1713$age_str= (int$age/60/60/24/365);1714$age_str.=" years ago";1715}elsif($age>60*60*24*(365/12)*2) {1716$age_str=int$age/60/60/24/(365/12);1717$age_str.=" months ago";1718}elsif($age>60*60*24*7*2) {1719$age_str=int$age/60/60/24/7;1720$age_str.=" weeks ago";1721}elsif($age>60*60*24*2) {1722$age_str=int$age/60/60/24;1723$age_str.=" days ago";1724}elsif($age>60*60*2) {1725$age_str=int$age/60/60;1726$age_str.=" hours ago";1727}elsif($age>60*2) {1728$age_str=int$age/60;1729$age_str.=" min ago";1730}elsif($age>2) {1731$age_str=int$age;1732$age_str.=" sec ago";1733}else{1734$age_str.=" right now";1735}1736return$age_str;1737}17381739useconstant{1740 S_IFINVALID =>0030000,1741 S_IFGITLINK =>0160000,1742};17431744# submodule/subproject, a commit object reference1745sub S_ISGITLINK {1746my$mode=shift;17471748return(($mode& S_IFMT) == S_IFGITLINK)1749}17501751# convert file mode in octal to symbolic file mode string1752sub mode_str {1753my$mode=oct shift;17541755if(S_ISGITLINK($mode)) {1756return'm---------';1757}elsif(S_ISDIR($mode& S_IFMT)) {1758return'drwxr-xr-x';1759}elsif(S_ISLNK($mode)) {1760return'lrwxrwxrwx';1761}elsif(S_ISREG($mode)) {1762# git cares only about the executable bit1763if($mode& S_IXUSR) {1764return'-rwxr-xr-x';1765}else{1766return'-rw-r--r--';1767};1768}else{1769return'----------';1770}1771}17721773# convert file mode in octal to file type string1774sub file_type {1775my$mode=shift;17761777if($mode!~m/^[0-7]+$/) {1778return$mode;1779}else{1780$mode=oct$mode;1781}17821783if(S_ISGITLINK($mode)) {1784return"submodule";1785}elsif(S_ISDIR($mode& S_IFMT)) {1786return"directory";1787}elsif(S_ISLNK($mode)) {1788return"symlink";1789}elsif(S_ISREG($mode)) {1790return"file";1791}else{1792return"unknown";1793}1794}17951796# convert file mode in octal to file type description string1797sub file_type_long {1798my$mode=shift;17991800if($mode!~m/^[0-7]+$/) {1801return$mode;1802}else{1803$mode=oct$mode;1804}18051806if(S_ISGITLINK($mode)) {1807return"submodule";1808}elsif(S_ISDIR($mode& S_IFMT)) {1809return"directory";1810}elsif(S_ISLNK($mode)) {1811return"symlink";1812}elsif(S_ISREG($mode)) {1813if($mode& S_IXUSR) {1814return"executable";1815}else{1816return"file";1817};1818}else{1819return"unknown";1820}1821}182218231824## ----------------------------------------------------------------------1825## functions returning short HTML fragments, or transforming HTML fragments1826## which don't belong to other sections18271828# format line of commit message.1829sub format_log_line_html {1830my$line=shift;18311832$line= esc_html($line, -nbsp=>1);1833$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1834$cgi->a({-href => href(action=>"object", hash=>$1),1835-class=>"text"},$1);1836}eg;18371838return$line;1839}18401841# format marker of refs pointing to given object18421843# the destination action is chosen based on object type and current context:1844# - for annotated tags, we choose the tag view unless it's the current view1845# already, in which case we go to shortlog view1846# - for other refs, we keep the current view if we're in history, shortlog or1847# log view, and select shortlog otherwise1848sub format_ref_marker {1849my($refs,$id) =@_;1850my$markers='';18511852if(defined$refs->{$id}) {1853foreachmy$ref(@{$refs->{$id}}) {1854# this code exploits the fact that non-lightweight tags are the1855# only indirect objects, and that they are the only objects for which1856# we want to use tag instead of shortlog as action1857my($type,$name) =qw();1858my$indirect= ($ref=~s/\^\{\}$//);1859# e.g. tags/v2.6.11 or heads/next1860if($ref=~m!^(.*?)s?/(.*)$!) {1861$type=$1;1862$name=$2;1863}else{1864$type="ref";1865$name=$ref;1866}18671868my$class=$type;1869$class.=" indirect"if$indirect;18701871my$dest_action="shortlog";18721873if($indirect) {1874$dest_action="tag"unless$actioneq"tag";1875}elsif($action=~/^(history|(short)?log)$/) {1876$dest_action=$action;1877}18781879my$dest="";1880$dest.="refs/"unless$ref=~ m!^refs/!;1881$dest.=$ref;18821883my$link=$cgi->a({1884-href => href(1885 action=>$dest_action,1886 hash=>$dest1887)},$name);18881889$markers.=" <span class=\"".esc_attr($class)."\"title=\"".esc_attr($ref)."\">".1890$link."</span>";1891}1892}18931894if($markers) {1895return' <span class="refs">'.$markers.'</span>';1896}else{1897return"";1898}1899}19001901# format, perhaps shortened and with markers, title line1902sub format_subject_html {1903my($long,$short,$href,$extra) =@_;1904$extra=''unlessdefined($extra);19051906if(length($short) <length($long)) {1907$long=~s/[[:cntrl:]]/?/g;1908return$cgi->a({-href =>$href, -class=>"list subject",1909-title => to_utf8($long)},1910 esc_html($short)) .$extra;1911}else{1912return$cgi->a({-href =>$href, -class=>"list subject"},1913 esc_html($long)) .$extra;1914}1915}19161917# Rather than recomputing the url for an email multiple times, we cache it1918# after the first hit. This gives a visible benefit in views where the avatar1919# for the same email is used repeatedly (e.g. shortlog).1920# The cache is shared by all avatar engines (currently gravatar only), which1921# are free to use it as preferred. Since only one avatar engine is used for any1922# given page, there's no risk for cache conflicts.1923our%avatar_cache= ();19241925# Compute the picon url for a given email, by using the picon search service over at1926# http://www.cs.indiana.edu/picons/search.html1927sub picon_url {1928my$email=lc shift;1929if(!$avatar_cache{$email}) {1930my($user,$domain) =split('@',$email);1931$avatar_cache{$email} =1932"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1933"$domain/$user/".1934"users+domains+unknown/up/single";1935}1936return$avatar_cache{$email};1937}19381939# Compute the gravatar url for a given email, if it's not in the cache already.1940# Gravatar stores only the part of the URL before the size, since that's the1941# one computationally more expensive. This also allows reuse of the cache for1942# different sizes (for this particular engine).1943sub gravatar_url {1944my$email=lc shift;1945my$size=shift;1946$avatar_cache{$email} ||=1947"http://www.gravatar.com/avatar/".1948 Digest::MD5::md5_hex($email) ."?s=";1949return$avatar_cache{$email} .$size;1950}19511952# Insert an avatar for the given $email at the given $size if the feature1953# is enabled.1954sub git_get_avatar {1955my($email,%opts) =@_;1956my$pre_white= ($opts{-pad_before} ?" ":"");1957my$post_white= ($opts{-pad_after} ?" ":"");1958$opts{-size} ||='default';1959my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1960my$url="";1961if($git_avatareq'gravatar') {1962$url= gravatar_url($email,$size);1963}elsif($git_avatareq'picon') {1964$url= picon_url($email);1965}1966# Other providers can be added by extending the if chain, defining $url1967# as needed. If no variant puts something in $url, we assume avatars1968# are completely disabled/unavailable.1969if($url) {1970return$pre_white.1971"<img width=\"$size\"".1972"class=\"avatar\"".1973"src=\"".esc_url($url)."\"".1974"alt=\"\"".1975"/>".$post_white;1976}else{1977return"";1978}1979}19801981sub format_search_author {1982my($author,$searchtype,$displaytext) =@_;1983my$have_search= gitweb_check_feature('search');19841985if($have_search) {1986my$performed="";1987if($searchtypeeq'author') {1988$performed="authored";1989}elsif($searchtypeeq'committer') {1990$performed="committed";1991}19921993return$cgi->a({-href => href(action=>"search", hash=>$hash,1994 searchtext=>$author,1995 searchtype=>$searchtype),class=>"list",1996 title=>"Search for commits$performedby$author"},1997$displaytext);19981999}else{2000return$displaytext;2001}2002}20032004# format the author name of the given commit with the given tag2005# the author name is chopped and escaped according to the other2006# optional parameters (see chop_str).2007sub format_author_html {2008my$tag=shift;2009my$co=shift;2010my$author= chop_and_escape_str($co->{'author_name'},@_);2011return"<$tagclass=\"author\">".2012 format_search_author($co->{'author_name'},"author",2013 git_get_avatar($co->{'author_email'}, -pad_after =>1) .2014$author) .2015"</$tag>";2016}20172018# format git diff header line, i.e. "diff --(git|combined|cc) ..."2019sub format_git_diff_header_line {2020my$line=shift;2021my$diffinfo=shift;2022my($from,$to) =@_;20232024if($diffinfo->{'nparents'}) {2025# combined diff2026$line=~s!^(diff (.*?) )"?.*$!$1!;2027if($to->{'href'}) {2028$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2029 esc_path($to->{'file'}));2030}else{# file was deleted (no href)2031$line.= esc_path($to->{'file'});2032}2033}else{2034# "ordinary" diff2035$line=~s!^(diff (.*?) )"?a/.*$!$1!;2036if($from->{'href'}) {2037$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},2038'a/'. esc_path($from->{'file'}));2039}else{# file was added (no href)2040$line.='a/'. esc_path($from->{'file'});2041}2042$line.=' ';2043if($to->{'href'}) {2044$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2045'b/'. esc_path($to->{'file'}));2046}else{# file was deleted2047$line.='b/'. esc_path($to->{'file'});2048}2049}20502051return"<div class=\"diff header\">$line</div>\n";2052}20532054# format extended diff header line, before patch itself2055sub format_extended_diff_header_line {2056my$line=shift;2057my$diffinfo=shift;2058my($from,$to) =@_;20592060# match <path>2061if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {2062$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},2063 esc_path($from->{'file'}));2064}2065if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {2066$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},2067 esc_path($to->{'file'}));2068}2069# match single <mode>2070if($line=~m/\s(\d{6})$/) {2071$line.='<span class="info"> ('.2072 file_type_long($1) .2073')</span>';2074}2075# match <hash>2076if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {2077# can match only for combined diff2078$line='index ';2079for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2080if($from->{'href'}[$i]) {2081$line.=$cgi->a({-href=>$from->{'href'}[$i],2082-class=>"hash"},2083substr($diffinfo->{'from_id'}[$i],0,7));2084}else{2085$line.='0' x 7;2086}2087# separator2088$line.=','if($i<$diffinfo->{'nparents'} -1);2089}2090$line.='..';2091if($to->{'href'}) {2092$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2093substr($diffinfo->{'to_id'},0,7));2094}else{2095$line.='0' x 7;2096}20972098}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {2099# can match only for ordinary diff2100my($from_link,$to_link);2101if($from->{'href'}) {2102$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},2103substr($diffinfo->{'from_id'},0,7));2104}else{2105$from_link='0' x 7;2106}2107if($to->{'href'}) {2108$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2109substr($diffinfo->{'to_id'},0,7));2110}else{2111$to_link='0' x 7;2112}2113my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});2114$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;2115}21162117return$line."<br/>\n";2118}21192120# format from-file/to-file diff header2121sub format_diff_from_to_header {2122my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2123my$line;2124my$result='';21252126$line=$from_line;2127#assert($line =~ m/^---/) if DEBUG;2128# no extra formatting for "^--- /dev/null"2129if(!$diffinfo->{'nparents'}) {2130# ordinary (single parent) diff2131if($line=~m!^--- "?a/!) {2132if($from->{'href'}) {2133$line='--- a/'.2134$cgi->a({-href=>$from->{'href'}, -class=>"path"},2135 esc_path($from->{'file'}));2136}else{2137$line='--- a/'.2138 esc_path($from->{'file'});2139}2140}2141$result.= qq!<div class="diff from_file">$line</div>\n!;21422143}else{2144# combined diff (merge commit)2145for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2146if($from->{'href'}[$i]) {2147$line='--- '.2148$cgi->a({-href=>href(action=>"blobdiff",2149 hash_parent=>$diffinfo->{'from_id'}[$i],2150 hash_parent_base=>$parents[$i],2151 file_parent=>$from->{'file'}[$i],2152 hash=>$diffinfo->{'to_id'},2153 hash_base=>$hash,2154 file_name=>$to->{'file'}),2155-class=>"path",2156-title=>"diff". ($i+1)},2157$i+1) .2158'/'.2159$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2160 esc_path($from->{'file'}[$i]));2161}else{2162$line='--- /dev/null';2163}2164$result.= qq!<div class="diff from_file">$line</div>\n!;2165}2166}21672168$line=$to_line;2169#assert($line =~ m/^\+\+\+/) if DEBUG;2170# no extra formatting for "^+++ /dev/null"2171if($line=~m!^\+\+\+ "?b/!) {2172if($to->{'href'}) {2173$line='+++ b/'.2174$cgi->a({-href=>$to->{'href'}, -class=>"path"},2175 esc_path($to->{'file'}));2176}else{2177$line='+++ b/'.2178 esc_path($to->{'file'});2179}2180}2181$result.= qq!<div class="diff to_file">$line</div>\n!;21822183return$result;2184}21852186# create note for patch simplified by combined diff2187sub format_diff_cc_simplified {2188my($diffinfo,@parents) =@_;2189my$result='';21902191$result.="<div class=\"diff header\">".2192"diff --cc ";2193if(!is_deleted($diffinfo)) {2194$result.=$cgi->a({-href => href(action=>"blob",2195 hash_base=>$hash,2196 hash=>$diffinfo->{'to_id'},2197 file_name=>$diffinfo->{'to_file'}),2198-class=>"path"},2199 esc_path($diffinfo->{'to_file'}));2200}else{2201$result.= esc_path($diffinfo->{'to_file'});2202}2203$result.="</div>\n".# class="diff header"2204"<div class=\"diff nodifferences\">".2205"Simple merge".2206"</div>\n";# class="diff nodifferences"22072208return$result;2209}22102211# format patch (diff) line (not to be used for diff headers)2212sub format_diff_line {2213my$line=shift;2214my($from,$to) =@_;2215my$diff_class="";22162217chomp$line;22182219if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2220# combined diff2221my$prefix=substr($line,0,scalar@{$from->{'href'}});2222if($line=~m/^\@{3}/) {2223$diff_class=" chunk_header";2224}elsif($line=~m/^\\/) {2225$diff_class=" incomplete";2226}elsif($prefix=~tr/+/+/) {2227$diff_class=" add";2228}elsif($prefix=~tr/-/-/) {2229$diff_class=" rem";2230}2231}else{2232# assume ordinary diff2233my$char=substr($line,0,1);2234if($chareq'+') {2235$diff_class=" add";2236}elsif($chareq'-') {2237$diff_class=" rem";2238}elsif($chareq'@') {2239$diff_class=" chunk_header";2240}elsif($chareq"\\") {2241$diff_class=" incomplete";2242}2243}2244$line= untabify($line);2245if($from&&$to&&$line=~m/^\@{2} /) {2246my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2247$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;22482249$from_lines=0unlessdefined$from_lines;2250$to_lines=0unlessdefined$to_lines;22512252if($from->{'href'}) {2253$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2254-class=>"list"},$from_text);2255}2256if($to->{'href'}) {2257$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2258-class=>"list"},$to_text);2259}2260$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2261"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2262return"<div class=\"diff$diff_class\">$line</div>\n";2263}elsif($from&&$to&&$line=~m/^\@{3}/) {2264my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2265my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);22662267@from_text=split(' ',$ranges);2268for(my$i=0;$i<@from_text; ++$i) {2269($from_start[$i],$from_nlines[$i]) =2270(split(',',substr($from_text[$i],1)),0);2271}22722273$to_text=pop@from_text;2274$to_start=pop@from_start;2275$to_nlines=pop@from_nlines;22762277$line="<span class=\"chunk_info\">$prefix";2278for(my$i=0;$i<@from_text; ++$i) {2279if($from->{'href'}[$i]) {2280$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2281-class=>"list"},$from_text[$i]);2282}else{2283$line.=$from_text[$i];2284}2285$line.=" ";2286}2287if($to->{'href'}) {2288$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2289-class=>"list"},$to_text);2290}else{2291$line.=$to_text;2292}2293$line.="$prefix</span>".2294"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2295return"<div class=\"diff$diff_class\">$line</div>\n";2296}2297return"<div class=\"diff$diff_class\">". esc_html($line, -nbsp=>1) ."</div>\n";2298}22992300# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2301# linked. Pass the hash of the tree/commit to snapshot.2302sub format_snapshot_links {2303my($hash) =@_;2304my$num_fmts=@snapshot_fmts;2305if($num_fmts>1) {2306# A parenthesized list of links bearing format names.2307# e.g. "snapshot (_tar.gz_ _zip_)"2308return"snapshot (".join(' ',map2309$cgi->a({2310-href => href(2311 action=>"snapshot",2312 hash=>$hash,2313 snapshot_format=>$_2314)2315},$known_snapshot_formats{$_}{'display'})2316,@snapshot_fmts) .")";2317}elsif($num_fmts==1) {2318# A single "snapshot" link whose tooltip bears the format name.2319# i.e. "_snapshot_"2320my($fmt) =@snapshot_fmts;2321return2322$cgi->a({2323-href => href(2324 action=>"snapshot",2325 hash=>$hash,2326 snapshot_format=>$fmt2327),2328-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2329},"snapshot");2330}else{# $num_fmts == 02331returnundef;2332}2333}23342335## ......................................................................2336## functions returning values to be passed, perhaps after some2337## transformation, to other functions; e.g. returning arguments to href()23382339# returns hash to be passed to href to generate gitweb URL2340# in -title key it returns description of link2341sub get_feed_info {2342my$format=shift||'Atom';2343my%res= (action =>lc($format));23442345# feed links are possible only for project views2346return unless(defined$project);2347# some views should link to OPML, or to generic project feed,2348# or don't have specific feed yet (so they should use generic)2349return if($action=~/^(?:tags|heads|forks|tag|search)$/x);23502351my$branch;2352# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2353# from tag links; this also makes possible to detect branch links2354if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2355(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2356$branch=$1;2357}2358# find log type for feed description (title)2359my$type='log';2360if(defined$file_name) {2361$type="history of$file_name";2362$type.="/"if($actioneq'tree');2363$type.=" on '$branch'"if(defined$branch);2364}else{2365$type="log of$branch"if(defined$branch);2366}23672368$res{-title} =$type;2369$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2370$res{'file_name'} =$file_name;23712372return%res;2373}23742375## ----------------------------------------------------------------------2376## git utility subroutines, invoking git commands23772378# returns path to the core git executable and the --git-dir parameter as list2379sub git_cmd {2380$number_of_git_cmds++;2381return$GIT,'--git-dir='.$git_dir;2382}23832384# quote the given arguments for passing them to the shell2385# quote_command("command", "arg 1", "arg with ' and ! characters")2386# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2387# Try to avoid using this function wherever possible.2388sub quote_command {2389returnjoin(' ',2390map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2391}23922393# get HEAD ref of given project as hash2394sub git_get_head_hash {2395return git_get_full_hash(shift,'HEAD');2396}23972398sub git_get_full_hash {2399return git_get_hash(@_);2400}24012402sub git_get_short_hash {2403return git_get_hash(@_,'--short=7');2404}24052406sub git_get_hash {2407my($project,$hash,@options) =@_;2408my$o_git_dir=$git_dir;2409my$retval=undef;2410$git_dir="$projectroot/$project";2411if(open my$fd,'-|', git_cmd(),'rev-parse',2412'--verify','-q',@options,$hash) {2413$retval= <$fd>;2414chomp$retvalifdefined$retval;2415close$fd;2416}2417if(defined$o_git_dir) {2418$git_dir=$o_git_dir;2419}2420return$retval;2421}24222423# get type of given object2424sub git_get_type {2425my$hash=shift;24262427open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2428my$type= <$fd>;2429close$fdorreturn;2430chomp$type;2431return$type;2432}24332434# repository configuration2435our$config_file='';2436our%config;24372438# store multiple values for single key as anonymous array reference2439# single values stored directly in the hash, not as [ <value> ]2440sub hash_set_multi {2441my($hash,$key,$value) =@_;24422443if(!exists$hash->{$key}) {2444$hash->{$key} =$value;2445}elsif(!ref$hash->{$key}) {2446$hash->{$key} = [$hash->{$key},$value];2447}else{2448push@{$hash->{$key}},$value;2449}2450}24512452# return hash of git project configuration2453# optionally limited to some section, e.g. 'gitweb'2454sub git_parse_project_config {2455my$section_regexp=shift;2456my%config;24572458local$/="\0";24592460open my$fh,"-|", git_cmd(),"config",'-z','-l',2461orreturn;24622463while(my$keyval= <$fh>) {2464chomp$keyval;2465my($key,$value) =split(/\n/,$keyval,2);24662467 hash_set_multi(\%config,$key,$value)2468if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2469}2470close$fh;24712472return%config;2473}24742475# convert config value to boolean: 'true' or 'false'2476# no value, number > 0, 'true' and 'yes' values are true2477# rest of values are treated as false (never as error)2478sub config_to_bool {2479my$val=shift;24802481return1if!defined$val;# section.key24822483# strip leading and trailing whitespace2484$val=~s/^\s+//;2485$val=~s/\s+$//;24862487return(($val=~/^\d+$/&&$val) ||# section.key = 12488($val=~/^(?:true|yes)$/i));# section.key = true2489}24902491# convert config value to simple decimal number2492# an optional value suffix of 'k', 'm', or 'g' will cause the value2493# to be multiplied by 1024, 1048576, or 10737418242494sub config_to_int {2495my$val=shift;24962497# strip leading and trailing whitespace2498$val=~s/^\s+//;2499$val=~s/\s+$//;25002501if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2502$unit=lc($unit);2503# unknown unit is treated as 12504return$num* ($uniteq'g'?1073741824:2505$uniteq'm'?1048576:2506$uniteq'k'?1024:1);2507}2508return$val;2509}25102511# convert config value to array reference, if needed2512sub config_to_multi {2513my$val=shift;25142515returnref($val) ?$val: (defined($val) ? [$val] : []);2516}25172518sub git_get_project_config {2519my($key,$type) =@_;25202521return unlessdefined$git_dir;25222523# key sanity check2524return unless($key);2525$key=~s/^gitweb\.//;2526return if($key=~m/\W/);25272528# type sanity check2529if(defined$type) {2530$type=~s/^--//;2531$type=undef2532unless($typeeq'bool'||$typeeq'int');2533}25342535# get config2536if(!defined$config_file||2537$config_filene"$git_dir/config") {2538%config= git_parse_project_config('gitweb');2539$config_file="$git_dir/config";2540}25412542# check if config variable (key) exists2543return unlessexists$config{"gitweb.$key"};25442545# ensure given type2546if(!defined$type) {2547return$config{"gitweb.$key"};2548}elsif($typeeq'bool') {2549# backward compatibility: 'git config --bool' returns true/false2550return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2551}elsif($typeeq'int') {2552return config_to_int($config{"gitweb.$key"});2553}2554return$config{"gitweb.$key"};2555}25562557# get hash of given path at given ref2558sub git_get_hash_by_path {2559my$base=shift;2560my$path=shift||returnundef;2561my$type=shift;25622563$path=~ s,/+$,,;25642565open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2566or die_error(500,"Open git-ls-tree failed");2567my$line= <$fd>;2568close$fdorreturnundef;25692570if(!defined$line) {2571# there is no tree or hash given by $path at $base2572returnundef;2573}25742575#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2576$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2577if(defined$type&&$typene$2) {2578# type doesn't match2579returnundef;2580}2581return$3;2582}25832584# get path of entry with given hash at given tree-ish (ref)2585# used to get 'from' filename for combined diff (merge commit) for renames2586sub git_get_path_by_hash {2587my$base=shift||return;2588my$hash=shift||return;25892590local$/="\0";25912592open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2593orreturnundef;2594while(my$line= <$fd>) {2595chomp$line;25962597#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2598#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2599if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2600close$fd;2601return$1;2602}2603}2604close$fd;2605returnundef;2606}26072608## ......................................................................2609## git utility functions, directly accessing git repository26102611# get the value of config variable either from file named as the variable2612# itself in the repository ($GIT_DIR/$name file), or from gitweb.$name2613# configuration variable in the repository config file.2614sub git_get_file_or_project_config {2615my($path,$name) =@_;26162617$git_dir="$projectroot/$path";2618open my$fd,'<',"$git_dir/$name"2619orreturn git_get_project_config($name);2620my$conf= <$fd>;2621close$fd;2622if(defined$conf) {2623chomp$conf;2624}2625return$conf;2626}26272628sub git_get_project_description {2629my$path=shift;2630return git_get_file_or_project_config($path,'description');2631}26322633sub git_get_project_category {2634my$path=shift;2635return git_get_file_or_project_config($path,'category');2636}263726382639# supported formats:2640# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2641# - if its contents is a number, use it as tag weight,2642# - otherwise add a tag with weight 12643# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2644# the same value multiple times increases tag weight2645# * `gitweb.ctag' multi-valued repo config variable2646sub git_get_project_ctags {2647my$project=shift;2648my$ctags= {};26492650$git_dir="$projectroot/$project";2651if(opendir my$dh,"$git_dir/ctags") {2652my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2653foreachmy$tagfile(@files) {2654open my$ct,'<',$tagfile2655ornext;2656my$val= <$ct>;2657chomp$valif$val;2658close$ct;26592660(my$ctag=$tagfile) =~ s#.*/##;2661if($val=~/^\d+$/) {2662$ctags->{$ctag} =$val;2663}else{2664$ctags->{$ctag} =1;2665}2666}2667closedir$dh;26682669}elsif(open my$fh,'<',"$git_dir/ctags") {2670while(my$line= <$fh>) {2671chomp$line;2672$ctags->{$line}++if$line;2673}2674close$fh;26752676}else{2677my$taglist= config_to_multi(git_get_project_config('ctag'));2678foreachmy$tag(@$taglist) {2679$ctags->{$tag}++;2680}2681}26822683return$ctags;2684}26852686# return hash, where keys are content tags ('ctags'),2687# and values are sum of weights of given tag in every project2688sub git_gather_all_ctags {2689my$projects=shift;2690my$ctags= {};26912692foreachmy$p(@$projects) {2693foreachmy$ct(keys%{$p->{'ctags'}}) {2694$ctags->{$ct} +=$p->{'ctags'}->{$ct};2695}2696}26972698return$ctags;2699}27002701sub git_populate_project_tagcloud {2702my$ctags=shift;27032704# First, merge different-cased tags; tags vote on casing2705my%ctags_lc;2706foreach(keys%$ctags) {2707$ctags_lc{lc$_}->{count} +=$ctags->{$_};2708if(not$ctags_lc{lc$_}->{topcount}2709or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2710$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2711$ctags_lc{lc$_}->{topname} =$_;2712}2713}27142715my$cloud;2716my$matched=$cgi->param('by_tag');2717if(eval{require HTML::TagCloud;1; }) {2718$cloud= HTML::TagCloud->new;2719foreachmy$ctag(sort keys%ctags_lc) {2720# Pad the title with spaces so that the cloud looks2721# less crammed.2722my$title= esc_html($ctags_lc{$ctag}->{topname});2723$title=~s/ / /g;2724$title=~s/^/ /g;2725$title=~s/$/ /g;2726if(defined$matched&&$matchedeq$ctag) {2727$title=qq(<span class="match">$title</span>);2728}2729$cloud->add($title, href(project=>undef, ctag=>$ctag),2730$ctags_lc{$ctag}->{count});2731}2732}else{2733$cloud= {};2734foreachmy$ctag(keys%ctags_lc) {2735my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2736if(defined$matched&&$matchedeq$ctag) {2737$title=qq(<span class="match">$title</span>);2738}2739$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};2740$cloud->{$ctag}{ctag} =2741$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);2742}2743}2744return$cloud;2745}27462747sub git_show_project_tagcloud {2748my($cloud,$count) =@_;2749if(ref$cloudeq'HTML::TagCloud') {2750return$cloud->html_and_css($count);2751}else{2752my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;2753return2754'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.2755join(', ',map{2756$cloud->{$_}->{'ctag'}2757}splice(@tags,0,$count)) .2758'</div>';2759}2760}27612762sub git_get_project_url_list {2763my$path=shift;27642765$git_dir="$projectroot/$path";2766open my$fd,'<',"$git_dir/cloneurl"2767orreturnwantarray?2768@{ config_to_multi(git_get_project_config('url')) } :2769 config_to_multi(git_get_project_config('url'));2770my@git_project_url_list=map{chomp;$_} <$fd>;2771close$fd;27722773returnwantarray?@git_project_url_list: \@git_project_url_list;2774}27752776sub git_get_projects_list {2777my$filter=shift||'';2778my@list;27792780$filter=~s/\.git$//;27812782if(-d $projects_list) {2783# search in directory2784my$dir=$projects_list;2785# remove the trailing "/"2786$dir=~s!/+$!!;2787my$pfxlen=length("$projects_list");2788my$pfxdepth= ($projects_list=~tr!/!!);2789# when filtering, search only given subdirectory2790if($filter) {2791$dir.="/$filter";2792$dir=~s!/+$!!;2793}27942795 File::Find::find({2796 follow_fast =>1,# follow symbolic links2797 follow_skip =>2,# ignore duplicates2798 dangling_symlinks =>0,# ignore dangling symlinks, silently2799 wanted =>sub{2800# global variables2801our$project_maxdepth;2802our$projectroot;2803# skip project-list toplevel, if we get it.2804return if(m!^[/.]$!);2805# only directories can be git repositories2806return unless(-d $_);2807# don't traverse too deep (Find is super slow on os x)2808# $project_maxdepth excludes depth of $projectroot2809if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2810$File::Find::prune =1;2811return;2812}28132814my$path=substr($File::Find::name,$pfxlen+1);2815# we check related file in $projectroot2816if(check_export_ok("$projectroot/$path")) {2817push@list, { path =>$path};2818$File::Find::prune =1;2819}2820},2821},"$dir");28222823}elsif(-f $projects_list) {2824# read from file(url-encoded):2825# 'git%2Fgit.git Linus+Torvalds'2826# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2827# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2828open my$fd,'<',$projects_listorreturn;2829 PROJECT:2830while(my$line= <$fd>) {2831chomp$line;2832my($path,$owner) =split' ',$line;2833$path= unescape($path);2834$owner= unescape($owner);2835if(!defined$path) {2836next;2837}2838# if $filter is rpovided, check if $path begins with $filter2839if($filter&&$path!~m!^\Q$filter\E/!) {2840next;2841}2842if(check_export_ok("$projectroot/$path")) {2843my$pr= {2844 path =>$path,2845 owner => to_utf8($owner),2846};2847push@list,$pr;2848}2849}2850close$fd;2851}2852return@list;2853}28542855# written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)2856# as side effects it sets 'forks' field to list of forks for forked projects2857sub filter_forks_from_projects_list {2858my$projects=shift;28592860my%trie;# prefix tree of directories (path components)2861# generate trie out of those directories that might contain forks2862foreachmy$pr(@$projects) {2863my$path=$pr->{'path'};2864$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory2865next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'2866next unless($path);# skip '.git' repository: tests, git-instaweb2867next unless(-d $path);# containing directory exists2868$pr->{'forks'} = [];# there can be 0 or more forks of project28692870# add to trie2871my@dirs=split('/',$path);2872# walk the trie, until either runs out of components or out of trie2873my$ref= \%trie;2874while(scalar@dirs&&2875exists($ref->{$dirs[0]})) {2876$ref=$ref->{shift@dirs};2877}2878# create rest of trie structure from rest of components2879foreachmy$dir(@dirs) {2880$ref=$ref->{$dir} = {};2881}2882# create end marker, store $pr as a data2883$ref->{''} =$prif(!exists$ref->{''});2884}28852886# filter out forks, by finding shortest prefix match for paths2887my@filtered;2888 PROJECT:2889foreachmy$pr(@$projects) {2890# trie lookup2891my$ref= \%trie;2892 DIR:2893foreachmy$dir(split('/',$pr->{'path'})) {2894if(exists$ref->{''}) {2895# found [shortest] prefix, is a fork - skip it2896push@{$ref->{''}{'forks'}},$pr;2897next PROJECT;2898}2899if(!exists$ref->{$dir}) {2900# not in trie, cannot have prefix, not a fork2901push@filtered,$pr;2902next PROJECT;2903}2904# If the dir is there, we just walk one step down the trie.2905$ref=$ref->{$dir};2906}2907# we ran out of trie2908# (shouldn't happen: it's either no match, or end marker)2909push@filtered,$pr;2910}29112912return@filtered;2913}29142915# note: fill_project_list_info must be run first,2916# for 'descr_long' and 'ctags' to be filled2917sub search_projects_list {2918my($projlist,%opts) =@_;2919my$tagfilter=$opts{'tagfilter'};2920my$searchtext=$opts{'searchtext'};29212922return@$projlist2923unless($tagfilter||$searchtext);29242925my@projects;2926 PROJECT:2927foreachmy$pr(@$projlist) {29282929if($tagfilter) {2930next unlessref($pr->{'ctags'})eq'HASH';2931next unless2932grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};2933}29342935if($searchtext) {2936next unless2937$pr->{'path'} =~/$searchtext/||2938$pr->{'descr_long'} =~/$searchtext/;2939}29402941push@projects,$pr;2942}29432944return@projects;2945}29462947our$gitweb_project_owner=undef;2948sub git_get_project_list_from_file {29492950return if(defined$gitweb_project_owner);29512952$gitweb_project_owner= {};2953# read from file (url-encoded):2954# 'git%2Fgit.git Linus+Torvalds'2955# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2956# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2957if(-f $projects_list) {2958open(my$fd,'<',$projects_list);2959while(my$line= <$fd>) {2960chomp$line;2961my($pr,$ow) =split' ',$line;2962$pr= unescape($pr);2963$ow= unescape($ow);2964$gitweb_project_owner->{$pr} = to_utf8($ow);2965}2966close$fd;2967}2968}29692970sub git_get_project_owner {2971my$project=shift;2972my$owner;29732974returnundefunless$project;2975$git_dir="$projectroot/$project";29762977if(!defined$gitweb_project_owner) {2978 git_get_project_list_from_file();2979}29802981if(exists$gitweb_project_owner->{$project}) {2982$owner=$gitweb_project_owner->{$project};2983}2984if(!defined$owner){2985$owner= git_get_project_config('owner');2986}2987if(!defined$owner) {2988$owner= get_file_owner("$git_dir");2989}29902991return$owner;2992}29932994sub git_get_last_activity {2995my($path) =@_;2996my$fd;29972998$git_dir="$projectroot/$path";2999open($fd,"-|", git_cmd(),'for-each-ref',3000'--format=%(committer)',3001'--sort=-committerdate',3002'--count=1',3003'refs/heads')orreturn;3004my$most_recent= <$fd>;3005close$fdorreturn;3006if(defined$most_recent&&3007$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {3008my$timestamp=$1;3009my$age=time-$timestamp;3010return($age, age_string($age));3011}3012return(undef,undef);3013}30143015# Implementation note: when a single remote is wanted, we cannot use 'git3016# remote show -n' because that command always work (assuming it's a remote URL3017# if it's not defined), and we cannot use 'git remote show' because that would3018# try to make a network roundtrip. So the only way to find if that particular3019# remote is defined is to walk the list provided by 'git remote -v' and stop if3020# and when we find what we want.3021sub git_get_remotes_list {3022my$wanted=shift;3023my%remotes= ();30243025open my$fd,'-|', git_cmd(),'remote','-v';3026return unless$fd;3027while(my$remote= <$fd>) {3028chomp$remote;3029$remote=~s!\t(.*?)\s+\((\w+)\)$!!;3030next if$wantedand not$remoteeq$wanted;3031my($url,$key) = ($1,$2);30323033$remotes{$remote} ||= {'heads'=> () };3034$remotes{$remote}{$key} =$url;3035}3036close$fdorreturn;3037returnwantarray?%remotes: \%remotes;3038}30393040# Takes a hash of remotes as first parameter and fills it by adding the3041# available remote heads for each of the indicated remotes.3042sub fill_remote_heads {3043my$remotes=shift;3044my@heads=map{"remotes/$_"}keys%$remotes;3045my@remoteheads= git_get_heads_list(undef,@heads);3046foreachmy$remote(keys%$remotes) {3047$remotes->{$remote}{'heads'} = [grep{3048$_->{'name'} =~s!^$remote/!!3049}@remoteheads];3050}3051}30523053sub git_get_references {3054my$type=shift||"";3055my%refs;3056# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113057# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3058open my$fd,"-|", git_cmd(),"show-ref","--dereference",3059($type? ("--","refs/$type") : ())# use -- <pattern> if $type3060orreturn;30613062while(my$line= <$fd>) {3063chomp$line;3064if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3065if(defined$refs{$1}) {3066push@{$refs{$1}},$2;3067}else{3068$refs{$1} = [$2];3069}3070}3071}3072close$fdorreturn;3073return \%refs;3074}30753076sub git_get_rev_name_tags {3077my$hash=shift||returnundef;30783079open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3080orreturn;3081my$name_rev= <$fd>;3082close$fd;30833084if($name_rev=~ m|^$hash tags/(.*)$|) {3085return$1;3086}else{3087# catches also '$hash undefined' output3088returnundef;3089}3090}30913092## ----------------------------------------------------------------------3093## parse to hash functions30943095sub parse_date {3096my$epoch=shift;3097my$tz=shift||"-0000";30983099my%date;3100my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3101my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3102my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3103$date{'hour'} =$hour;3104$date{'minute'} =$min;3105$date{'mday'} =$mday;3106$date{'day'} =$days[$wday];3107$date{'month'} =$months[$mon];3108$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3109$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3110$date{'mday-time'} =sprintf"%d%s%02d:%02d",3111$mday,$months[$mon],$hour,$min;3112$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",31131900+$year,1+$mon,$mday,$hour,$min,$sec;31143115my($tz_sign,$tz_hour,$tz_min) =3116($tz=~m/^([-+])(\d\d)(\d\d)$/);3117$tz_sign= ($tz_signeq'-'? -1: +1);3118my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3119($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3120$date{'hour_local'} =$hour;3121$date{'minute_local'} =$min;3122$date{'tz_local'} =$tz;3123$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",31241900+$year,$mon+1,$mday,3125$hour,$min,$sec,$tz);3126return%date;3127}31283129sub parse_tag {3130my$tag_id=shift;3131my%tag;3132my@comment;31333134open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3135$tag{'id'} =$tag_id;3136while(my$line= <$fd>) {3137chomp$line;3138if($line=~m/^object ([0-9a-fA-F]{40})$/) {3139$tag{'object'} =$1;3140}elsif($line=~m/^type (.+)$/) {3141$tag{'type'} =$1;3142}elsif($line=~m/^tag (.+)$/) {3143$tag{'name'} =$1;3144}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3145$tag{'author'} =$1;3146$tag{'author_epoch'} =$2;3147$tag{'author_tz'} =$3;3148if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3149$tag{'author_name'} =$1;3150$tag{'author_email'} =$2;3151}else{3152$tag{'author_name'} =$tag{'author'};3153}3154}elsif($line=~m/--BEGIN/) {3155push@comment,$line;3156last;3157}elsif($lineeq"") {3158last;3159}3160}3161push@comment, <$fd>;3162$tag{'comment'} = \@comment;3163close$fdorreturn;3164if(!defined$tag{'name'}) {3165return3166};3167return%tag3168}31693170sub parse_commit_text {3171my($commit_text,$withparents) =@_;3172my@commit_lines=split'\n',$commit_text;3173my%co;31743175pop@commit_lines;# Remove '\0'31763177if(!@commit_lines) {3178return;3179}31803181my$header=shift@commit_lines;3182if($header!~m/^[0-9a-fA-F]{40}/) {3183return;3184}3185($co{'id'},my@parents) =split' ',$header;3186while(my$line=shift@commit_lines) {3187last if$lineeq"\n";3188if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3189$co{'tree'} =$1;3190}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3191push@parents,$1;3192}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3193$co{'author'} = to_utf8($1);3194$co{'author_epoch'} =$2;3195$co{'author_tz'} =$3;3196if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3197$co{'author_name'} =$1;3198$co{'author_email'} =$2;3199}else{3200$co{'author_name'} =$co{'author'};3201}3202}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3203$co{'committer'} = to_utf8($1);3204$co{'committer_epoch'} =$2;3205$co{'committer_tz'} =$3;3206if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3207$co{'committer_name'} =$1;3208$co{'committer_email'} =$2;3209}else{3210$co{'committer_name'} =$co{'committer'};3211}3212}3213}3214if(!defined$co{'tree'}) {3215return;3216};3217$co{'parents'} = \@parents;3218$co{'parent'} =$parents[0];32193220foreachmy$title(@commit_lines) {3221$title=~s/^ //;3222if($titlene"") {3223$co{'title'} = chop_str($title,80,5);3224# remove leading stuff of merges to make the interesting part visible3225if(length($title) >50) {3226$title=~s/^Automatic //;3227$title=~s/^merge (of|with) /Merge ... /i;3228if(length($title) >50) {3229$title=~s/(http|rsync):\/\///;3230}3231if(length($title) >50) {3232$title=~s/(master|www|rsync)\.//;3233}3234if(length($title) >50) {3235$title=~s/kernel.org:?//;3236}3237if(length($title) >50) {3238$title=~s/\/pub\/scm//;3239}3240}3241$co{'title_short'} = chop_str($title,50,5);3242last;3243}3244}3245if(!defined$co{'title'} ||$co{'title'}eq"") {3246$co{'title'} =$co{'title_short'} ='(no commit message)';3247}3248# remove added spaces3249foreachmy$line(@commit_lines) {3250$line=~s/^ //;3251}3252$co{'comment'} = \@commit_lines;32533254my$age=time-$co{'committer_epoch'};3255$co{'age'} =$age;3256$co{'age_string'} = age_string($age);3257my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3258if($age>60*60*24*7*2) {3259$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3260$co{'age_string_age'} =$co{'age_string'};3261}else{3262$co{'age_string_date'} =$co{'age_string'};3263$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3264}3265return%co;3266}32673268sub parse_commit {3269my($commit_id) =@_;3270my%co;32713272local$/="\0";32733274open my$fd,"-|", git_cmd(),"rev-list",3275"--parents",3276"--header",3277"--max-count=1",3278$commit_id,3279"--",3280or die_error(500,"Open git-rev-list failed");3281%co= parse_commit_text(<$fd>,1);3282close$fd;32833284return%co;3285}32863287sub parse_commits {3288my($commit_id,$maxcount,$skip,$filename,@args) =@_;3289my@cos;32903291$maxcount||=1;3292$skip||=0;32933294local$/="\0";32953296open my$fd,"-|", git_cmd(),"rev-list",3297"--header",3298@args,3299("--max-count=".$maxcount),3300("--skip=".$skip),3301@extra_options,3302$commit_id,3303"--",3304($filename? ($filename) : ())3305or die_error(500,"Open git-rev-list failed");3306while(my$line= <$fd>) {3307my%co= parse_commit_text($line);3308push@cos, \%co;3309}3310close$fd;33113312returnwantarray?@cos: \@cos;3313}33143315# parse line of git-diff-tree "raw" output3316sub parse_difftree_raw_line {3317my$line=shift;3318my%res;33193320# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3321# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3322if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3323$res{'from_mode'} =$1;3324$res{'to_mode'} =$2;3325$res{'from_id'} =$3;3326$res{'to_id'} =$4;3327$res{'status'} =$5;3328$res{'similarity'} =$6;3329if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3330($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3331}else{3332$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3333}3334}3335# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3336# combined diff (for merge commit)3337elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3338$res{'nparents'} =length($1);3339$res{'from_mode'} = [split(' ',$2) ];3340$res{'to_mode'} =pop@{$res{'from_mode'}};3341$res{'from_id'} = [split(' ',$3) ];3342$res{'to_id'} =pop@{$res{'from_id'}};3343$res{'status'} = [split('',$4) ];3344$res{'to_file'} = unquote($5);3345}3346# 'c512b523472485aef4fff9e57b229d9d243c967f'3347elsif($line=~m/^([0-9a-fA-F]{40})$/) {3348$res{'commit'} =$1;3349}33503351returnwantarray?%res: \%res;3352}33533354# wrapper: return parsed line of git-diff-tree "raw" output3355# (the argument might be raw line, or parsed info)3356sub parsed_difftree_line {3357my$line_or_ref=shift;33583359if(ref($line_or_ref)eq"HASH") {3360# pre-parsed (or generated by hand)3361return$line_or_ref;3362}else{3363return parse_difftree_raw_line($line_or_ref);3364}3365}33663367# parse line of git-ls-tree output3368sub parse_ls_tree_line {3369my$line=shift;3370my%opts=@_;3371my%res;33723373if($opts{'-l'}) {3374#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3375$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;33763377$res{'mode'} =$1;3378$res{'type'} =$2;3379$res{'hash'} =$3;3380$res{'size'} =$4;3381if($opts{'-z'}) {3382$res{'name'} =$5;3383}else{3384$res{'name'} = unquote($5);3385}3386}else{3387#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3388$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;33893390$res{'mode'} =$1;3391$res{'type'} =$2;3392$res{'hash'} =$3;3393if($opts{'-z'}) {3394$res{'name'} =$4;3395}else{3396$res{'name'} = unquote($4);3397}3398}33993400returnwantarray?%res: \%res;3401}34023403# generates _two_ hashes, references to which are passed as 2 and 3 argument3404sub parse_from_to_diffinfo {3405my($diffinfo,$from,$to,@parents) =@_;34063407if($diffinfo->{'nparents'}) {3408# combined diff3409$from->{'file'} = [];3410$from->{'href'} = [];3411 fill_from_file_info($diffinfo,@parents)3412unlessexists$diffinfo->{'from_file'};3413for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3414$from->{'file'}[$i] =3415defined$diffinfo->{'from_file'}[$i] ?3416$diffinfo->{'from_file'}[$i] :3417$diffinfo->{'to_file'};3418if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3419$from->{'href'}[$i] = href(action=>"blob",3420 hash_base=>$parents[$i],3421 hash=>$diffinfo->{'from_id'}[$i],3422 file_name=>$from->{'file'}[$i]);3423}else{3424$from->{'href'}[$i] =undef;3425}3426}3427}else{3428# ordinary (not combined) diff3429$from->{'file'} =$diffinfo->{'from_file'};3430if($diffinfo->{'status'}ne"A") {# not new (added) file3431$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3432 hash=>$diffinfo->{'from_id'},3433 file_name=>$from->{'file'});3434}else{3435delete$from->{'href'};3436}3437}34383439$to->{'file'} =$diffinfo->{'to_file'};3440if(!is_deleted($diffinfo)) {# file exists in result3441$to->{'href'} = href(action=>"blob", hash_base=>$hash,3442 hash=>$diffinfo->{'to_id'},3443 file_name=>$to->{'file'});3444}else{3445delete$to->{'href'};3446}3447}34483449## ......................................................................3450## parse to array of hashes functions34513452sub git_get_heads_list {3453my($limit,@classes) =@_;3454@classes= ('heads')unless@classes;3455my@patterns=map{"refs/$_"}@classes;3456my@headslist;34573458open my$fd,'-|', git_cmd(),'for-each-ref',3459($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3460'--format=%(objectname) %(refname) %(subject)%00%(committer)',3461@patterns3462orreturn;3463while(my$line= <$fd>) {3464my%ref_item;34653466chomp$line;3467my($refinfo,$committerinfo) =split(/\0/,$line);3468my($hash,$name,$title) =split(' ',$refinfo,3);3469my($committer,$epoch,$tz) =3470($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3471$ref_item{'fullname'} =$name;3472$name=~s!^refs/(?:head|remote)s/!!;34733474$ref_item{'name'} =$name;3475$ref_item{'id'} =$hash;3476$ref_item{'title'} =$title||'(no commit message)';3477$ref_item{'epoch'} =$epoch;3478if($epoch) {3479$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3480}else{3481$ref_item{'age'} ="unknown";3482}34833484push@headslist, \%ref_item;3485}3486close$fd;34873488returnwantarray?@headslist: \@headslist;3489}34903491sub git_get_tags_list {3492my$limit=shift;3493my@tagslist;34943495open my$fd,'-|', git_cmd(),'for-each-ref',3496($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3497'--format=%(objectname) %(objecttype) %(refname) '.3498'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3499'refs/tags'3500orreturn;3501while(my$line= <$fd>) {3502my%ref_item;35033504chomp$line;3505my($refinfo,$creatorinfo) =split(/\0/,$line);3506my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3507my($creator,$epoch,$tz) =3508($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3509$ref_item{'fullname'} =$name;3510$name=~s!^refs/tags/!!;35113512$ref_item{'type'} =$type;3513$ref_item{'id'} =$id;3514$ref_item{'name'} =$name;3515if($typeeq"tag") {3516$ref_item{'subject'} =$title;3517$ref_item{'reftype'} =$reftype;3518$ref_item{'refid'} =$refid;3519}else{3520$ref_item{'reftype'} =$type;3521$ref_item{'refid'} =$id;3522}35233524if($typeeq"tag"||$typeeq"commit") {3525$ref_item{'epoch'} =$epoch;3526if($epoch) {3527$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3528}else{3529$ref_item{'age'} ="unknown";3530}3531}35323533push@tagslist, \%ref_item;3534}3535close$fd;35363537returnwantarray?@tagslist: \@tagslist;3538}35393540## ----------------------------------------------------------------------3541## filesystem-related functions35423543sub get_file_owner {3544my$path=shift;35453546my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3547my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3548if(!defined$gcos) {3549returnundef;3550}3551my$owner=$gcos;3552$owner=~s/[,;].*$//;3553return to_utf8($owner);3554}35553556# assume that file exists3557sub insert_file {3558my$filename=shift;35593560open my$fd,'<',$filename;3561print map{ to_utf8($_) } <$fd>;3562close$fd;3563}35643565## ......................................................................3566## mimetype related functions35673568sub mimetype_guess_file {3569my$filename=shift;3570my$mimemap=shift;3571-r $mimemaporreturnundef;35723573my%mimemap;3574open(my$mh,'<',$mimemap)orreturnundef;3575while(<$mh>) {3576next ifm/^#/;# skip comments3577my($mimetype,$exts) =split(/\t+/);3578if(defined$exts) {3579my@exts=split(/\s+/,$exts);3580foreachmy$ext(@exts) {3581$mimemap{$ext} =$mimetype;3582}3583}3584}3585close($mh);35863587$filename=~/\.([^.]*)$/;3588return$mimemap{$1};3589}35903591sub mimetype_guess {3592my$filename=shift;3593my$mime;3594$filename=~/\./orreturnundef;35953596if($mimetypes_file) {3597my$file=$mimetypes_file;3598if($file!~m!^/!) {# if it is relative path3599# it is relative to project3600$file="$projectroot/$project/$file";3601}3602$mime= mimetype_guess_file($filename,$file);3603}3604$mime||= mimetype_guess_file($filename,'/etc/mime.types');3605return$mime;3606}36073608sub blob_mimetype {3609my$fd=shift;3610my$filename=shift;36113612if($filename) {3613my$mime= mimetype_guess($filename);3614$mimeandreturn$mime;3615}36163617# just in case3618return$default_blob_plain_mimetypeunless$fd;36193620if(-T $fd) {3621return'text/plain';3622}elsif(!$filename) {3623return'application/octet-stream';3624}elsif($filename=~m/\.png$/i) {3625return'image/png';3626}elsif($filename=~m/\.gif$/i) {3627return'image/gif';3628}elsif($filename=~m/\.jpe?g$/i) {3629return'image/jpeg';3630}else{3631return'application/octet-stream';3632}3633}36343635sub blob_contenttype {3636my($fd,$file_name,$type) =@_;36373638$type||= blob_mimetype($fd,$file_name);3639if($typeeq'text/plain'&&defined$default_text_plain_charset) {3640$type.="; charset=$default_text_plain_charset";3641}36423643return$type;3644}36453646# guess file syntax for syntax highlighting; return undef if no highlighting3647# the name of syntax can (in the future) depend on syntax highlighter used3648sub guess_file_syntax {3649my($highlight,$mimetype,$file_name) =@_;3650returnundefunless($highlight&&defined$file_name);3651my$basename= basename($file_name,'.in');3652return$highlight_basename{$basename}3653ifexists$highlight_basename{$basename};36543655$basename=~/\.([^.]*)$/;3656my$ext=$1orreturnundef;3657return$highlight_ext{$ext}3658ifexists$highlight_ext{$ext};36593660returnundef;3661}36623663# run highlighter and return FD of its output,3664# or return original FD if no highlighting3665sub run_highlighter {3666my($fd,$highlight,$syntax) =@_;3667return$fdunless($highlight&&defined$syntax);36683669close$fd;3670open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3671 quote_command($highlight_bin).3672" --replace-tabs=8 --fragment --syntax$syntax|"3673or die_error(500,"Couldn't open file or run syntax highlighter");3674return$fd;3675}36763677## ======================================================================3678## functions printing HTML: header, footer, error page36793680sub get_page_title {3681my$title= to_utf8($site_name);36823683return$titleunless(defined$project);3684$title.=" - ". to_utf8($project);36853686return$titleunless(defined$action);3687$title.="/$action";# $action is US-ASCII (7bit ASCII)36883689return$titleunless(defined$file_name);3690$title.=" - ". esc_path($file_name);3691if($actioneq"tree"&&$file_name!~ m|/$|) {3692$title.="/";3693}36943695return$title;3696}36973698sub print_feed_meta {3699if(defined$project) {3700my%href_params= get_feed_info();3701if(!exists$href_params{'-title'}) {3702$href_params{'-title'} ='log';3703}37043705foreachmy$format(qw(RSS Atom)) {3706my$type=lc($format);3707my%link_attr= (3708'-rel'=>'alternate',3709'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3710'-type'=>"application/$type+xml"3711);37123713$href_params{'action'} =$type;3714$link_attr{'-href'} = href(%href_params);3715print"<link ".3716"rel=\"$link_attr{'-rel'}\"".3717"title=\"$link_attr{'-title'}\"".3718"href=\"$link_attr{'-href'}\"".3719"type=\"$link_attr{'-type'}\"".3720"/>\n";37213722$href_params{'extra_options'} ='--no-merges';3723$link_attr{'-href'} = href(%href_params);3724$link_attr{'-title'} .=' (no merges)';3725print"<link ".3726"rel=\"$link_attr{'-rel'}\"".3727"title=\"$link_attr{'-title'}\"".3728"href=\"$link_attr{'-href'}\"".3729"type=\"$link_attr{'-type'}\"".3730"/>\n";3731}37323733}else{3734printf('<link rel="alternate" title="%sprojects list" '.3735'href="%s" type="text/plain; charset=utf-8" />'."\n",3736 esc_attr($site_name), href(project=>undef, action=>"project_index"));3737printf('<link rel="alternate" title="%sprojects feeds" '.3738'href="%s" type="text/x-opml" />'."\n",3739 esc_attr($site_name), href(project=>undef, action=>"opml"));3740}3741}37423743sub git_header_html {3744my$status=shift||"200 OK";3745my$expires=shift;3746my%opts=@_;37473748my$title= get_page_title();3749my$content_type;3750# require explicit support from the UA if we are to send the page as3751# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3752# we have to do this because MSIE sometimes globs '*/*', pretending to3753# support xhtml+xml but choking when it gets what it asked for.3754if(defined$cgi->http('HTTP_ACCEPT') &&3755$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3756$cgi->Accept('application/xhtml+xml') !=0) {3757$content_type='application/xhtml+xml';3758}else{3759$content_type='text/html';3760}3761print$cgi->header(-type=>$content_type, -charset =>'utf-8',3762-status=>$status, -expires =>$expires)3763unless($opts{'-no_http_header'});3764my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3765print<<EOF;3766<?xml version="1.0" encoding="utf-8"?>3767<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3768<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3769<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3770<!-- git core binaries version$git_version-->3771<head>3772<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3773<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3774<meta name="robots" content="index, nofollow"/>3775<title>$title</title>3776EOF3777# the stylesheet, favicon etc urls won't work correctly with path_info3778# unless we set the appropriate base URL3779if($ENV{'PATH_INFO'}) {3780print"<base href=\"".esc_url($base_url)."\"/>\n";3781}3782# print out each stylesheet that exist, providing backwards capability3783# for those people who defined $stylesheet in a config file3784if(defined$stylesheet) {3785print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3786}else{3787foreachmy$stylesheet(@stylesheets) {3788next unless$stylesheet;3789print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3790}3791}3792 print_feed_meta()3793if($statuseq'200 OK');3794if(defined$favicon) {3795printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);3796}37973798print"</head>\n".3799"<body>\n";38003801if(defined$site_header&& -f $site_header) {3802 insert_file($site_header);3803}38043805print"<div class=\"page_header\">\n";3806if(defined$logo) {3807print$cgi->a({-href => esc_url($logo_url),3808-title =>$logo_label},3809$cgi->img({-src => esc_url($logo),3810-width =>72, -height =>27,3811-alt =>"git",3812-class=>"logo"}));3813}3814print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3815if(defined$project) {3816print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3817if(defined$action) {3818my$action_print=$action;3819if(defined$opts{-action_extra}) {3820$action_print=$cgi->a({-href => href(action=>$action)},3821$action);3822}3823print" /$action_print";3824}3825if(defined$opts{-action_extra}) {3826print" /$opts{-action_extra}";3827}3828print"\n";3829}3830print"</div>\n";38313832my$have_search= gitweb_check_feature('search');3833if(defined$project&&$have_search) {3834if(!defined$searchtext) {3835$searchtext="";3836}3837my$search_hash;3838if(defined$hash_base) {3839$search_hash=$hash_base;3840}elsif(defined$hash) {3841$search_hash=$hash;3842}else{3843$search_hash="HEAD";3844}3845my$action=$my_uri;3846my$use_pathinfo= gitweb_check_feature('pathinfo');3847if($use_pathinfo) {3848$action.="/".esc_url($project);3849}3850print$cgi->startform(-method=>"get", -action =>$action) .3851"<div class=\"search\">\n".3852(!$use_pathinfo&&3853$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3854$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3855$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3856$cgi->popup_menu(-name =>'st', -default=>'commit',3857-values=> ['commit','grep','author','committer','pickaxe']) .3858$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3859" search:\n",3860$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3861"<span title=\"Extended regular expression\">".3862$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3863-checked =>$search_use_regexp) .3864"</span>".3865"</div>".3866$cgi->end_form() ."\n";3867}3868}38693870sub git_footer_html {3871my$feed_class='rss_logo';38723873print"<div class=\"page_footer\">\n";3874if(defined$project) {3875my$descr= git_get_project_description($project);3876if(defined$descr) {3877print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3878}38793880my%href_params= get_feed_info();3881if(!%href_params) {3882$feed_class.=' generic';3883}3884$href_params{'-title'} ||='log';38853886foreachmy$format(qw(RSS Atom)) {3887$href_params{'action'} =lc($format);3888print$cgi->a({-href => href(%href_params),3889-title =>"$href_params{'-title'}$formatfeed",3890-class=>$feed_class},$format)."\n";3891}38923893}else{3894print$cgi->a({-href => href(project=>undef, action=>"opml"),3895-class=>$feed_class},"OPML") ." ";3896print$cgi->a({-href => href(project=>undef, action=>"project_index"),3897-class=>$feed_class},"TXT") ."\n";3898}3899print"</div>\n";# class="page_footer"39003901if(defined$t0&& gitweb_check_feature('timed')) {3902print"<div id=\"generating_info\">\n";3903print'This page took '.3904'<span id="generating_time" class="time_span">'.3905 tv_interval($t0, [ gettimeofday() ]).3906' seconds </span>'.3907' and '.3908'<span id="generating_cmd">'.3909$number_of_git_cmds.3910'</span> git commands '.3911" to generate.\n";3912print"</div>\n";# class="page_footer"3913}39143915if(defined$site_footer&& -f $site_footer) {3916 insert_file($site_footer);3917}39183919print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;3920if(defined$action&&3921$actioneq'blame_incremental') {3922print qq!<script type="text/javascript">\n!.3923 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.3924 qq!"!. href() .qq!");\n!.3925 qq!</script>\n!;3926}else{3927my($jstimezone,$tz_cookie,$datetime_class) =3928 gitweb_get_feature('javascript-timezone');39293930print qq!<script type="text/javascript">\n!.3931 qq!window.onload = function () {\n!;3932if(gitweb_check_feature('javascript-actions')) {3933print qq! fixLinks();\n!;3934}3935if($jstimezone&&$tz_cookie&&$datetime_class) {3936print qq! var tz_cookie = { name:'$tz_cookie', expires:14, path:'/'};\n!.# in days3937 qq! onloadTZSetup('$jstimezone', tz_cookie,'$datetime_class');\n!;3938}3939print qq!};\n!.3940 qq!</script>\n!;3941}39423943print"</body>\n".3944"</html>";3945}39463947# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])3948# Example: die_error(404, 'Hash not found')3949# By convention, use the following status codes (as defined in RFC 2616):3950# 400: Invalid or missing CGI parameters, or3951# requested object exists but has wrong type.3952# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3953# this server or project.3954# 404: Requested object/revision/project doesn't exist.3955# 500: The server isn't configured properly, or3956# an internal error occurred (e.g. failed assertions caused by bugs), or3957# an unknown error occurred (e.g. the git binary died unexpectedly).3958# 503: The server is currently unavailable (because it is overloaded,3959# or down for maintenance). Generally, this is a temporary state.3960sub die_error {3961my$status=shift||500;3962my$error= esc_html(shift) ||"Internal Server Error";3963my$extra=shift;3964my%opts=@_;39653966my%http_responses= (3967400=>'400 Bad Request',3968403=>'403 Forbidden',3969404=>'404 Not Found',3970500=>'500 Internal Server Error',3971503=>'503 Service Unavailable',3972);3973 git_header_html($http_responses{$status},undef,%opts);3974print<<EOF;3975<div class="page_body">3976<br /><br />3977$status-$error3978<br />3979EOF3980if(defined$extra) {3981print"<hr />\n".3982"$extra\n";3983}3984print"</div>\n";39853986 git_footer_html();3987goto DONE_GITWEB3988unless($opts{'-error_handler'});3989}39903991## ----------------------------------------------------------------------3992## functions printing or outputting HTML: navigation39933994sub git_print_page_nav {3995my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;3996$extra=''if!defined$extra;# pager or formats39973998my@navs=qw(summary shortlog log commit commitdiff tree);3999if($suppress) {4000@navs=grep{$_ne$suppress}@navs;4001}40024003my%arg=map{$_=> {action=>$_} }@navs;4004if(defined$head) {4005for(qw(commit commitdiff)) {4006$arg{$_}{'hash'} =$head;4007}4008if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {4009for(qw(shortlog log)) {4010$arg{$_}{'hash'} =$head;4011}4012}4013}40144015$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;4016$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;40174018my@actions= gitweb_get_feature('actions');4019my%repl= (4020'%'=>'%',4021'n'=>$project,# project name4022'f'=>$git_dir,# project path within filesystem4023'h'=>$treehead||'',# current hash ('h' parameter)4024'b'=>$treebase||'',# hash base ('hb' parameter)4025);4026while(@actions) {4027my($label,$link,$pos) =splice(@actions,0,3);4028# insert4029@navs=map{$_eq$pos? ($_,$label) :$_}@navs;4030# munch munch4031$link=~s/%([%nfhb])/$repl{$1}/g;4032$arg{$label}{'_href'} =$link;4033}40344035print"<div class=\"page_nav\">\n".4036(join" | ",4037map{$_eq$current?4038$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4039}@navs);4040print"<br/>\n$extra<br/>\n".4041"</div>\n";4042}40434044# returns a submenu for the nagivation of the refs views (tags, heads,4045# remotes) with the current view disabled and the remotes view only4046# available if the feature is enabled4047sub format_ref_views {4048my($current) =@_;4049my@ref_views=qw{tags heads};4050push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4051returnjoin" | ",map{4052$_eq$current?$_:4053$cgi->a({-href => href(action=>$_)},$_)4054}@ref_views4055}40564057sub format_paging_nav {4058my($action,$page,$has_next_link) =@_;4059my$paging_nav;406040614062if($page>0) {4063$paging_nav.=4064$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4065" ⋅ ".4066$cgi->a({-href => href(-replay=>1, page=>$page-1),4067-accesskey =>"p", -title =>"Alt-p"},"prev");4068}else{4069$paging_nav.="first ⋅ prev";4070}40714072if($has_next_link) {4073$paging_nav.=" ⋅ ".4074$cgi->a({-href => href(-replay=>1, page=>$page+1),4075-accesskey =>"n", -title =>"Alt-n"},"next");4076}else{4077$paging_nav.=" ⋅ next";4078}40794080return$paging_nav;4081}40824083## ......................................................................4084## functions printing or outputting HTML: div40854086sub git_print_header_div {4087my($action,$title,$hash,$hash_base) =@_;4088my%args= ();40894090$args{'action'} =$action;4091$args{'hash'} =$hashif$hash;4092$args{'hash_base'} =$hash_baseif$hash_base;40934094print"<div class=\"header\">\n".4095$cgi->a({-href => href(%args), -class=>"title"},4096$title?$title:$action) .4097"\n</div>\n";4098}40994100sub format_repo_url {4101my($name,$url) =@_;4102return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4103}41044105# Group output by placing it in a DIV element and adding a header.4106# Options for start_div() can be provided by passing a hash reference as the4107# first parameter to the function.4108# Options to git_print_header_div() can be provided by passing an array4109# reference. This must follow the options to start_div if they are present.4110# The content can be a scalar, which is output as-is, a scalar reference, which4111# is output after html escaping, an IO handle passed either as *handle or4112# *handle{IO}, or a function reference. In the latter case all following4113# parameters will be taken as argument to the content function call.4114sub git_print_section {4115my($div_args,$header_args,$content);4116my$arg=shift;4117if(ref($arg)eq'HASH') {4118$div_args=$arg;4119$arg=shift;4120}4121if(ref($arg)eq'ARRAY') {4122$header_args=$arg;4123$arg=shift;4124}4125$content=$arg;41264127print$cgi->start_div($div_args);4128 git_print_header_div(@$header_args);41294130if(ref($content)eq'CODE') {4131$content->(@_);4132}elsif(ref($content)eq'SCALAR') {4133print esc_html($$content);4134}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4135print<$content>;4136}elsif(!ref($content) &&defined($content)) {4137print$content;4138}41394140print$cgi->end_div;4141}41424143sub format_timestamp_html {4144my$date=shift;4145my$strtime=$date->{'rfc2822'};41464147my(undef,undef,$datetime_class) =4148 gitweb_get_feature('javascript-timezone');4149if($datetime_class) {4150$strtime= qq!<span class="$datetime_class">$strtime</span>!;4151}41524153my$localtime_format='(%02d:%02d%s)';4154if($date->{'hour_local'} <6) {4155$localtime_format='(<span class="atnight">%02d:%02d</span>%s)';4156}4157$strtime.=' '.4158sprintf($localtime_format,4159$date->{'hour_local'},$date->{'minute_local'},$date->{'tz_local'});41604161return$strtime;4162}41634164# Outputs the author name and date in long form4165sub git_print_authorship {4166my$co=shift;4167my%opts=@_;4168my$tag=$opts{-tag} ||'div';4169my$author=$co->{'author_name'};41704171my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4172print"<$tagclass=\"author_date\">".4173 format_search_author($author,"author", esc_html($author)) .4174" [".format_timestamp_html(\%ad)."]".4175 git_get_avatar($co->{'author_email'}, -pad_before =>1) .4176"</$tag>\n";4177}41784179# Outputs table rows containing the full author or committer information,4180# in the format expected for 'commit' view (& similar).4181# Parameters are a commit hash reference, followed by the list of people4182# to output information for. If the list is empty it defaults to both4183# author and committer.4184sub git_print_authorship_rows {4185my$co=shift;4186# too bad we can't use @people = @_ || ('author', 'committer')4187my@people=@_;4188@people= ('author','committer')unless@people;4189foreachmy$who(@people) {4190my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4191print"<tr><td>$who</td><td>".4192 format_search_author($co->{"${who}_name"},$who,4193 esc_html($co->{"${who}_name"})) ." ".4194 format_search_author($co->{"${who}_email"},$who,4195 esc_html("<".$co->{"${who}_email"} .">")) .4196"</td><td rowspan=\"2\">".4197 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4198"</td></tr>\n".4199"<tr>".4200"<td></td><td>".4201 format_timestamp_html(\%wd) .4202"</td>".4203"</tr>\n";4204}4205}42064207sub git_print_page_path {4208my$name=shift;4209my$type=shift;4210my$hb=shift;421142124213print"<div class=\"page_path\">";4214print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4215-title =>'tree root'}, to_utf8("[$project]"));4216print" / ";4217if(defined$name) {4218my@dirname=split'/',$name;4219my$basename=pop@dirname;4220my$fullname='';42214222foreachmy$dir(@dirname) {4223$fullname.= ($fullname?'/':'') .$dir;4224print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4225 hash_base=>$hb),4226-title =>$fullname}, esc_path($dir));4227print" / ";4228}4229if(defined$type&&$typeeq'blob') {4230print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4231 hash_base=>$hb),4232-title =>$name}, esc_path($basename));4233}elsif(defined$type&&$typeeq'tree') {4234print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4235 hash_base=>$hb),4236-title =>$name}, esc_path($basename));4237print" / ";4238}else{4239print esc_path($basename);4240}4241}4242print"<br/></div>\n";4243}42444245sub git_print_log {4246my$log=shift;4247my%opts=@_;42484249if($opts{'-remove_title'}) {4250# remove title, i.e. first line of log4251shift@$log;4252}4253# remove leading empty lines4254while(defined$log->[0] &&$log->[0]eq"") {4255shift@$log;4256}42574258# print log4259my$signoff=0;4260my$empty=0;4261foreachmy$line(@$log) {4262if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {4263$signoff=1;4264$empty=0;4265if(!$opts{'-remove_signoff'}) {4266print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4267next;4268}else{4269# remove signoff lines4270next;4271}4272}else{4273$signoff=0;4274}42754276# print only one empty line4277# do not print empty line after signoff4278if($lineeq"") {4279next if($empty||$signoff);4280$empty=1;4281}else{4282$empty=0;4283}42844285print format_log_line_html($line) ."<br/>\n";4286}42874288if($opts{'-final_empty_line'}) {4289# end with single empty line4290print"<br/>\n"unless$empty;4291}4292}42934294# return link target (what link points to)4295sub git_get_link_target {4296my$hash=shift;4297my$link_target;42984299# read link4300open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4301orreturn;4302{4303local$/=undef;4304$link_target= <$fd>;4305}4306close$fd4307orreturn;43084309return$link_target;4310}43114312# given link target, and the directory (basedir) the link is in,4313# return target of link relative to top directory (top tree);4314# return undef if it is not possible (including absolute links).4315sub normalize_link_target {4316my($link_target,$basedir) =@_;43174318# absolute symlinks (beginning with '/') cannot be normalized4319return if(substr($link_target,0,1)eq'/');43204321# normalize link target to path from top (root) tree (dir)4322my$path;4323if($basedir) {4324$path=$basedir.'/'.$link_target;4325}else{4326# we are in top (root) tree (dir)4327$path=$link_target;4328}43294330# remove //, /./, and /../4331my@path_parts;4332foreachmy$part(split('/',$path)) {4333# discard '.' and ''4334next if(!$part||$parteq'.');4335# handle '..'4336if($parteq'..') {4337if(@path_parts) {4338pop@path_parts;4339}else{4340# link leads outside repository (outside top dir)4341return;4342}4343}else{4344push@path_parts,$part;4345}4346}4347$path=join('/',@path_parts);43484349return$path;4350}43514352# print tree entry (row of git_tree), but without encompassing <tr> element4353sub git_print_tree_entry {4354my($t,$basedir,$hash_base,$have_blame) =@_;43554356my%base_key= ();4357$base_key{'hash_base'} =$hash_baseifdefined$hash_base;43584359# The format of a table row is: mode list link. Where mode is4360# the mode of the entry, list is the name of the entry, an href,4361# and link is the action links of the entry.43624363print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4364if(exists$t->{'size'}) {4365print"<td class=\"size\">$t->{'size'}</td>\n";4366}4367if($t->{'type'}eq"blob") {4368print"<td class=\"list\">".4369$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4370 file_name=>"$basedir$t->{'name'}",%base_key),4371-class=>"list"}, esc_path($t->{'name'}));4372if(S_ISLNK(oct$t->{'mode'})) {4373my$link_target= git_get_link_target($t->{'hash'});4374if($link_target) {4375my$norm_target= normalize_link_target($link_target,$basedir);4376if(defined$norm_target) {4377print" -> ".4378$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4379 file_name=>$norm_target),4380-title =>$norm_target}, esc_path($link_target));4381}else{4382print" -> ". esc_path($link_target);4383}4384}4385}4386print"</td>\n";4387print"<td class=\"link\">";4388print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4389 file_name=>"$basedir$t->{'name'}",%base_key)},4390"blob");4391if($have_blame) {4392print" | ".4393$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4394 file_name=>"$basedir$t->{'name'}",%base_key)},4395"blame");4396}4397if(defined$hash_base) {4398print" | ".4399$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4400 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4401"history");4402}4403print" | ".4404$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4405 file_name=>"$basedir$t->{'name'}")},4406"raw");4407print"</td>\n";44084409}elsif($t->{'type'}eq"tree") {4410print"<td class=\"list\">";4411print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4412 file_name=>"$basedir$t->{'name'}",4413%base_key)},4414 esc_path($t->{'name'}));4415print"</td>\n";4416print"<td class=\"link\">";4417print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4418 file_name=>"$basedir$t->{'name'}",4419%base_key)},4420"tree");4421if(defined$hash_base) {4422print" | ".4423$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4424 file_name=>"$basedir$t->{'name'}")},4425"history");4426}4427print"</td>\n";4428}else{4429# unknown object: we can only present history for it4430# (this includes 'commit' object, i.e. submodule support)4431print"<td class=\"list\">".4432 esc_path($t->{'name'}) .4433"</td>\n";4434print"<td class=\"link\">";4435if(defined$hash_base) {4436print$cgi->a({-href => href(action=>"history",4437 hash_base=>$hash_base,4438 file_name=>"$basedir$t->{'name'}")},4439"history");4440}4441print"</td>\n";4442}4443}44444445## ......................................................................4446## functions printing large fragments of HTML44474448# get pre-image filenames for merge (combined) diff4449sub fill_from_file_info {4450my($diff,@parents) =@_;44514452$diff->{'from_file'} = [ ];4453$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4454for(my$i=0;$i<$diff->{'nparents'};$i++) {4455if($diff->{'status'}[$i]eq'R'||4456$diff->{'status'}[$i]eq'C') {4457$diff->{'from_file'}[$i] =4458 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4459}4460}44614462return$diff;4463}44644465# is current raw difftree line of file deletion4466sub is_deleted {4467my$diffinfo=shift;44684469return$diffinfo->{'to_id'}eq('0' x 40);4470}44714472# does patch correspond to [previous] difftree raw line4473# $diffinfo - hashref of parsed raw diff format4474# $patchinfo - hashref of parsed patch diff format4475# (the same keys as in $diffinfo)4476sub is_patch_split {4477my($diffinfo,$patchinfo) =@_;44784479returndefined$diffinfo&&defined$patchinfo4480&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4481}448244834484sub git_difftree_body {4485my($difftree,$hash,@parents) =@_;4486my($parent) =$parents[0];4487my$have_blame= gitweb_check_feature('blame');4488print"<div class=\"list_head\">\n";4489if($#{$difftree} >10) {4490print(($#{$difftree} +1) ." files changed:\n");4491}4492print"</div>\n";44934494print"<table class=\"".4495(@parents>1?"combined ":"") .4496"diff_tree\">\n";44974498# header only for combined diff in 'commitdiff' view4499my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4500if($has_header) {4501# table header4502print"<thead><tr>\n".4503"<th></th><th></th>\n";# filename, patchN link4504for(my$i=0;$i<@parents;$i++) {4505my$par=$parents[$i];4506print"<th>".4507$cgi->a({-href => href(action=>"commitdiff",4508 hash=>$hash, hash_parent=>$par),4509-title =>'commitdiff to parent number '.4510($i+1) .': '.substr($par,0,7)},4511$i+1) .4512" </th>\n";4513}4514print"</tr></thead>\n<tbody>\n";4515}45164517my$alternate=1;4518my$patchno=0;4519foreachmy$line(@{$difftree}) {4520my$diff= parsed_difftree_line($line);45214522if($alternate) {4523print"<tr class=\"dark\">\n";4524}else{4525print"<tr class=\"light\">\n";4526}4527$alternate^=1;45284529if(exists$diff->{'nparents'}) {# combined diff45304531 fill_from_file_info($diff,@parents)4532unlessexists$diff->{'from_file'};45334534if(!is_deleted($diff)) {4535# file exists in the result (child) commit4536print"<td>".4537$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4538 file_name=>$diff->{'to_file'},4539 hash_base=>$hash),4540-class=>"list"}, esc_path($diff->{'to_file'})) .4541"</td>\n";4542}else{4543print"<td>".4544 esc_path($diff->{'to_file'}) .4545"</td>\n";4546}45474548if($actioneq'commitdiff') {4549# link to patch4550$patchno++;4551print"<td class=\"link\">".4552$cgi->a({-href => href(-anchor=>"patch$patchno")},4553"patch") .4554" | ".4555"</td>\n";4556}45574558my$has_history=0;4559my$not_deleted=0;4560for(my$i=0;$i<$diff->{'nparents'};$i++) {4561my$hash_parent=$parents[$i];4562my$from_hash=$diff->{'from_id'}[$i];4563my$from_path=$diff->{'from_file'}[$i];4564my$status=$diff->{'status'}[$i];45654566$has_history||= ($statusne'A');4567$not_deleted||= ($statusne'D');45684569if($statuseq'A') {4570print"<td class=\"link\"align=\"right\"> | </td>\n";4571}elsif($statuseq'D') {4572print"<td class=\"link\">".4573$cgi->a({-href => href(action=>"blob",4574 hash_base=>$hash,4575 hash=>$from_hash,4576 file_name=>$from_path)},4577"blob". ($i+1)) .4578" | </td>\n";4579}else{4580if($diff->{'to_id'}eq$from_hash) {4581print"<td class=\"link nochange\">";4582}else{4583print"<td class=\"link\">";4584}4585print$cgi->a({-href => href(action=>"blobdiff",4586 hash=>$diff->{'to_id'},4587 hash_parent=>$from_hash,4588 hash_base=>$hash,4589 hash_parent_base=>$hash_parent,4590 file_name=>$diff->{'to_file'},4591 file_parent=>$from_path)},4592"diff". ($i+1)) .4593" | </td>\n";4594}4595}45964597print"<td class=\"link\">";4598if($not_deleted) {4599print$cgi->a({-href => href(action=>"blob",4600 hash=>$diff->{'to_id'},4601 file_name=>$diff->{'to_file'},4602 hash_base=>$hash)},4603"blob");4604print" | "if($has_history);4605}4606if($has_history) {4607print$cgi->a({-href => href(action=>"history",4608 file_name=>$diff->{'to_file'},4609 hash_base=>$hash)},4610"history");4611}4612print"</td>\n";46134614print"</tr>\n";4615next;# instead of 'else' clause, to avoid extra indent4616}4617# else ordinary diff46184619my($to_mode_oct,$to_mode_str,$to_file_type);4620my($from_mode_oct,$from_mode_str,$from_file_type);4621if($diff->{'to_mode'}ne('0' x 6)) {4622$to_mode_oct=oct$diff->{'to_mode'};4623if(S_ISREG($to_mode_oct)) {# only for regular file4624$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4625}4626$to_file_type= file_type($diff->{'to_mode'});4627}4628if($diff->{'from_mode'}ne('0' x 6)) {4629$from_mode_oct=oct$diff->{'from_mode'};4630if(S_ISREG($from_mode_oct)) {# only for regular file4631$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4632}4633$from_file_type= file_type($diff->{'from_mode'});4634}46354636if($diff->{'status'}eq"A") {# created4637my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4638$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4639$mode_chng.="]</span>";4640print"<td>";4641print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4642 hash_base=>$hash, file_name=>$diff->{'file'}),4643-class=>"list"}, esc_path($diff->{'file'}));4644print"</td>\n";4645print"<td>$mode_chng</td>\n";4646print"<td class=\"link\">";4647if($actioneq'commitdiff') {4648# link to patch4649$patchno++;4650print$cgi->a({-href => href(-anchor=>"patch$patchno")},4651"patch") .4652" | ";4653}4654print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4655 hash_base=>$hash, file_name=>$diff->{'file'})},4656"blob");4657print"</td>\n";46584659}elsif($diff->{'status'}eq"D") {# deleted4660my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4661print"<td>";4662print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4663 hash_base=>$parent, file_name=>$diff->{'file'}),4664-class=>"list"}, esc_path($diff->{'file'}));4665print"</td>\n";4666print"<td>$mode_chng</td>\n";4667print"<td class=\"link\">";4668if($actioneq'commitdiff') {4669# link to patch4670$patchno++;4671print$cgi->a({-href => href(-anchor=>"patch$patchno")},4672"patch") .4673" | ";4674}4675print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4676 hash_base=>$parent, file_name=>$diff->{'file'})},4677"blob") ." | ";4678if($have_blame) {4679print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4680 file_name=>$diff->{'file'})},4681"blame") ." | ";4682}4683print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4684 file_name=>$diff->{'file'})},4685"history");4686print"</td>\n";46874688}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4689my$mode_chnge="";4690if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4691$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4692if($from_file_typene$to_file_type) {4693$mode_chnge.=" from$from_file_typeto$to_file_type";4694}4695if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4696if($from_mode_str&&$to_mode_str) {4697$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4698}elsif($to_mode_str) {4699$mode_chnge.=" mode:$to_mode_str";4700}4701}4702$mode_chnge.="]</span>\n";4703}4704print"<td>";4705print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4706 hash_base=>$hash, file_name=>$diff->{'file'}),4707-class=>"list"}, esc_path($diff->{'file'}));4708print"</td>\n";4709print"<td>$mode_chnge</td>\n";4710print"<td class=\"link\">";4711if($actioneq'commitdiff') {4712# link to patch4713$patchno++;4714print$cgi->a({-href => href(-anchor=>"patch$patchno")},4715"patch") .4716" | ";4717}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4718# "commit" view and modified file (not onlu mode changed)4719print$cgi->a({-href => href(action=>"blobdiff",4720 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4721 hash_base=>$hash, hash_parent_base=>$parent,4722 file_name=>$diff->{'file'})},4723"diff") .4724" | ";4725}4726print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4727 hash_base=>$hash, file_name=>$diff->{'file'})},4728"blob") ." | ";4729if($have_blame) {4730print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4731 file_name=>$diff->{'file'})},4732"blame") ." | ";4733}4734print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4735 file_name=>$diff->{'file'})},4736"history");4737print"</td>\n";47384739}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4740my%status_name= ('R'=>'moved','C'=>'copied');4741my$nstatus=$status_name{$diff->{'status'}};4742my$mode_chng="";4743if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4744# mode also for directories, so we cannot use $to_mode_str4745$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4746}4747print"<td>".4748$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4749 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4750-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4751"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4752$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4753 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4754-class=>"list"}, esc_path($diff->{'from_file'})) .4755" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4756"<td class=\"link\">";4757if($actioneq'commitdiff') {4758# link to patch4759$patchno++;4760print$cgi->a({-href => href(-anchor=>"patch$patchno")},4761"patch") .4762" | ";4763}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4764# "commit" view and modified file (not only pure rename or copy)4765print$cgi->a({-href => href(action=>"blobdiff",4766 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4767 hash_base=>$hash, hash_parent_base=>$parent,4768 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4769"diff") .4770" | ";4771}4772print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4773 hash_base=>$parent, file_name=>$diff->{'to_file'})},4774"blob") ." | ";4775if($have_blame) {4776print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4777 file_name=>$diff->{'to_file'})},4778"blame") ." | ";4779}4780print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4781 file_name=>$diff->{'to_file'})},4782"history");4783print"</td>\n";47844785}# we should not encounter Unmerged (U) or Unknown (X) status4786print"</tr>\n";4787}4788print"</tbody>"if$has_header;4789print"</table>\n";4790}47914792sub git_patchset_body {4793my($fd,$difftree,$hash,@hash_parents) =@_;4794my($hash_parent) =$hash_parents[0];47954796my$is_combined= (@hash_parents>1);4797my$patch_idx=0;4798my$patch_number=0;4799my$patch_line;4800my$diffinfo;4801my$to_name;4802my(%from,%to);48034804print"<div class=\"patchset\">\n";48054806# skip to first patch4807while($patch_line= <$fd>) {4808chomp$patch_line;48094810last if($patch_line=~m/^diff /);4811}48124813 PATCH:4814while($patch_line) {48154816# parse "git diff" header line4817if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4818# $1 is from_name, which we do not use4819$to_name= unquote($2);4820$to_name=~s!^b/!!;4821}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4822# $1 is 'cc' or 'combined', which we do not use4823$to_name= unquote($2);4824}else{4825$to_name=undef;4826}48274828# check if current patch belong to current raw line4829# and parse raw git-diff line if needed4830if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4831# this is continuation of a split patch4832print"<div class=\"patch cont\">\n";4833}else{4834# advance raw git-diff output if needed4835$patch_idx++ifdefined$diffinfo;48364837# read and prepare patch information4838$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);48394840# compact combined diff output can have some patches skipped4841# find which patch (using pathname of result) we are at now;4842if($is_combined) {4843while($to_namene$diffinfo->{'to_file'}) {4844print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4845 format_diff_cc_simplified($diffinfo,@hash_parents) .4846"</div>\n";# class="patch"48474848$patch_idx++;4849$patch_number++;48504851last if$patch_idx>$#$difftree;4852$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4853}4854}48554856# modifies %from, %to hashes4857 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);48584859# this is first patch for raw difftree line with $patch_idx index4860# we index @$difftree array from 0, but number patches from 14861print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4862}48634864# git diff header4865#assert($patch_line =~ m/^diff /) if DEBUG;4866#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4867$patch_number++;4868# print "git diff" header4869print format_git_diff_header_line($patch_line,$diffinfo,4870 \%from, \%to);48714872# print extended diff header4873print"<div class=\"diff extended_header\">\n";4874 EXTENDED_HEADER:4875while($patch_line= <$fd>) {4876chomp$patch_line;48774878last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);48794880print format_extended_diff_header_line($patch_line,$diffinfo,4881 \%from, \%to);4882}4883print"</div>\n";# class="diff extended_header"48844885# from-file/to-file diff header4886if(!$patch_line) {4887print"</div>\n";# class="patch"4888last PATCH;4889}4890next PATCH if($patch_line=~m/^diff /);4891#assert($patch_line =~ m/^---/) if DEBUG;48924893my$last_patch_line=$patch_line;4894$patch_line= <$fd>;4895chomp$patch_line;4896#assert($patch_line =~ m/^\+\+\+/) if DEBUG;48974898print format_diff_from_to_header($last_patch_line,$patch_line,4899$diffinfo, \%from, \%to,4900@hash_parents);49014902# the patch itself4903 LINE:4904while($patch_line= <$fd>) {4905chomp$patch_line;49064907next PATCH if($patch_line=~m/^diff /);49084909print format_diff_line($patch_line, \%from, \%to);4910}49114912}continue{4913print"</div>\n";# class="patch"4914}49154916# for compact combined (--cc) format, with chunk and patch simplification4917# the patchset might be empty, but there might be unprocessed raw lines4918for(++$patch_idxif$patch_number>0;4919$patch_idx<@$difftree;4920++$patch_idx) {4921# read and prepare patch information4922$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);49234924# generate anchor for "patch" links in difftree / whatchanged part4925print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4926 format_diff_cc_simplified($diffinfo,@hash_parents) .4927"</div>\n";# class="patch"49284929$patch_number++;4930}49314932if($patch_number==0) {4933if(@hash_parents>1) {4934print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4935}else{4936print"<div class=\"diff nodifferences\">No differences found</div>\n";4937}4938}49394940print"</div>\n";# class="patchset"4941}49424943# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49444945# fills project list info (age, description, owner, category, forks)4946# for each project in the list, removing invalid projects from4947# returned list4948# NOTE: modifies $projlist, but does not remove entries from it4949sub fill_project_list_info {4950my$projlist=shift;4951my@projects;49524953my$show_ctags= gitweb_check_feature('ctags');4954 PROJECT:4955foreachmy$pr(@$projlist) {4956my(@activity) = git_get_last_activity($pr->{'path'});4957unless(@activity) {4958next PROJECT;4959}4960($pr->{'age'},$pr->{'age_string'}) =@activity;4961if(!defined$pr->{'descr'}) {4962my$descr= git_get_project_description($pr->{'path'}) ||"";4963$descr= to_utf8($descr);4964$pr->{'descr_long'} =$descr;4965$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);4966}4967if(!defined$pr->{'owner'}) {4968$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";4969}4970if($show_ctags) {4971$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});4972}4973if($projects_list_group_categories&& !defined$pr->{'category'}) {4974my$cat= git_get_project_category($pr->{'path'}) ||4975$project_list_default_category;4976$pr->{'category'} = to_utf8($cat);4977}49784979push@projects,$pr;4980}49814982return@projects;4983}49844985sub sort_projects_list {4986my($projlist,$order) =@_;4987my@projects;49884989my%order_info= (4990 project => { key =>'path', type =>'str'},4991 descr => { key =>'descr_long', type =>'str'},4992 owner => { key =>'owner', type =>'str'},4993 age => { key =>'age', type =>'num'}4994);4995my$oi=$order_info{$order};4996return@$projlistunlessdefined$oi;4997if($oi->{'type'}eq'str') {4998@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@$projlist;4999}else{5000@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@$projlist;5001}50025003return@projects;5004}50055006# returns a hash of categories, containing the list of project5007# belonging to each category5008sub build_projlist_by_category {5009my($projlist,$from,$to) =@_;5010my%categories;50115012$from=0unlessdefined$from;5013$to=$#$projlistif(!defined$to||$#$projlist<$to);50145015for(my$i=$from;$i<=$to;$i++) {5016my$pr=$projlist->[$i];5017push@{$categories{$pr->{'category'} }},$pr;5018}50195020returnwantarray?%categories: \%categories;5021}50225023# print 'sort by' <th> element, generating 'sort by $name' replay link5024# if that order is not selected5025sub print_sort_th {5026print format_sort_th(@_);5027}50285029sub format_sort_th {5030my($name,$order,$header) =@_;5031my$sort_th="";5032$header||=ucfirst($name);50335034if($ordereq$name) {5035$sort_th.="<th>$header</th>\n";5036}else{5037$sort_th.="<th>".5038$cgi->a({-href => href(-replay=>1, order=>$name),5039-class=>"header"},$header) .5040"</th>\n";5041}50425043return$sort_th;5044}50455046sub git_project_list_rows {5047my($projlist,$from,$to,$check_forks) =@_;50485049$from=0unlessdefined$from;5050$to=$#$projlistif(!defined$to||$#$projlist<$to);50515052my$alternate=1;5053for(my$i=$from;$i<=$to;$i++) {5054my$pr=$projlist->[$i];50555056if($alternate) {5057print"<tr class=\"dark\">\n";5058}else{5059print"<tr class=\"light\">\n";5060}5061$alternate^=1;50625063if($check_forks) {5064print"<td>";5065if($pr->{'forks'}) {5066my$nforks=scalar@{$pr->{'forks'}};5067if($nforks>0) {5068print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5069-title =>"$nforksforks"},"+");5070}else{5071print$cgi->span({-title =>"$nforksforks"},"+");5072}5073}5074print"</td>\n";5075}5076print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5077-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".5078"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5079-class=>"list", -title =>$pr->{'descr_long'}},5080 esc_html($pr->{'descr'})) ."</td>\n".5081"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5082print"<td class=\"". age_class($pr->{'age'}) ."\">".5083(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".5084"<td class=\"link\">".5085$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5086$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5087$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5088$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5089($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5090"</td>\n".5091"</tr>\n";5092}5093}50945095sub git_project_list_body {5096# actually uses global variable $project5097my($projlist,$order,$from,$to,$extra,$no_header) =@_;5098my@projects=@$projlist;50995100my$check_forks= gitweb_check_feature('forks');5101my$show_ctags= gitweb_check_feature('ctags');5102my$tagfilter=$show_ctags?$cgi->param('by_tag') :undef;5103$check_forks=undef5104if($tagfilter||$searchtext);51055106# filtering out forks before filling info allows to do less work5107@projects= filter_forks_from_projects_list(\@projects)5108if($check_forks);5109@projects= fill_project_list_info(\@projects);5110# searching projects require filling to be run before it5111@projects= search_projects_list(\@projects,5112'searchtext'=>$searchtext,5113'tagfilter'=>$tagfilter)5114if($tagfilter||$searchtext);51155116$order||=$default_projects_order;5117$from=0unlessdefined$from;5118$to=$#projectsif(!defined$to||$#projects<$to);51195120# short circuit5121if($from>$to) {5122print"<center>\n".5123"<b>No such projects found</b><br />\n".5124"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5125"</center>\n<br />\n";5126return;5127}51285129@projects= sort_projects_list(\@projects,$order);51305131if($show_ctags) {5132my$ctags= git_gather_all_ctags(\@projects);5133my$cloud= git_populate_project_tagcloud($ctags);5134print git_show_project_tagcloud($cloud,64);5135}51365137print"<table class=\"project_list\">\n";5138unless($no_header) {5139print"<tr>\n";5140if($check_forks) {5141print"<th></th>\n";5142}5143 print_sort_th('project',$order,'Project');5144 print_sort_th('descr',$order,'Description');5145 print_sort_th('owner',$order,'Owner');5146 print_sort_th('age',$order,'Last Change');5147print"<th></th>\n".# for links5148"</tr>\n";5149}51505151if($projects_list_group_categories) {5152# only display categories with projects in the $from-$to window5153@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5154my%categories= build_projlist_by_category(\@projects,$from,$to);5155foreachmy$cat(sort keys%categories) {5156unless($cateq"") {5157print"<tr>\n";5158if($check_forks) {5159print"<td></td>\n";5160}5161print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5162print"</tr>\n";5163}51645165 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5166}5167}else{5168 git_project_list_rows(\@projects,$from,$to,$check_forks);5169}51705171if(defined$extra) {5172print"<tr>\n";5173if($check_forks) {5174print"<td></td>\n";5175}5176print"<td colspan=\"5\">$extra</td>\n".5177"</tr>\n";5178}5179print"</table>\n";5180}51815182sub git_log_body {5183# uses global variable $project5184my($commitlist,$from,$to,$refs,$extra) =@_;51855186$from=0unlessdefined$from;5187$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);51885189for(my$i=0;$i<=$to;$i++) {5190my%co= %{$commitlist->[$i]};5191next if!%co;5192my$commit=$co{'id'};5193my$ref= format_ref_marker($refs,$commit);5194 git_print_header_div('commit',5195"<span class=\"age\">$co{'age_string'}</span>".5196 esc_html($co{'title'}) .$ref,5197$commit);5198print"<div class=\"title_text\">\n".5199"<div class=\"log_link\">\n".5200$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5201" | ".5202$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5203" | ".5204$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5205"<br/>\n".5206"</div>\n";5207 git_print_authorship(\%co, -tag =>'span');5208print"<br/>\n</div>\n";52095210print"<div class=\"log_body\">\n";5211 git_print_log($co{'comment'}, -final_empty_line=>1);5212print"</div>\n";5213}5214if($extra) {5215print"<div class=\"page_nav\">\n";5216print"$extra\n";5217print"</div>\n";5218}5219}52205221sub git_shortlog_body {5222# uses global variable $project5223my($commitlist,$from,$to,$refs,$extra) =@_;52245225$from=0unlessdefined$from;5226$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);52275228print"<table class=\"shortlog\">\n";5229my$alternate=1;5230for(my$i=$from;$i<=$to;$i++) {5231my%co= %{$commitlist->[$i]};5232my$commit=$co{'id'};5233my$ref= format_ref_marker($refs,$commit);5234if($alternate) {5235print"<tr class=\"dark\">\n";5236}else{5237print"<tr class=\"light\">\n";5238}5239$alternate^=1;5240# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5241print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5242 format_author_html('td', \%co,10) ."<td>";5243print format_subject_html($co{'title'},$co{'title_short'},5244 href(action=>"commit", hash=>$commit),$ref);5245print"</td>\n".5246"<td class=\"link\">".5247$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5248$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5249$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5250my$snapshot_links= format_snapshot_links($commit);5251if(defined$snapshot_links) {5252print" | ".$snapshot_links;5253}5254print"</td>\n".5255"</tr>\n";5256}5257if(defined$extra) {5258print"<tr>\n".5259"<td colspan=\"4\">$extra</td>\n".5260"</tr>\n";5261}5262print"</table>\n";5263}52645265sub git_history_body {5266# Warning: assumes constant type (blob or tree) during history5267my($commitlist,$from,$to,$refs,$extra,5268$file_name,$file_hash,$ftype) =@_;52695270$from=0unlessdefined$from;5271$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});52725273print"<table class=\"history\">\n";5274my$alternate=1;5275for(my$i=$from;$i<=$to;$i++) {5276my%co= %{$commitlist->[$i]};5277if(!%co) {5278next;5279}5280my$commit=$co{'id'};52815282my$ref= format_ref_marker($refs,$commit);52835284if($alternate) {5285print"<tr class=\"dark\">\n";5286}else{5287print"<tr class=\"light\">\n";5288}5289$alternate^=1;5290print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5291# shortlog: format_author_html('td', \%co, 10)5292 format_author_html('td', \%co,15,3) ."<td>";5293# originally git_history used chop_str($co{'title'}, 50)5294print format_subject_html($co{'title'},$co{'title_short'},5295 href(action=>"commit", hash=>$commit),$ref);5296print"</td>\n".5297"<td class=\"link\">".5298$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5299$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");53005301if($ftypeeq'blob') {5302my$blob_current=$file_hash;5303my$blob_parent= git_get_hash_by_path($commit,$file_name);5304if(defined$blob_current&&defined$blob_parent&&5305$blob_currentne$blob_parent) {5306print" | ".5307$cgi->a({-href => href(action=>"blobdiff",5308 hash=>$blob_current, hash_parent=>$blob_parent,5309 hash_base=>$hash_base, hash_parent_base=>$commit,5310 file_name=>$file_name)},5311"diff to current");5312}5313}5314print"</td>\n".5315"</tr>\n";5316}5317if(defined$extra) {5318print"<tr>\n".5319"<td colspan=\"4\">$extra</td>\n".5320"</tr>\n";5321}5322print"</table>\n";5323}53245325sub git_tags_body {5326# uses global variable $project5327my($taglist,$from,$to,$extra) =@_;5328$from=0unlessdefined$from;5329$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);53305331print"<table class=\"tags\">\n";5332my$alternate=1;5333for(my$i=$from;$i<=$to;$i++) {5334my$entry=$taglist->[$i];5335my%tag=%$entry;5336my$comment=$tag{'subject'};5337my$comment_short;5338if(defined$comment) {5339$comment_short= chop_str($comment,30,5);5340}5341if($alternate) {5342print"<tr class=\"dark\">\n";5343}else{5344print"<tr class=\"light\">\n";5345}5346$alternate^=1;5347if(defined$tag{'age'}) {5348print"<td><i>$tag{'age'}</i></td>\n";5349}else{5350print"<td></td>\n";5351}5352print"<td>".5353$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5354-class=>"list name"}, esc_html($tag{'name'})) .5355"</td>\n".5356"<td>";5357if(defined$comment) {5358print format_subject_html($comment,$comment_short,5359 href(action=>"tag", hash=>$tag{'id'}));5360}5361print"</td>\n".5362"<td class=\"selflink\">";5363if($tag{'type'}eq"tag") {5364print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");5365}else{5366print" ";5367}5368print"</td>\n".5369"<td class=\"link\">"." | ".5370$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});5371if($tag{'reftype'}eq"commit") {5372print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .5373" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");5374}elsif($tag{'reftype'}eq"blob") {5375print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");5376}5377print"</td>\n".5378"</tr>";5379}5380if(defined$extra) {5381print"<tr>\n".5382"<td colspan=\"5\">$extra</td>\n".5383"</tr>\n";5384}5385print"</table>\n";5386}53875388sub git_heads_body {5389# uses global variable $project5390my($headlist,$head,$from,$to,$extra) =@_;5391$from=0unlessdefined$from;5392$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);53935394print"<table class=\"heads\">\n";5395my$alternate=1;5396for(my$i=$from;$i<=$to;$i++) {5397my$entry=$headlist->[$i];5398my%ref=%$entry;5399my$curr=$ref{'id'}eq$head;5400if($alternate) {5401print"<tr class=\"dark\">\n";5402}else{5403print"<tr class=\"light\">\n";5404}5405$alternate^=1;5406print"<td><i>$ref{'age'}</i></td>\n".5407($curr?"<td class=\"current_head\">":"<td>") .5408$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),5409-class=>"list name"},esc_html($ref{'name'})) .5410"</td>\n".5411"<td class=\"link\">".5412$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".5413$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".5414$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .5415"</td>\n".5416"</tr>";5417}5418if(defined$extra) {5419print"<tr>\n".5420"<td colspan=\"3\">$extra</td>\n".5421"</tr>\n";5422}5423print"</table>\n";5424}54255426# Display a single remote block5427sub git_remote_block {5428my($remote,$rdata,$limit,$head) =@_;54295430my$heads=$rdata->{'heads'};5431my$fetch=$rdata->{'fetch'};5432my$push=$rdata->{'push'};54335434my$urls_table="<table class=\"projects_list\">\n";54355436if(defined$fetch) {5437if($fetcheq$push) {5438$urls_table.= format_repo_url("URL",$fetch);5439}else{5440$urls_table.= format_repo_url("Fetch URL",$fetch);5441$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;5442}5443}elsif(defined$push) {5444$urls_table.= format_repo_url("Push URL",$push);5445}else{5446$urls_table.= format_repo_url("","No remote URL");5447}54485449$urls_table.="</table>\n";54505451my$dots;5452if(defined$limit&&$limit<@$heads) {5453$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");5454}54555456print$urls_table;5457 git_heads_body($heads,$head,0,$limit,$dots);5458}54595460# Display a list of remote names with the respective fetch and push URLs5461sub git_remotes_list {5462my($remotedata,$limit) =@_;5463print"<table class=\"heads\">\n";5464my$alternate=1;5465my@remotes=sort keys%$remotedata;54665467my$limited=$limit&&$limit<@remotes;54685469$#remotes=$limit-1if$limited;54705471while(my$remote=shift@remotes) {5472my$rdata=$remotedata->{$remote};5473my$fetch=$rdata->{'fetch'};5474my$push=$rdata->{'push'};5475if($alternate) {5476print"<tr class=\"dark\">\n";5477}else{5478print"<tr class=\"light\">\n";5479}5480$alternate^=1;5481print"<td>".5482$cgi->a({-href=> href(action=>'remotes', hash=>$remote),5483-class=>"list name"},esc_html($remote)) .5484"</td>";5485print"<td class=\"link\">".5486(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .5487" | ".5488(defined$push?$cgi->a({-href=>$push},"push") :"push") .5489"</td>";54905491print"</tr>\n";5492}54935494if($limited) {5495print"<tr>\n".5496"<td colspan=\"3\">".5497$cgi->a({-href => href(action=>"remotes")},"...") .5498"</td>\n"."</tr>\n";5499}55005501print"</table>";5502}55035504# Display remote heads grouped by remote, unless there are too many5505# remotes, in which case we only display the remote names5506sub git_remotes_body {5507my($remotedata,$limit,$head) =@_;5508if($limitand$limit<keys%$remotedata) {5509 git_remotes_list($remotedata,$limit);5510}else{5511 fill_remote_heads($remotedata);5512while(my($remote,$rdata) =each%$remotedata) {5513 git_print_section({-class=>"remote", -id=>$remote},5514["remotes",$remote,$remote],sub{5515 git_remote_block($remote,$rdata,$limit,$head);5516});5517}5518}5519}55205521sub git_search_grep_body {5522my($commitlist,$from,$to,$extra) =@_;5523$from=0unlessdefined$from;5524$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);55255526print"<table class=\"commit_search\">\n";5527my$alternate=1;5528for(my$i=$from;$i<=$to;$i++) {5529my%co= %{$commitlist->[$i]};5530if(!%co) {5531next;5532}5533my$commit=$co{'id'};5534if($alternate) {5535print"<tr class=\"dark\">\n";5536}else{5537print"<tr class=\"light\">\n";5538}5539$alternate^=1;5540print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5541 format_author_html('td', \%co,15,5) .5542"<td>".5543$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5544-class=>"list subject"},5545 chop_and_escape_str($co{'title'},50) ."<br/>");5546my$comment=$co{'comment'};5547foreachmy$line(@$comment) {5548if($line=~m/^(.*?)($search_regexp)(.*)$/i) {5549my($lead,$match,$trail) = ($1,$2,$3);5550$match= chop_str($match,70,5,'center');5551my$contextlen=int((80-length($match))/2);5552$contextlen=30if($contextlen>30);5553$lead= chop_str($lead,$contextlen,10,'left');5554$trail= chop_str($trail,$contextlen,10,'right');55555556$lead= esc_html($lead);5557$match= esc_html($match);5558$trail= esc_html($trail);55595560print"$lead<span class=\"match\">$match</span>$trail<br />";5561}5562}5563print"</td>\n".5564"<td class=\"link\">".5565$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .5566" | ".5567$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .5568" | ".5569$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");5570print"</td>\n".5571"</tr>\n";5572}5573if(defined$extra) {5574print"<tr>\n".5575"<td colspan=\"3\">$extra</td>\n".5576"</tr>\n";5577}5578print"</table>\n";5579}55805581## ======================================================================5582## ======================================================================5583## actions55845585sub git_project_list {5586my$order=$input_params{'order'};5587if(defined$order&&$order!~m/none|project|descr|owner|age/) {5588 die_error(400,"Unknown order parameter");5589}55905591my@list= git_get_projects_list();5592if(!@list) {5593 die_error(404,"No projects found");5594}55955596 git_header_html();5597if(defined$home_text&& -f $home_text) {5598print"<div class=\"index_include\">\n";5599 insert_file($home_text);5600print"</div>\n";5601}5602print$cgi->startform(-method=>"get") .5603"<p class=\"projsearch\">Search:\n".5604$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".5605"</p>".5606$cgi->end_form() ."\n";5607 git_project_list_body(\@list,$order);5608 git_footer_html();5609}56105611sub git_forks {5612my$order=$input_params{'order'};5613if(defined$order&&$order!~m/none|project|descr|owner|age/) {5614 die_error(400,"Unknown order parameter");5615}56165617my@list= git_get_projects_list($project);5618if(!@list) {5619 die_error(404,"No forks found");5620}56215622 git_header_html();5623 git_print_page_nav('','');5624 git_print_header_div('summary',"$projectforks");5625 git_project_list_body(\@list,$order);5626 git_footer_html();5627}56285629sub git_project_index {5630my@projects= git_get_projects_list();5631if(!@projects) {5632 die_error(404,"No projects found");5633}56345635print$cgi->header(5636-type =>'text/plain',5637-charset =>'utf-8',5638-content_disposition =>'inline; filename="index.aux"');56395640foreachmy$pr(@projects) {5641if(!exists$pr->{'owner'}) {5642$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");5643}56445645my($path,$owner) = ($pr->{'path'},$pr->{'owner'});5646# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '5647$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5648$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5649$path=~s/ /\+/g;5650$owner=~s/ /\+/g;56515652print"$path$owner\n";5653}5654}56555656sub git_summary {5657my$descr= git_get_project_description($project) ||"none";5658my%co= parse_commit("HEAD");5659my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();5660my$head=$co{'id'};5661my$remote_heads= gitweb_check_feature('remote_heads');56625663my$owner= git_get_project_owner($project);56645665my$refs= git_get_references();5666# These get_*_list functions return one more to allow us to see if5667# there are more ...5668my@taglist= git_get_tags_list(16);5669my@headlist= git_get_heads_list(16);5670my%remotedata=$remote_heads? git_get_remotes_list() : ();5671my@forklist;5672my$check_forks= gitweb_check_feature('forks');56735674if($check_forks) {5675# find forks of a project5676@forklist= git_get_projects_list($project);5677# filter out forks of forks5678@forklist= filter_forks_from_projects_list(\@forklist)5679if(@forklist);5680}56815682 git_header_html();5683 git_print_page_nav('summary','',$head);56845685print"<div class=\"title\"> </div>\n";5686print"<table class=\"projects_list\">\n".5687"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".5688"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";5689if(defined$cd{'rfc2822'}) {5690print"<tr id=\"metadata_lchange\"><td>last change</td>".5691"<td>".format_timestamp_html(\%cd)."</td></tr>\n";5692}56935694# use per project git URL list in $projectroot/$project/cloneurl5695# or make project git URL from git base URL and project name5696my$url_tag="URL";5697my@url_list= git_get_project_url_list($project);5698@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;5699foreachmy$git_url(@url_list) {5700next unless$git_url;5701print format_repo_url($url_tag,$git_url);5702$url_tag="";5703}57045705# Tag cloud5706my$show_ctags= gitweb_check_feature('ctags');5707if($show_ctags) {5708my$ctags= git_get_project_ctags($project);5709if(%$ctags) {5710# without ability to add tags, don't show if there are none5711my$cloud= git_populate_project_tagcloud($ctags);5712print"<tr id=\"metadata_ctags\">".5713"<td>content tags</td>".5714"<td>".git_show_project_tagcloud($cloud,48)."</td>".5715"</tr>\n";5716}5717}57185719print"</table>\n";57205721# If XSS prevention is on, we don't include README.html.5722# TODO: Allow a readme in some safe format.5723if(!$prevent_xss&& -s "$projectroot/$project/README.html") {5724print"<div class=\"title\">readme</div>\n".5725"<div class=\"readme\">\n";5726 insert_file("$projectroot/$project/README.html");5727print"\n</div>\n";# class="readme"5728}57295730# we need to request one more than 16 (0..15) to check if5731# those 16 are all5732my@commitlist=$head? parse_commits($head,17) : ();5733if(@commitlist) {5734 git_print_header_div('shortlog');5735 git_shortlog_body(\@commitlist,0,15,$refs,5736$#commitlist<=15?undef:5737$cgi->a({-href => href(action=>"shortlog")},"..."));5738}57395740if(@taglist) {5741 git_print_header_div('tags');5742 git_tags_body(\@taglist,0,15,5743$#taglist<=15?undef:5744$cgi->a({-href => href(action=>"tags")},"..."));5745}57465747if(@headlist) {5748 git_print_header_div('heads');5749 git_heads_body(\@headlist,$head,0,15,5750$#headlist<=15?undef:5751$cgi->a({-href => href(action=>"heads")},"..."));5752}57535754if(%remotedata) {5755 git_print_header_div('remotes');5756 git_remotes_body(\%remotedata,15,$head);5757}57585759if(@forklist) {5760 git_print_header_div('forks');5761 git_project_list_body(\@forklist,'age',0,15,5762$#forklist<=15?undef:5763$cgi->a({-href => href(action=>"forks")},"..."),5764'no_header');5765}57665767 git_footer_html();5768}57695770sub git_tag {5771my%tag= parse_tag($hash);57725773if(!%tag) {5774 die_error(404,"Unknown tag object");5775}57765777my$head= git_get_head_hash($project);5778 git_header_html();5779 git_print_page_nav('','',$head,undef,$head);5780 git_print_header_div('commit', esc_html($tag{'name'}),$hash);5781print"<div class=\"title_text\">\n".5782"<table class=\"object_header\">\n".5783"<tr>\n".5784"<td>object</td>\n".5785"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5786$tag{'object'}) ."</td>\n".5787"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5788$tag{'type'}) ."</td>\n".5789"</tr>\n";5790if(defined($tag{'author'})) {5791 git_print_authorship_rows(\%tag,'author');5792}5793print"</table>\n\n".5794"</div>\n";5795print"<div class=\"page_body\">";5796my$comment=$tag{'comment'};5797foreachmy$line(@$comment) {5798chomp$line;5799print esc_html($line, -nbsp=>1) ."<br/>\n";5800}5801print"</div>\n";5802 git_footer_html();5803}58045805sub git_blame_common {5806my$format=shift||'porcelain';5807if($formateq'porcelain'&&$cgi->param('js')) {5808$format='incremental';5809$action='blame_incremental';# for page title etc5810}58115812# permissions5813 gitweb_check_feature('blame')5814or die_error(403,"Blame view not allowed");58155816# error checking5817 die_error(400,"No file name given")unless$file_name;5818$hash_base||= git_get_head_hash($project);5819 die_error(404,"Couldn't find base commit")unless$hash_base;5820my%co= parse_commit($hash_base)5821or die_error(404,"Commit not found");5822my$ftype="blob";5823if(!defined$hash) {5824$hash= git_get_hash_by_path($hash_base,$file_name,"blob")5825or die_error(404,"Error looking up file");5826}else{5827$ftype= git_get_type($hash);5828if($ftype!~"blob") {5829 die_error(400,"Object is not a blob");5830}5831}58325833my$fd;5834if($formateq'incremental') {5835# get file contents (as base)5836open$fd,"-|", git_cmd(),'cat-file','blob',$hash5837or die_error(500,"Open git-cat-file failed");5838}elsif($formateq'data') {5839# run git-blame --incremental5840open$fd,"-|", git_cmd(),"blame","--incremental",5841$hash_base,"--",$file_name5842or die_error(500,"Open git-blame --incremental failed");5843}else{5844# run git-blame --porcelain5845open$fd,"-|", git_cmd(),"blame",'-p',5846$hash_base,'--',$file_name5847or die_error(500,"Open git-blame --porcelain failed");5848}58495850# incremental blame data returns early5851if($formateq'data') {5852print$cgi->header(5853-type=>"text/plain", -charset =>"utf-8",5854-status=>"200 OK");5855local$| =1;# output autoflush5856printwhile<$fd>;5857close$fd5858or print"ERROR$!\n";58595860print'END';5861if(defined$t0&& gitweb_check_feature('timed')) {5862print' '.5863 tv_interval($t0, [ gettimeofday() ]).5864' '.$number_of_git_cmds;5865}5866print"\n";58675868return;5869}58705871# page header5872 git_header_html();5873my$formats_nav=5874$cgi->a({-href => href(action=>"blob", -replay=>1)},5875"blob") .5876" | ";5877if($formateq'incremental') {5878$formats_nav.=5879$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},5880"blame") ." (non-incremental)";5881}else{5882$formats_nav.=5883$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},5884"blame") ." (incremental)";5885}5886$formats_nav.=5887" | ".5888$cgi->a({-href => href(action=>"history", -replay=>1)},5889"history") .5890" | ".5891$cgi->a({-href => href(action=>$action, file_name=>$file_name)},5892"HEAD");5893 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5894 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5895 git_print_page_path($file_name,$ftype,$hash_base);58965897# page body5898if($formateq'incremental') {5899print"<noscript>\n<div class=\"error\"><center><b>\n".5900"This page requires JavaScript to run.\nUse ".5901$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},5902'this page').5903" instead.\n".5904"</b></center></div>\n</noscript>\n";59055906print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;5907}59085909print qq!<div class="page_body">\n!;5910print qq!<div id="progress_info">.../ ...</div>\n!5911if($formateq'incremental');5912print qq!<table id="blame_table"class="blame" width="100%">\n!.5913#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.5914 qq!<thead>\n!.5915 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.5916 qq!</thead>\n!.5917 qq!<tbody>\n!;59185919my@rev_color=qw(light dark);5920my$num_colors=scalar(@rev_color);5921my$current_color=0;59225923if($formateq'incremental') {5924my$color_class=$rev_color[$current_color];59255926#contents of a file5927my$linenr=0;5928 LINE:5929while(my$line= <$fd>) {5930chomp$line;5931$linenr++;59325933print qq!<tr id="l$linenr"class="$color_class">!.5934 qq!<td class="sha1"><a href=""> </a></td>!.5935 qq!<td class="linenr">!.5936 qq!<a class="linenr" href="">$linenr</a></td>!;5937print qq!<td class="pre">! . esc_html($line) ."</td>\n";5938print qq!</tr>\n!;5939}59405941}else{# porcelain, i.e. ordinary blame5942my%metainfo= ();# saves information about commits59435944# blame data5945 LINE:5946while(my$line= <$fd>) {5947chomp$line;5948# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]5949# no <lines in group> for subsequent lines in group of lines5950my($full_rev,$orig_lineno,$lineno,$group_size) =5951($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);5952if(!exists$metainfo{$full_rev}) {5953$metainfo{$full_rev} = {'nprevious'=>0};5954}5955my$meta=$metainfo{$full_rev};5956my$data;5957while($data= <$fd>) {5958chomp$data;5959last if($data=~s/^\t//);# contents of line5960if($data=~/^(\S+)(?: (.*))?$/) {5961$meta->{$1} =$2unlessexists$meta->{$1};5962}5963if($data=~/^previous /) {5964$meta->{'nprevious'}++;5965}5966}5967my$short_rev=substr($full_rev,0,8);5968my$author=$meta->{'author'};5969my%date=5970 parse_date($meta->{'author-time'},$meta->{'author-tz'});5971my$date=$date{'iso-tz'};5972if($group_size) {5973$current_color= ($current_color+1) %$num_colors;5974}5975my$tr_class=$rev_color[$current_color];5976$tr_class.=' boundary'if(exists$meta->{'boundary'});5977$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);5978$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);5979print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";5980if($group_size) {5981print"<td class=\"sha1\"";5982print" title=\"". esc_html($author) .",$date\"";5983print" rowspan=\"$group_size\""if($group_size>1);5984print">";5985print$cgi->a({-href => href(action=>"commit",5986 hash=>$full_rev,5987 file_name=>$file_name)},5988 esc_html($short_rev));5989if($group_size>=2) {5990my@author_initials= ($author=~/\b([[:upper:]])\B/g);5991if(@author_initials) {5992print"<br />".5993 esc_html(join('',@author_initials));5994# or join('.', ...)5995}5996}5997print"</td>\n";5998}5999# 'previous' <sha1 of parent commit> <filename at commit>6000if(exists$meta->{'previous'} &&6001$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {6002$meta->{'parent'} =$1;6003$meta->{'file_parent'} = unquote($2);6004}6005my$linenr_commit=6006exists($meta->{'parent'}) ?6007$meta->{'parent'} :$full_rev;6008my$linenr_filename=6009exists($meta->{'file_parent'}) ?6010$meta->{'file_parent'} : unquote($meta->{'filename'});6011my$blamed= href(action =>'blame',6012 file_name =>$linenr_filename,6013 hash_base =>$linenr_commit);6014print"<td class=\"linenr\">";6015print$cgi->a({ -href =>"$blamed#l$orig_lineno",6016-class=>"linenr"},6017 esc_html($lineno));6018print"</td>";6019print"<td class=\"pre\">". esc_html($data) ."</td>\n";6020print"</tr>\n";6021}# end while60226023}60246025# footer6026print"</tbody>\n".6027"</table>\n";# class="blame"6028print"</div>\n";# class="blame_body"6029close$fd6030or print"Reading blob failed\n";60316032 git_footer_html();6033}60346035sub git_blame {6036 git_blame_common();6037}60386039sub git_blame_incremental {6040 git_blame_common('incremental');6041}60426043sub git_blame_data {6044 git_blame_common('data');6045}60466047sub git_tags {6048my$head= git_get_head_hash($project);6049 git_header_html();6050 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6051 git_print_header_div('summary',$project);60526053my@tagslist= git_get_tags_list();6054if(@tagslist) {6055 git_tags_body(\@tagslist);6056}6057 git_footer_html();6058}60596060sub git_heads {6061my$head= git_get_head_hash($project);6062 git_header_html();6063 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6064 git_print_header_div('summary',$project);60656066my@headslist= git_get_heads_list();6067if(@headslist) {6068 git_heads_body(\@headslist,$head);6069}6070 git_footer_html();6071}60726073# used both for single remote view and for list of all the remotes6074sub git_remotes {6075 gitweb_check_feature('remote_heads')6076or die_error(403,"Remote heads view is disabled");60776078my$head= git_get_head_hash($project);6079my$remote=$input_params{'hash'};60806081my$remotedata= git_get_remotes_list($remote);6082 die_error(500,"Unable to get remote information")unlessdefined$remotedata;60836084unless(%$remotedata) {6085 die_error(404,defined$remote?6086"Remote$remotenot found":6087"No remotes found");6088}60896090 git_header_html(undef,undef, -action_extra =>$remote);6091 git_print_page_nav('','',$head,undef,$head,6092 format_ref_views($remote?'':'remotes'));60936094 fill_remote_heads($remotedata);6095if(defined$remote) {6096 git_print_header_div('remotes',"$remoteremote for$project");6097 git_remote_block($remote,$remotedata->{$remote},undef,$head);6098}else{6099 git_print_header_div('summary',"$projectremotes");6100 git_remotes_body($remotedata,undef,$head);6101}61026103 git_footer_html();6104}61056106sub git_blob_plain {6107my$type=shift;6108my$expires;61096110if(!defined$hash) {6111if(defined$file_name) {6112my$base=$hash_base|| git_get_head_hash($project);6113$hash= git_get_hash_by_path($base,$file_name,"blob")6114or die_error(404,"Cannot find file");6115}else{6116 die_error(400,"No file name defined");6117}6118}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6119# blobs defined by non-textual hash id's can be cached6120$expires="+1d";6121}61226123open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6124or die_error(500,"Open git-cat-file blob '$hash' failed");61256126# content-type (can include charset)6127$type= blob_contenttype($fd,$file_name,$type);61286129# "save as" filename, even when no $file_name is given6130my$save_as="$hash";6131if(defined$file_name) {6132$save_as=$file_name;6133}elsif($type=~m/^text\//) {6134$save_as.='.txt';6135}61366137# With XSS prevention on, blobs of all types except a few known safe6138# ones are served with "Content-Disposition: attachment" to make sure6139# they don't run in our security domain. For certain image types,6140# blob view writes an <img> tag referring to blob_plain view, and we6141# want to be sure not to break that by serving the image as an6142# attachment (though Firefox 3 doesn't seem to care).6143my$sandbox=$prevent_xss&&6144$type!~m!^(?:text/plain|image/(?:gif|png|jpeg))(?:[ ;]|$)!;61456146print$cgi->header(6147-type =>$type,6148-expires =>$expires,6149-content_disposition =>6150($sandbox?'attachment':'inline')6151.'; filename="'.$save_as.'"');6152local$/=undef;6153binmode STDOUT,':raw';6154print<$fd>;6155binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6156close$fd;6157}61586159sub git_blob {6160my$expires;61616162if(!defined$hash) {6163if(defined$file_name) {6164my$base=$hash_base|| git_get_head_hash($project);6165$hash= git_get_hash_by_path($base,$file_name,"blob")6166or die_error(404,"Cannot find file");6167}else{6168 die_error(400,"No file name defined");6169}6170}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6171# blobs defined by non-textual hash id's can be cached6172$expires="+1d";6173}61746175my$have_blame= gitweb_check_feature('blame');6176open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6177or die_error(500,"Couldn't cat$file_name,$hash");6178my$mimetype= blob_mimetype($fd,$file_name);6179# use 'blob_plain' (aka 'raw') view for files that cannot be displayed6180if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {6181close$fd;6182return git_blob_plain($mimetype);6183}6184# we can have blame only for text/* mimetype6185$have_blame&&= ($mimetype=~m!^text/!);61866187my$highlight= gitweb_check_feature('highlight');6188my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);6189$fd= run_highlighter($fd,$highlight,$syntax)6190if$syntax;61916192 git_header_html(undef,$expires);6193my$formats_nav='';6194if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6195if(defined$file_name) {6196if($have_blame) {6197$formats_nav.=6198$cgi->a({-href => href(action=>"blame", -replay=>1)},6199"blame") .6200" | ";6201}6202$formats_nav.=6203$cgi->a({-href => href(action=>"history", -replay=>1)},6204"history") .6205" | ".6206$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6207"raw") .6208" | ".6209$cgi->a({-href => href(action=>"blob",6210 hash_base=>"HEAD", file_name=>$file_name)},6211"HEAD");6212}else{6213$formats_nav.=6214$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6215"raw");6216}6217 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6218 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6219}else{6220print"<div class=\"page_nav\">\n".6221"<br/><br/></div>\n".6222"<div class=\"title\">".esc_html($hash)."</div>\n";6223}6224 git_print_page_path($file_name,"blob",$hash_base);6225print"<div class=\"page_body\">\n";6226if($mimetype=~m!^image/!) {6227print qq!<img type="!.esc_attr($mimetype).qq!"!;6228if($file_name) {6229print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;6230}6231print qq! src="! .6232 href(action=>"blob_plain", hash=>$hash,6233 hash_base=>$hash_base, file_name=>$file_name) .6234 qq!"/>\n!;6235}else{6236my$nr;6237while(my$line= <$fd>) {6238chomp$line;6239$nr++;6240$line= untabify($line);6241printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,6242$nr, esc_attr(href(-replay =>1)),$nr,$nr,$syntax?$line: esc_html($line, -nbsp=>1);6243}6244}6245close$fd6246or print"Reading blob failed.\n";6247print"</div>";6248 git_footer_html();6249}62506251sub git_tree {6252if(!defined$hash_base) {6253$hash_base="HEAD";6254}6255if(!defined$hash) {6256if(defined$file_name) {6257$hash= git_get_hash_by_path($hash_base,$file_name,"tree");6258}else{6259$hash=$hash_base;6260}6261}6262 die_error(404,"No such tree")unlessdefined($hash);62636264my$show_sizes= gitweb_check_feature('show-sizes');6265my$have_blame= gitweb_check_feature('blame');62666267my@entries= ();6268{6269local$/="\0";6270open my$fd,"-|", git_cmd(),"ls-tree",'-z',6271($show_sizes?'-l': ()),@extra_options,$hash6272or die_error(500,"Open git-ls-tree failed");6273@entries=map{chomp;$_} <$fd>;6274close$fd6275or die_error(404,"Reading tree failed");6276}62776278my$refs= git_get_references();6279my$ref= format_ref_marker($refs,$hash_base);6280 git_header_html();6281my$basedir='';6282if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6283my@views_nav= ();6284if(defined$file_name) {6285push@views_nav,6286$cgi->a({-href => href(action=>"history", -replay=>1)},6287"history"),6288$cgi->a({-href => href(action=>"tree",6289 hash_base=>"HEAD", file_name=>$file_name)},6290"HEAD"),6291}6292my$snapshot_links= format_snapshot_links($hash);6293if(defined$snapshot_links) {6294# FIXME: Should be available when we have no hash base as well.6295push@views_nav,$snapshot_links;6296}6297 git_print_page_nav('tree','',$hash_base,undef,undef,6298join(' | ',@views_nav));6299 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);6300}else{6301undef$hash_base;6302print"<div class=\"page_nav\">\n";6303print"<br/><br/></div>\n";6304print"<div class=\"title\">".esc_html($hash)."</div>\n";6305}6306if(defined$file_name) {6307$basedir=$file_name;6308if($basedirne''&&substr($basedir, -1)ne'/') {6309$basedir.='/';6310}6311 git_print_page_path($file_name,'tree',$hash_base);6312}6313print"<div class=\"page_body\">\n";6314print"<table class=\"tree\">\n";6315my$alternate=1;6316# '..' (top directory) link if possible6317if(defined$hash_base&&6318defined$file_name&&$file_name=~m![^/]+$!) {6319if($alternate) {6320print"<tr class=\"dark\">\n";6321}else{6322print"<tr class=\"light\">\n";6323}6324$alternate^=1;63256326my$up=$file_name;6327$up=~s!/?[^/]+$!!;6328undef$upunless$up;6329# based on git_print_tree_entry6330print'<td class="mode">'. mode_str('040000') ."</td>\n";6331print'<td class="size"> </td>'."\n"if$show_sizes;6332print'<td class="list">';6333print$cgi->a({-href => href(action=>"tree",6334 hash_base=>$hash_base,6335 file_name=>$up)},6336"..");6337print"</td>\n";6338print"<td class=\"link\"></td>\n";63396340print"</tr>\n";6341}6342foreachmy$line(@entries) {6343my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);63446345if($alternate) {6346print"<tr class=\"dark\">\n";6347}else{6348print"<tr class=\"light\">\n";6349}6350$alternate^=1;63516352 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);63536354print"</tr>\n";6355}6356print"</table>\n".6357"</div>";6358 git_footer_html();6359}63606361sub snapshot_name {6362my($project,$hash) =@_;63636364# path/to/project.git -> project6365# path/to/project/.git -> project6366my$name= to_utf8($project);6367$name=~ s,([^/])/*\.git$,$1,;6368$name= basename($name);6369# sanitize name6370$name=~s/[[:cntrl:]]/?/g;63716372my$ver=$hash;6373if($hash=~/^[0-9a-fA-F]+$/) {6374# shorten SHA-1 hash6375my$full_hash= git_get_full_hash($project,$hash);6376if($full_hash=~/^$hash/&&length($hash) >7) {6377$ver= git_get_short_hash($project,$hash);6378}6379}elsif($hash=~m!^refs/tags/(.*)$!) {6380# tags don't need shortened SHA-1 hash6381$ver=$1;6382}else{6383# branches and other need shortened SHA-1 hash6384if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {6385$ver=$1;6386}6387$ver.='-'. git_get_short_hash($project,$hash);6388}6389# in case of hierarchical branch names6390$ver=~s!/!.!g;63916392# name = project-version_string6393$name="$name-$ver";63946395returnwantarray? ($name,$name) :$name;6396}63976398sub git_snapshot {6399my$format=$input_params{'snapshot_format'};6400if(!@snapshot_fmts) {6401 die_error(403,"Snapshots not allowed");6402}6403# default to first supported snapshot format6404$format||=$snapshot_fmts[0];6405if($format!~m/^[a-z0-9]+$/) {6406 die_error(400,"Invalid snapshot format parameter");6407}elsif(!exists($known_snapshot_formats{$format})) {6408 die_error(400,"Unknown snapshot format");6409}elsif($known_snapshot_formats{$format}{'disabled'}) {6410 die_error(403,"Snapshot format not allowed");6411}elsif(!grep($_eq$format,@snapshot_fmts)) {6412 die_error(403,"Unsupported snapshot format");6413}64146415my$type= git_get_type("$hash^{}");6416if(!$type) {6417 die_error(404,'Object does not exist');6418}elsif($typeeq'blob') {6419 die_error(400,'Object is not a tree-ish');6420}64216422my($name,$prefix) = snapshot_name($project,$hash);6423my$filename="$name$known_snapshot_formats{$format}{'suffix'}";6424my$cmd= quote_command(6425 git_cmd(),'archive',6426"--format=$known_snapshot_formats{$format}{'format'}",6427"--prefix=$prefix/",$hash);6428if(exists$known_snapshot_formats{$format}{'compressor'}) {6429$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});6430}64316432$filename=~s/(["\\])/\\$1/g;6433print$cgi->header(6434-type =>$known_snapshot_formats{$format}{'type'},6435-content_disposition =>'inline; filename="'.$filename.'"',6436-status =>'200 OK');64376438open my$fd,"-|",$cmd6439or die_error(500,"Execute git-archive failed");6440binmode STDOUT,':raw';6441print<$fd>;6442binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6443close$fd;6444}64456446sub git_log_generic {6447my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;64486449my$head= git_get_head_hash($project);6450if(!defined$base) {6451$base=$head;6452}6453if(!defined$page) {6454$page=0;6455}6456my$refs= git_get_references();64576458my$commit_hash=$base;6459if(defined$parent) {6460$commit_hash="$parent..$base";6461}6462my@commitlist=6463 parse_commits($commit_hash,101, (100*$page),6464defined$file_name? ($file_name,"--full-history") : ());64656466my$ftype;6467if(!defined$file_hash&&defined$file_name) {6468# some commits could have deleted file in question,6469# and not have it in tree, but one of them has to have it6470for(my$i=0;$i<@commitlist;$i++) {6471$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);6472last ifdefined$file_hash;6473}6474}6475if(defined$file_hash) {6476$ftype= git_get_type($file_hash);6477}6478if(defined$file_name&& !defined$ftype) {6479 die_error(500,"Unknown type of object");6480}6481my%co;6482if(defined$file_name) {6483%co= parse_commit($base)6484or die_error(404,"Unknown commit object");6485}648664876488my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);6489my$next_link='';6490if($#commitlist>=100) {6491$next_link=6492$cgi->a({-href => href(-replay=>1, page=>$page+1),6493-accesskey =>"n", -title =>"Alt-n"},"next");6494}6495my$patch_max= gitweb_get_feature('patches');6496if($patch_max&& !defined$file_name) {6497if($patch_max<0||@commitlist<=$patch_max) {6498$paging_nav.=" ⋅ ".6499$cgi->a({-href => href(action=>"patches", -replay=>1)},6500"patches");6501}6502}65036504 git_header_html();6505 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);6506if(defined$file_name) {6507 git_print_header_div('commit', esc_html($co{'title'}),$base);6508}else{6509 git_print_header_div('summary',$project)6510}6511 git_print_page_path($file_name,$ftype,$hash_base)6512if(defined$file_name);65136514$body_subr->(\@commitlist,0,99,$refs,$next_link,6515$file_name,$file_hash,$ftype);65166517 git_footer_html();6518}65196520sub git_log {6521 git_log_generic('log', \&git_log_body,6522$hash,$hash_parent);6523}65246525sub git_commit {6526$hash||=$hash_base||"HEAD";6527my%co= parse_commit($hash)6528or die_error(404,"Unknown commit object");65296530my$parent=$co{'parent'};6531my$parents=$co{'parents'};# listref65326533# we need to prepare $formats_nav before any parameter munging6534my$formats_nav;6535if(!defined$parent) {6536# --root commitdiff6537$formats_nav.='(initial)';6538}elsif(@$parents==1) {6539# single parent commit6540$formats_nav.=6541'(parent: '.6542$cgi->a({-href => href(action=>"commit",6543 hash=>$parent)},6544 esc_html(substr($parent,0,7))) .6545')';6546}else{6547# merge commit6548$formats_nav.=6549'(merge: '.6550join(' ',map{6551$cgi->a({-href => href(action=>"commit",6552 hash=>$_)},6553 esc_html(substr($_,0,7)));6554}@$parents) .6555')';6556}6557if(gitweb_check_feature('patches') &&@$parents<=1) {6558$formats_nav.=" | ".6559$cgi->a({-href => href(action=>"patch", -replay=>1)},6560"patch");6561}65626563if(!defined$parent) {6564$parent="--root";6565}6566my@difftree;6567open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",6568@diff_opts,6569(@$parents<=1?$parent:'-c'),6570$hash,"--"6571or die_error(500,"Open git-diff-tree failed");6572@difftree=map{chomp;$_} <$fd>;6573close$fdor die_error(404,"Reading git-diff-tree failed");65746575# non-textual hash id's can be cached6576my$expires;6577if($hash=~m/^[0-9a-fA-F]{40}$/) {6578$expires="+1d";6579}6580my$refs= git_get_references();6581my$ref= format_ref_marker($refs,$co{'id'});65826583 git_header_html(undef,$expires);6584 git_print_page_nav('commit','',6585$hash,$co{'tree'},$hash,6586$formats_nav);65876588if(defined$co{'parent'}) {6589 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);6590}else{6591 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);6592}6593print"<div class=\"title_text\">\n".6594"<table class=\"object_header\">\n";6595 git_print_authorship_rows(\%co);6596print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";6597print"<tr>".6598"<td>tree</td>".6599"<td class=\"sha1\">".6600$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),6601class=>"list"},$co{'tree'}) .6602"</td>".6603"<td class=\"link\">".6604$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},6605"tree");6606my$snapshot_links= format_snapshot_links($hash);6607if(defined$snapshot_links) {6608print" | ".$snapshot_links;6609}6610print"</td>".6611"</tr>\n";66126613foreachmy$par(@$parents) {6614print"<tr>".6615"<td>parent</td>".6616"<td class=\"sha1\">".6617$cgi->a({-href => href(action=>"commit", hash=>$par),6618class=>"list"},$par) .6619"</td>".6620"<td class=\"link\">".6621$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .6622" | ".6623$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .6624"</td>".6625"</tr>\n";6626}6627print"</table>".6628"</div>\n";66296630print"<div class=\"page_body\">\n";6631 git_print_log($co{'comment'});6632print"</div>\n";66336634 git_difftree_body(\@difftree,$hash,@$parents);66356636 git_footer_html();6637}66386639sub git_object {6640# object is defined by:6641# - hash or hash_base alone6642# - hash_base and file_name6643my$type;66446645# - hash or hash_base alone6646if($hash|| ($hash_base&& !defined$file_name)) {6647my$object_id=$hash||$hash_base;66486649open my$fd,"-|", quote_command(6650 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'6651or die_error(404,"Object does not exist");6652$type= <$fd>;6653chomp$type;6654close$fd6655or die_error(404,"Object does not exist");66566657# - hash_base and file_name6658}elsif($hash_base&&defined$file_name) {6659$file_name=~ s,/+$,,;66606661system(git_cmd(),"cat-file",'-e',$hash_base) ==06662or die_error(404,"Base object does not exist");66636664# here errors should not hapen6665open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name6666or die_error(500,"Open git-ls-tree failed");6667my$line= <$fd>;6668close$fd;66696670#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'6671unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {6672 die_error(404,"File or directory for given base does not exist");6673}6674$type=$2;6675$hash=$3;6676}else{6677 die_error(400,"Not enough information to find object");6678}66796680print$cgi->redirect(-uri => href(action=>$type, -full=>1,6681 hash=>$hash, hash_base=>$hash_base,6682 file_name=>$file_name),6683-status =>'302 Found');6684}66856686sub git_blobdiff {6687my$format=shift||'html';66886689my$fd;6690my@difftree;6691my%diffinfo;6692my$expires;66936694# preparing $fd and %diffinfo for git_patchset_body6695# new style URI6696if(defined$hash_base&&defined$hash_parent_base) {6697if(defined$file_name) {6698# read raw output6699open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6700$hash_parent_base,$hash_base,6701"--", (defined$file_parent?$file_parent: ()),$file_name6702or die_error(500,"Open git-diff-tree failed");6703@difftree=map{chomp;$_} <$fd>;6704close$fd6705or die_error(404,"Reading git-diff-tree failed");6706@difftree6707or die_error(404,"Blob diff not found");67086709}elsif(defined$hash&&6710$hash=~/[0-9a-fA-F]{40}/) {6711# try to find filename from $hash67126713# read filtered raw output6714open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6715$hash_parent_base,$hash_base,"--"6716or die_error(500,"Open git-diff-tree failed");6717@difftree=6718# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'6719# $hash == to_id6720grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}6721map{chomp;$_} <$fd>;6722close$fd6723or die_error(404,"Reading git-diff-tree failed");6724@difftree6725or die_error(404,"Blob diff not found");67266727}else{6728 die_error(400,"Missing one of the blob diff parameters");6729}67306731if(@difftree>1) {6732 die_error(400,"Ambiguous blob diff specification");6733}67346735%diffinfo= parse_difftree_raw_line($difftree[0]);6736$file_parent||=$diffinfo{'from_file'} ||$file_name;6737$file_name||=$diffinfo{'to_file'};67386739$hash_parent||=$diffinfo{'from_id'};6740$hash||=$diffinfo{'to_id'};67416742# non-textual hash id's can be cached6743if($hash_base=~m/^[0-9a-fA-F]{40}$/&&6744$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {6745$expires='+1d';6746}67476748# open patch output6749open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6750'-p', ($formateq'html'?"--full-index": ()),6751$hash_parent_base,$hash_base,6752"--", (defined$file_parent?$file_parent: ()),$file_name6753or die_error(500,"Open git-diff-tree failed");6754}67556756# old/legacy style URI -- not generated anymore since 1.4.3.6757if(!%diffinfo) {6758 die_error('404 Not Found',"Missing one of the blob diff parameters")6759}67606761# header6762if($formateq'html') {6763my$formats_nav=6764$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},6765"raw");6766 git_header_html(undef,$expires);6767if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6768 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6769 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6770}else{6771print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";6772print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";6773}6774if(defined$file_name) {6775 git_print_page_path($file_name,"blob",$hash_base);6776}else{6777print"<div class=\"page_path\"></div>\n";6778}67796780}elsif($formateq'plain') {6781print$cgi->header(6782-type =>'text/plain',6783-charset =>'utf-8',6784-expires =>$expires,6785-content_disposition =>'inline; filename="'."$file_name".'.patch"');67866787print"X-Git-Url: ".$cgi->self_url() ."\n\n";67886789}else{6790 die_error(400,"Unknown blobdiff format");6791}67926793# patch6794if($formateq'html') {6795print"<div class=\"page_body\">\n";67966797 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);6798close$fd;67996800print"</div>\n";# class="page_body"6801 git_footer_html();68026803}else{6804while(my$line= <$fd>) {6805$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;6806$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;68076808print$line;68096810last if$line=~m!^\+\+\+!;6811}6812local$/=undef;6813print<$fd>;6814close$fd;6815}6816}68176818sub git_blobdiff_plain {6819 git_blobdiff('plain');6820}68216822sub git_commitdiff {6823my%params=@_;6824my$format=$params{-format} ||'html';68256826my($patch_max) = gitweb_get_feature('patches');6827if($formateq'patch') {6828 die_error(403,"Patch view not allowed")unless$patch_max;6829}68306831$hash||=$hash_base||"HEAD";6832my%co= parse_commit($hash)6833or die_error(404,"Unknown commit object");68346835# choose format for commitdiff for merge6836if(!defined$hash_parent&& @{$co{'parents'}} >1) {6837$hash_parent='--cc';6838}6839# we need to prepare $formats_nav before almost any parameter munging6840my$formats_nav;6841if($formateq'html') {6842$formats_nav=6843$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},6844"raw");6845if($patch_max&& @{$co{'parents'}} <=1) {6846$formats_nav.=" | ".6847$cgi->a({-href => href(action=>"patch", -replay=>1)},6848"patch");6849}68506851if(defined$hash_parent&&6852$hash_parentne'-c'&&$hash_parentne'--cc') {6853# commitdiff with two commits given6854my$hash_parent_short=$hash_parent;6855if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {6856$hash_parent_short=substr($hash_parent,0,7);6857}6858$formats_nav.=6859' (from';6860for(my$i=0;$i< @{$co{'parents'}};$i++) {6861if($co{'parents'}[$i]eq$hash_parent) {6862$formats_nav.=' parent '. ($i+1);6863last;6864}6865}6866$formats_nav.=': '.6867$cgi->a({-href => href(action=>"commitdiff",6868 hash=>$hash_parent)},6869 esc_html($hash_parent_short)) .6870')';6871}elsif(!$co{'parent'}) {6872# --root commitdiff6873$formats_nav.=' (initial)';6874}elsif(scalar@{$co{'parents'}} ==1) {6875# single parent commit6876$formats_nav.=6877' (parent: '.6878$cgi->a({-href => href(action=>"commitdiff",6879 hash=>$co{'parent'})},6880 esc_html(substr($co{'parent'},0,7))) .6881')';6882}else{6883# merge commit6884if($hash_parenteq'--cc') {6885$formats_nav.=' | '.6886$cgi->a({-href => href(action=>"commitdiff",6887 hash=>$hash, hash_parent=>'-c')},6888'combined');6889}else{# $hash_parent eq '-c'6890$formats_nav.=' | '.6891$cgi->a({-href => href(action=>"commitdiff",6892 hash=>$hash, hash_parent=>'--cc')},6893'compact');6894}6895$formats_nav.=6896' (merge: '.6897join(' ',map{6898$cgi->a({-href => href(action=>"commitdiff",6899 hash=>$_)},6900 esc_html(substr($_,0,7)));6901} @{$co{'parents'}} ) .6902')';6903}6904}69056906my$hash_parent_param=$hash_parent;6907if(!defined$hash_parent_param) {6908# --cc for multiple parents, --root for parentless6909$hash_parent_param=6910@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';6911}69126913# read commitdiff6914my$fd;6915my@difftree;6916if($formateq'html') {6917open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6918"--no-commit-id","--patch-with-raw","--full-index",6919$hash_parent_param,$hash,"--"6920or die_error(500,"Open git-diff-tree failed");69216922while(my$line= <$fd>) {6923chomp$line;6924# empty line ends raw part of diff-tree output6925last unless$line;6926push@difftree,scalar parse_difftree_raw_line($line);6927}69286929}elsif($formateq'plain') {6930open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6931'-p',$hash_parent_param,$hash,"--"6932or die_error(500,"Open git-diff-tree failed");6933}elsif($formateq'patch') {6934# For commit ranges, we limit the output to the number of6935# patches specified in the 'patches' feature.6936# For single commits, we limit the output to a single patch,6937# diverging from the git-format-patch default.6938my@commit_spec= ();6939if($hash_parent) {6940if($patch_max>0) {6941push@commit_spec,"-$patch_max";6942}6943push@commit_spec,'-n',"$hash_parent..$hash";6944}else{6945if($params{-single}) {6946push@commit_spec,'-1';6947}else{6948if($patch_max>0) {6949push@commit_spec,"-$patch_max";6950}6951push@commit_spec,"-n";6952}6953push@commit_spec,'--root',$hash;6954}6955open$fd,"-|", git_cmd(),"format-patch",@diff_opts,6956'--encoding=utf8','--stdout',@commit_spec6957or die_error(500,"Open git-format-patch failed");6958}else{6959 die_error(400,"Unknown commitdiff format");6960}69616962# non-textual hash id's can be cached6963my$expires;6964if($hash=~m/^[0-9a-fA-F]{40}$/) {6965$expires="+1d";6966}69676968# write commit message6969if($formateq'html') {6970my$refs= git_get_references();6971my$ref= format_ref_marker($refs,$co{'id'});69726973 git_header_html(undef,$expires);6974 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);6975 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);6976print"<div class=\"title_text\">\n".6977"<table class=\"object_header\">\n";6978 git_print_authorship_rows(\%co);6979print"</table>".6980"</div>\n";6981print"<div class=\"page_body\">\n";6982if(@{$co{'comment'}} >1) {6983print"<div class=\"log\">\n";6984 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);6985print"</div>\n";# class="log"6986}69876988}elsif($formateq'plain') {6989my$refs= git_get_references("tags");6990my$tagname= git_get_rev_name_tags($hash);6991my$filename= basename($project) ."-$hash.patch";69926993print$cgi->header(6994-type =>'text/plain',6995-charset =>'utf-8',6996-expires =>$expires,6997-content_disposition =>'inline; filename="'."$filename".'"');6998my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});6999print"From: ". to_utf8($co{'author'}) ."\n";7000print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";7001print"Subject: ". to_utf8($co{'title'}) ."\n";70027003print"X-Git-Tag:$tagname\n"if$tagname;7004print"X-Git-Url: ".$cgi->self_url() ."\n\n";70057006foreachmy$line(@{$co{'comment'}}) {7007print to_utf8($line) ."\n";7008}7009print"---\n\n";7010}elsif($formateq'patch') {7011my$filename= basename($project) ."-$hash.patch";70127013print$cgi->header(7014-type =>'text/plain',7015-charset =>'utf-8',7016-expires =>$expires,7017-content_disposition =>'inline; filename="'."$filename".'"');7018}70197020# write patch7021if($formateq'html') {7022my$use_parents= !defined$hash_parent||7023$hash_parenteq'-c'||$hash_parenteq'--cc';7024 git_difftree_body(\@difftree,$hash,7025$use_parents? @{$co{'parents'}} :$hash_parent);7026print"<br/>\n";70277028 git_patchset_body($fd, \@difftree,$hash,7029$use_parents? @{$co{'parents'}} :$hash_parent);7030close$fd;7031print"</div>\n";# class="page_body"7032 git_footer_html();70337034}elsif($formateq'plain') {7035local$/=undef;7036print<$fd>;7037close$fd7038or print"Reading git-diff-tree failed\n";7039}elsif($formateq'patch') {7040local$/=undef;7041print<$fd>;7042close$fd7043or print"Reading git-format-patch failed\n";7044}7045}70467047sub git_commitdiff_plain {7048 git_commitdiff(-format =>'plain');7049}70507051# format-patch-style patches7052sub git_patch {7053 git_commitdiff(-format =>'patch', -single =>1);7054}70557056sub git_patches {7057 git_commitdiff(-format =>'patch');7058}70597060sub git_history {7061 git_log_generic('history', \&git_history_body,7062$hash_base,$hash_parent_base,7063$file_name,$hash);7064}70657066sub git_search {7067 gitweb_check_feature('search')or die_error(403,"Search is disabled");7068if(!defined$searchtext) {7069 die_error(400,"Text field is empty");7070}7071if(!defined$hash) {7072$hash= git_get_head_hash($project);7073}7074my%co= parse_commit($hash);7075if(!%co) {7076 die_error(404,"Unknown commit object");7077}7078if(!defined$page) {7079$page=0;7080}70817082$searchtype||='commit';7083if($searchtypeeq'pickaxe') {7084# pickaxe may take all resources of your box and run for several minutes7085# with every query - so decide by yourself how public you make this feature7086 gitweb_check_feature('pickaxe')7087or die_error(403,"Pickaxe is disabled");7088}7089if($searchtypeeq'grep') {7090 gitweb_check_feature('grep')7091or die_error(403,"Grep is disabled");7092}70937094 git_header_html();70957096if($searchtypeeq'commit'or$searchtypeeq'author'or$searchtypeeq'committer') {7097my$greptype;7098if($searchtypeeq'commit') {7099$greptype="--grep=";7100}elsif($searchtypeeq'author') {7101$greptype="--author=";7102}elsif($searchtypeeq'committer') {7103$greptype="--committer=";7104}7105$greptype.=$searchtext;7106my@commitlist= parse_commits($hash,101, (100*$page),undef,7107$greptype,'--regexp-ignore-case',7108$search_use_regexp?'--extended-regexp':'--fixed-strings');71097110my$paging_nav='';7111if($page>0) {7112$paging_nav.=7113$cgi->a({-href => href(action=>"search", hash=>$hash,7114 searchtext=>$searchtext,7115 searchtype=>$searchtype)},7116"first");7117$paging_nav.=" ⋅ ".7118$cgi->a({-href => href(-replay=>1, page=>$page-1),7119-accesskey =>"p", -title =>"Alt-p"},"prev");7120}else{7121$paging_nav.="first";7122$paging_nav.=" ⋅ prev";7123}7124my$next_link='';7125if($#commitlist>=100) {7126$next_link=7127$cgi->a({-href => href(-replay=>1, page=>$page+1),7128-accesskey =>"n", -title =>"Alt-n"},"next");7129$paging_nav.=" ⋅$next_link";7130}else{7131$paging_nav.=" ⋅ next";7132}71337134 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);7135 git_print_header_div('commit', esc_html($co{'title'}),$hash);7136if($page==0&& !@commitlist) {7137print"<p>No match.</p>\n";7138}else{7139 git_search_grep_body(\@commitlist,0,99,$next_link);7140}7141}71427143if($searchtypeeq'pickaxe') {7144 git_print_page_nav('','',$hash,$co{'tree'},$hash);7145 git_print_header_div('commit', esc_html($co{'title'}),$hash);71467147print"<table class=\"pickaxe search\">\n";7148my$alternate=1;7149local$/="\n";7150open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,7151'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",7152($search_use_regexp?'--pickaxe-regex': ());7153undef%co;7154my@files;7155while(my$line= <$fd>) {7156chomp$line;7157next unless$line;71587159my%set= parse_difftree_raw_line($line);7160if(defined$set{'commit'}) {7161# finish previous commit7162if(%co) {7163print"</td>\n".7164"<td class=\"link\">".7165$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .7166" | ".7167$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");7168print"</td>\n".7169"</tr>\n";7170}71717172if($alternate) {7173print"<tr class=\"dark\">\n";7174}else{7175print"<tr class=\"light\">\n";7176}7177$alternate^=1;7178%co= parse_commit($set{'commit'});7179my$author= chop_and_escape_str($co{'author_name'},15,5);7180print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".7181"<td><i>$author</i></td>\n".7182"<td>".7183$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),7184-class=>"list subject"},7185 chop_and_escape_str($co{'title'},50) ."<br/>");7186}elsif(defined$set{'to_id'}) {7187next if($set{'to_id'} =~m/^0{40}$/);71887189print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},7190 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),7191-class=>"list"},7192"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .7193"<br/>\n";7194}7195}7196close$fd;71977198# finish last commit (warning: repetition!)7199if(%co) {7200print"</td>\n".7201"<td class=\"link\">".7202$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .7203" | ".7204$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");7205print"</td>\n".7206"</tr>\n";7207}72087209print"</table>\n";7210}72117212if($searchtypeeq'grep') {7213 git_print_page_nav('','',$hash,$co{'tree'},$hash);7214 git_print_header_div('commit', esc_html($co{'title'}),$hash);72157216print"<table class=\"grep_search\">\n";7217my$alternate=1;7218my$matches=0;7219local$/="\n";7220open my$fd,"-|", git_cmd(),'grep','-n',7221$search_use_regexp? ('-E','-i') :'-F',7222$searchtext,$co{'tree'};7223my$lastfile='';7224while(my$line= <$fd>) {7225chomp$line;7226my($file,$lno,$ltext,$binary);7227last if($matches++>1000);7228if($line=~/^Binary file (.+) matches$/) {7229$file=$1;7230$binary=1;7231}else{7232(undef,$file,$lno,$ltext) =split(/:/,$line,4);7233}7234if($filene$lastfile) {7235$lastfileand print"</td></tr>\n";7236if($alternate++) {7237print"<tr class=\"dark\">\n";7238}else{7239print"<tr class=\"light\">\n";7240}7241print"<td class=\"list\">".7242$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},7243 file_name=>"$file"),7244-class=>"list"}, esc_path($file));7245print"</td><td>\n";7246$lastfile=$file;7247}7248if($binary) {7249print"<div class=\"binary\">Binary file</div>\n";7250}else{7251$ltext= untabify($ltext);7252if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {7253$ltext= esc_html($1, -nbsp=>1);7254$ltext.='<span class="match">';7255$ltext.= esc_html($2, -nbsp=>1);7256$ltext.='</span>';7257$ltext.= esc_html($3, -nbsp=>1);7258}else{7259$ltext= esc_html($ltext, -nbsp=>1);7260}7261print"<div class=\"pre\">".7262$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},7263 file_name=>"$file").'#l'.$lno,7264-class=>"linenr"},sprintf('%4i',$lno))7265.' '.$ltext."</div>\n";7266}7267}7268if($lastfile) {7269print"</td></tr>\n";7270if($matches>1000) {7271print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";7272}7273}else{7274print"<div class=\"diff nodifferences\">No matches found</div>\n";7275}7276close$fd;72777278print"</table>\n";7279}7280 git_footer_html();7281}72827283sub git_search_help {7284 git_header_html();7285 git_print_page_nav('','',$hash,$hash,$hash);7286print<<EOT;7287<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without7288regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,7289the pattern entered is recognized as the POSIX extended7290<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case7291insensitive).</p>7292<dl>7293<dt><b>commit</b></dt>7294<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>7295EOT7296my$have_grep= gitweb_check_feature('grep');7297if($have_grep) {7298print<<EOT;7299<dt><b>grep</b></dt>7300<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing7301 a different one) are searched for the given pattern. On large trees, this search can take7302a while and put some strain on the server, so please use it with some consideration. Note that7303due to git-grep peculiarity, currently if regexp mode is turned off, the matches are7304case-sensitive.</dd>7305EOT7306}7307print<<EOT;7308<dt><b>author</b></dt>7309<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>7310<dt><b>committer</b></dt>7311<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>7312EOT7313my$have_pickaxe= gitweb_check_feature('pickaxe');7314if($have_pickaxe) {7315print<<EOT;7316<dt><b>pickaxe</b></dt>7317<dd>All commits that caused the string to appear or disappear from any file (changes that7318added, removed or "modified" the string) will be listed. This search can take a while and7319takes a lot of strain on the server, so please use it wisely. Note that since you may be7320interested even in changes just changing the case as well, this search is case sensitive.</dd>7321EOT7322}7323print"</dl>\n";7324 git_footer_html();7325}73267327sub git_shortlog {7328 git_log_generic('shortlog', \&git_shortlog_body,7329$hash,$hash_parent);7330}73317332## ......................................................................7333## feeds (RSS, Atom; OPML)73347335sub git_feed {7336my$format=shift||'atom';7337my$have_blame= gitweb_check_feature('blame');73387339# Atom: http://www.atomenabled.org/developers/syndication/7340# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ7341if($formatne'rss'&&$formatne'atom') {7342 die_error(400,"Unknown web feed format");7343}73447345# log/feed of current (HEAD) branch, log of given branch, history of file/directory7346my$head=$hash||'HEAD';7347my@commitlist= parse_commits($head,150,0,$file_name);73487349my%latest_commit;7350my%latest_date;7351my$content_type="application/$format+xml";7352if(defined$cgi->http('HTTP_ACCEPT') &&7353$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {7354# browser (feed reader) prefers text/xml7355$content_type='text/xml';7356}7357if(defined($commitlist[0])) {7358%latest_commit= %{$commitlist[0]};7359my$latest_epoch=$latest_commit{'committer_epoch'};7360%latest_date= parse_date($latest_epoch,$latest_commit{'comitter_tz'});7361my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7362if(defined$if_modified) {7363my$since;7364if(eval{require HTTP::Date;1; }) {7365$since= HTTP::Date::str2time($if_modified);7366}elsif(eval{require Time::ParseDate;1; }) {7367$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7368}7369if(defined$since&&$latest_epoch<=$since) {7370print$cgi->header(7371-type =>$content_type,7372-charset =>'utf-8',7373-last_modified =>$latest_date{'rfc2822'},7374-status =>'304 Not Modified');7375return;7376}7377}7378print$cgi->header(7379-type =>$content_type,7380-charset =>'utf-8',7381-last_modified =>$latest_date{'rfc2822'});7382}else{7383print$cgi->header(7384-type =>$content_type,7385-charset =>'utf-8');7386}73877388# Optimization: skip generating the body if client asks only7389# for Last-Modified date.7390return if($cgi->request_method()eq'HEAD');73917392# header variables7393my$title="$site_name-$project/$action";7394my$feed_type='log';7395if(defined$hash) {7396$title.=" - '$hash'";7397$feed_type='branch log';7398if(defined$file_name) {7399$title.=" ::$file_name";7400$feed_type='history';7401}7402}elsif(defined$file_name) {7403$title.=" -$file_name";7404$feed_type='history';7405}7406$title.="$feed_type";7407my$descr= git_get_project_description($project);7408if(defined$descr) {7409$descr= esc_html($descr);7410}else{7411$descr="$project".7412($formateq'rss'?'RSS':'Atom') .7413" feed";7414}7415my$owner= git_get_project_owner($project);7416$owner= esc_html($owner);74177418#header7419my$alt_url;7420if(defined$file_name) {7421$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);7422}elsif(defined$hash) {7423$alt_url= href(-full=>1, action=>"log", hash=>$hash);7424}else{7425$alt_url= href(-full=>1, action=>"summary");7426}7427print qq!<?xml version="1.0" encoding="utf-8"?>\n!;7428if($formateq'rss') {7429print<<XML;7430<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">7431<channel>7432XML7433print"<title>$title</title>\n".7434"<link>$alt_url</link>\n".7435"<description>$descr</description>\n".7436"<language>en</language>\n".7437# project owner is responsible for 'editorial' content7438"<managingEditor>$owner</managingEditor>\n";7439if(defined$logo||defined$favicon) {7440# prefer the logo to the favicon, since RSS7441# doesn't allow both7442my$img= esc_url($logo||$favicon);7443print"<image>\n".7444"<url>$img</url>\n".7445"<title>$title</title>\n".7446"<link>$alt_url</link>\n".7447"</image>\n";7448}7449if(%latest_date) {7450print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";7451print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";7452}7453print"<generator>gitweb v.$version/$git_version</generator>\n";7454}elsif($formateq'atom') {7455print<<XML;7456<feed xmlns="http://www.w3.org/2005/Atom">7457XML7458print"<title>$title</title>\n".7459"<subtitle>$descr</subtitle>\n".7460'<link rel="alternate" type="text/html" href="'.7461$alt_url.'" />'."\n".7462'<link rel="self" type="'.$content_type.'" href="'.7463$cgi->self_url() .'" />'."\n".7464"<id>". href(-full=>1) ."</id>\n".7465# use project owner for feed author7466"<author><name>$owner</name></author>\n";7467if(defined$favicon) {7468print"<icon>". esc_url($favicon) ."</icon>\n";7469}7470if(defined$logo) {7471# not twice as wide as tall: 72 x 27 pixels7472print"<logo>". esc_url($logo) ."</logo>\n";7473}7474if(!%latest_date) {7475# dummy date to keep the feed valid until commits trickle in:7476print"<updated>1970-01-01T00:00:00Z</updated>\n";7477}else{7478print"<updated>$latest_date{'iso-8601'}</updated>\n";7479}7480print"<generator version='$version/$git_version'>gitweb</generator>\n";7481}74827483# contents7484for(my$i=0;$i<=$#commitlist;$i++) {7485my%co= %{$commitlist[$i]};7486my$commit=$co{'id'};7487# we read 150, we always show 30 and the ones more recent than 48 hours7488if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {7489last;7490}7491my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});74927493# get list of changed files7494open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7495$co{'parent'} ||"--root",7496$co{'id'},"--", (defined$file_name?$file_name: ())7497ornext;7498my@difftree=map{chomp;$_} <$fd>;7499close$fd7500ornext;75017502# print element (entry, item)7503my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);7504if($formateq'rss') {7505print"<item>\n".7506"<title>". esc_html($co{'title'}) ."</title>\n".7507"<author>". esc_html($co{'author'}) ."</author>\n".7508"<pubDate>$cd{'rfc2822'}</pubDate>\n".7509"<guid isPermaLink=\"true\">$co_url</guid>\n".7510"<link>$co_url</link>\n".7511"<description>". esc_html($co{'title'}) ."</description>\n".7512"<content:encoded>".7513"<![CDATA[\n";7514}elsif($formateq'atom') {7515print"<entry>\n".7516"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".7517"<updated>$cd{'iso-8601'}</updated>\n".7518"<author>\n".7519" <name>". esc_html($co{'author_name'}) ."</name>\n";7520if($co{'author_email'}) {7521print" <email>". esc_html($co{'author_email'}) ."</email>\n";7522}7523print"</author>\n".7524# use committer for contributor7525"<contributor>\n".7526" <name>". esc_html($co{'committer_name'}) ."</name>\n";7527if($co{'committer_email'}) {7528print" <email>". esc_html($co{'committer_email'}) ."</email>\n";7529}7530print"</contributor>\n".7531"<published>$cd{'iso-8601'}</published>\n".7532"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".7533"<id>$co_url</id>\n".7534"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".7535"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";7536}7537my$comment=$co{'comment'};7538print"<pre>\n";7539foreachmy$line(@$comment) {7540$line= esc_html($line);7541print"$line\n";7542}7543print"</pre><ul>\n";7544foreachmy$difftree_line(@difftree) {7545my%difftree= parse_difftree_raw_line($difftree_line);7546next if!$difftree{'from_id'};75477548my$file=$difftree{'file'} ||$difftree{'to_file'};75497550print"<li>".7551"[".7552$cgi->a({-href => href(-full=>1, action=>"blobdiff",7553 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},7554 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},7555 file_name=>$file, file_parent=>$difftree{'from_file'}),7556-title =>"diff"},'D');7557if($have_blame) {7558print$cgi->a({-href => href(-full=>1, action=>"blame",7559 file_name=>$file, hash_base=>$commit),7560-title =>"blame"},'B');7561}7562# if this is not a feed of a file history7563if(!defined$file_name||$file_namene$file) {7564print$cgi->a({-href => href(-full=>1, action=>"history",7565 file_name=>$file, hash=>$commit),7566-title =>"history"},'H');7567}7568$file= esc_path($file);7569print"] ".7570"$file</li>\n";7571}7572if($formateq'rss') {7573print"</ul>]]>\n".7574"</content:encoded>\n".7575"</item>\n";7576}elsif($formateq'atom') {7577print"</ul>\n</div>\n".7578"</content>\n".7579"</entry>\n";7580}7581}75827583# end of feed7584if($formateq'rss') {7585print"</channel>\n</rss>\n";7586}elsif($formateq'atom') {7587print"</feed>\n";7588}7589}75907591sub git_rss {7592 git_feed('rss');7593}75947595sub git_atom {7596 git_feed('atom');7597}75987599sub git_opml {7600my@list= git_get_projects_list();7601if(!@list) {7602 die_error(404,"No projects found");7603}76047605print$cgi->header(7606-type =>'text/xml',7607-charset =>'utf-8',7608-content_disposition =>'inline; filename="opml.xml"');76097610print<<XML;7611<?xml version="1.0" encoding="utf-8"?>7612<opml version="1.0">7613<head>7614 <title>$site_nameOPML Export</title>7615</head>7616<body>7617<outline text="git RSS feeds">7618XML76197620foreachmy$pr(@list) {7621my%proj=%$pr;7622my$head= git_get_head_hash($proj{'path'});7623if(!defined$head) {7624next;7625}7626$git_dir="$projectroot/$proj{'path'}";7627my%co= parse_commit($head);7628if(!%co) {7629next;7630}76317632my$path= esc_html(chop_str($proj{'path'},25,5));7633my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);7634my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);7635print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";7636}7637print<<XML;7638</outline>7639</body>7640</opml>7641XML7642}