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# 325# Note that this controls all search features, which means that if 326# it is disabled, then 'grep' and 'pickaxe' search would also be 327# disabled. 328'search'=> { 329'override'=>0, 330'default'=> [1]}, 331 332# Enable grep search, which will list the files in currently selected 333# tree containing the given string. Enabled by default. This can be 334# potentially CPU-intensive, of course. 335# Note that you need to have 'search' feature enabled too. 336 337# To enable system wide have in $GITWEB_CONFIG 338# $feature{'grep'}{'default'} = [1]; 339# To have project specific config enable override in $GITWEB_CONFIG 340# $feature{'grep'}{'override'} = 1; 341# and in project config gitweb.grep = 0|1; 342'grep'=> { 343'sub'=>sub{ feature_bool('grep',@_) }, 344'override'=>0, 345'default'=> [1]}, 346 347# Enable the pickaxe search, which will list the commits that modified 348# a given string in a file. This can be practical and quite faster 349# alternative to 'blame', but still potentially CPU-intensive. 350# Note that you need to have 'search' feature enabled too. 351 352# To enable system wide have in $GITWEB_CONFIG 353# $feature{'pickaxe'}{'default'} = [1]; 354# To have project specific config enable override in $GITWEB_CONFIG 355# $feature{'pickaxe'}{'override'} = 1; 356# and in project config gitweb.pickaxe = 0|1; 357'pickaxe'=> { 358'sub'=>sub{ feature_bool('pickaxe',@_) }, 359'override'=>0, 360'default'=> [1]}, 361 362# Enable showing size of blobs in a 'tree' view, in a separate 363# column, similar to what 'ls -l' does. This cost a bit of IO. 364 365# To disable system wide have in $GITWEB_CONFIG 366# $feature{'show-sizes'}{'default'} = [0]; 367# To have project specific config enable override in $GITWEB_CONFIG 368# $feature{'show-sizes'}{'override'} = 1; 369# and in project config gitweb.showsizes = 0|1; 370'show-sizes'=> { 371'sub'=>sub{ feature_bool('showsizes',@_) }, 372'override'=>0, 373'default'=> [1]}, 374 375# Make gitweb use an alternative format of the URLs which can be 376# more readable and natural-looking: project name is embedded 377# directly in the path and the query string contains other 378# auxiliary information. All gitweb installations recognize 379# URL in either format; this configures in which formats gitweb 380# generates links. 381 382# To enable system wide have in $GITWEB_CONFIG 383# $feature{'pathinfo'}{'default'} = [1]; 384# Project specific override is not supported. 385 386# Note that you will need to change the default location of CSS, 387# favicon, logo and possibly other files to an absolute URL. Also, 388# if gitweb.cgi serves as your indexfile, you will need to force 389# $my_uri to contain the script name in your $GITWEB_CONFIG. 390'pathinfo'=> { 391'override'=>0, 392'default'=> [0]}, 393 394# Make gitweb consider projects in project root subdirectories 395# to be forks of existing projects. Given project $projname.git, 396# projects matching $projname/*.git will not be shown in the main 397# projects list, instead a '+' mark will be added to $projname 398# there and a 'forks' view will be enabled for the project, listing 399# all the forks. If project list is taken from a file, forks have 400# to be listed after the main project. 401 402# To enable system wide have in $GITWEB_CONFIG 403# $feature{'forks'}{'default'} = [1]; 404# Project specific override is not supported. 405'forks'=> { 406'override'=>0, 407'default'=> [0]}, 408 409# Insert custom links to the action bar of all project pages. 410# This enables you mainly to link to third-party scripts integrating 411# into gitweb; e.g. git-browser for graphical history representation 412# or custom web-based repository administration interface. 413 414# The 'default' value consists of a list of triplets in the form 415# (label, link, position) where position is the label after which 416# to insert the link and link is a format string where %n expands 417# to the project name, %f to the project path within the filesystem, 418# %h to the current hash (h gitweb parameter) and %b to the current 419# hash base (hb gitweb parameter); %% expands to %. 420 421# To enable system wide have in $GITWEB_CONFIG e.g. 422# $feature{'actions'}{'default'} = [('graphiclog', 423# '/git-browser/by-commit.html?r=%n', 'summary')]; 424# Project specific override is not supported. 425'actions'=> { 426'override'=>0, 427'default'=> []}, 428 429# Allow gitweb scan project content tags of project repository, 430# and display the popular Web 2.0-ish "tag cloud" near the projects 431# list. Note that this is something COMPLETELY different from the 432# normal Git tags. 433 434# gitweb by itself can show existing tags, but it does not handle 435# tagging itself; you need to do it externally, outside gitweb. 436# The format is described in git_get_project_ctags() subroutine. 437# You may want to install the HTML::TagCloud Perl module to get 438# a pretty tag cloud instead of just a list of tags. 439 440# To enable system wide have in $GITWEB_CONFIG 441# $feature{'ctags'}{'default'} = [1]; 442# Project specific override is not supported. 443 444# In the future whether ctags editing is enabled might depend 445# on the value, but using 1 should always mean no editing of ctags. 446'ctags'=> { 447'override'=>0, 448'default'=> [0]}, 449 450# The maximum number of patches in a patchset generated in patch 451# view. Set this to 0 or undef to disable patch view, or to a 452# negative number to remove any limit. 453 454# To disable system wide have in $GITWEB_CONFIG 455# $feature{'patches'}{'default'} = [0]; 456# To have project specific config enable override in $GITWEB_CONFIG 457# $feature{'patches'}{'override'} = 1; 458# and in project config gitweb.patches = 0|n; 459# where n is the maximum number of patches allowed in a patchset. 460'patches'=> { 461'sub'=> \&feature_patches, 462'override'=>0, 463'default'=> [16]}, 464 465# Avatar support. When this feature is enabled, views such as 466# shortlog or commit will display an avatar associated with 467# the email of the committer(s) and/or author(s). 468 469# Currently available providers are gravatar and picon. 470# If an unknown provider is specified, the feature is disabled. 471 472# Gravatar depends on Digest::MD5. 473# Picon currently relies on the indiana.edu database. 474 475# To enable system wide have in $GITWEB_CONFIG 476# $feature{'avatar'}{'default'} = ['<provider>']; 477# where <provider> is either gravatar or picon. 478# To have project specific config enable override in $GITWEB_CONFIG 479# $feature{'avatar'}{'override'} = 1; 480# and in project config gitweb.avatar = <provider>; 481'avatar'=> { 482'sub'=> \&feature_avatar, 483'override'=>0, 484'default'=> ['']}, 485 486# Enable displaying how much time and how many git commands 487# it took to generate and display page. Disabled by default. 488# Project specific override is not supported. 489'timed'=> { 490'override'=>0, 491'default'=> [0]}, 492 493# Enable turning some links into links to actions which require 494# JavaScript to run (like 'blame_incremental'). Not enabled by 495# default. Project specific override is currently not supported. 496'javascript-actions'=> { 497'override'=>0, 498'default'=> [0]}, 499 500# Enable and configure ability to change common timezone for dates 501# in gitweb output via JavaScript. Enabled by default. 502# Project specific override is not supported. 503'javascript-timezone'=> { 504'override'=>0, 505'default'=> [ 506'local',# default timezone: 'utc', 'local', or '(-|+)HHMM' format, 507# or undef to turn off this feature 508'gitweb_tz',# name of cookie where to store selected timezone 509'datetime',# CSS class used to mark up dates for manipulation 510]}, 511 512# Syntax highlighting support. This is based on Daniel Svensson's 513# and Sham Chukoury's work in gitweb-xmms2.git. 514# It requires the 'highlight' program present in $PATH, 515# and therefore is disabled by default. 516 517# To enable system wide have in $GITWEB_CONFIG 518# $feature{'highlight'}{'default'} = [1]; 519 520'highlight'=> { 521'sub'=>sub{ feature_bool('highlight',@_) }, 522'override'=>0, 523'default'=> [0]}, 524 525# Enable displaying of remote heads in the heads list 526 527# To enable system wide have in $GITWEB_CONFIG 528# $feature{'remote_heads'}{'default'} = [1]; 529# To have project specific config enable override in $GITWEB_CONFIG 530# $feature{'remote_heads'}{'override'} = 1; 531# and in project config gitweb.remote_heads = 0|1; 532'remote_heads'=> { 533'sub'=>sub{ feature_bool('remote_heads',@_) }, 534'override'=>0, 535'default'=> [0]}, 536); 537 538sub gitweb_get_feature { 539my($name) =@_; 540return unlessexists$feature{$name}; 541my($sub,$override,@defaults) = ( 542$feature{$name}{'sub'}, 543$feature{$name}{'override'}, 544@{$feature{$name}{'default'}}); 545# project specific override is possible only if we have project 546our$git_dir;# global variable, declared later 547if(!$override|| !defined$git_dir) { 548return@defaults; 549} 550if(!defined$sub) { 551warn"feature$nameis not overridable"; 552return@defaults; 553} 554return$sub->(@defaults); 555} 556 557# A wrapper to check if a given feature is enabled. 558# With this, you can say 559# 560# my $bool_feat = gitweb_check_feature('bool_feat'); 561# gitweb_check_feature('bool_feat') or somecode; 562# 563# instead of 564# 565# my ($bool_feat) = gitweb_get_feature('bool_feat'); 566# (gitweb_get_feature('bool_feat'))[0] or somecode; 567# 568sub gitweb_check_feature { 569return(gitweb_get_feature(@_))[0]; 570} 571 572 573sub feature_bool { 574my$key=shift; 575my($val) = git_get_project_config($key,'--bool'); 576 577if(!defined$val) { 578return($_[0]); 579}elsif($valeq'true') { 580return(1); 581}elsif($valeq'false') { 582return(0); 583} 584} 585 586sub feature_snapshot { 587my(@fmts) =@_; 588 589my($val) = git_get_project_config('snapshot'); 590 591if($val) { 592@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 593} 594 595return@fmts; 596} 597 598sub feature_patches { 599my@val= (git_get_project_config('patches','--int')); 600 601if(@val) { 602return@val; 603} 604 605return($_[0]); 606} 607 608sub feature_avatar { 609my@val= (git_get_project_config('avatar')); 610 611return@val?@val:@_; 612} 613 614# checking HEAD file with -e is fragile if the repository was 615# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 616# and then pruned. 617sub check_head_link { 618my($dir) =@_; 619my$headfile="$dir/HEAD"; 620return((-e $headfile) || 621(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 622} 623 624sub check_export_ok { 625my($dir) =@_; 626return(check_head_link($dir) && 627(!$export_ok|| -e "$dir/$export_ok") && 628(!$export_auth_hook||$export_auth_hook->($dir))); 629} 630 631# process alternate names for backward compatibility 632# filter out unsupported (unknown) snapshot formats 633sub filter_snapshot_fmts { 634my@fmts=@_; 635 636@fmts=map{ 637exists$known_snapshot_format_aliases{$_} ? 638$known_snapshot_format_aliases{$_} :$_}@fmts; 639@fmts=grep{ 640exists$known_snapshot_formats{$_} && 641!$known_snapshot_formats{$_}{'disabled'}}@fmts; 642} 643 644# If it is set to code reference, it is code that it is to be run once per 645# request, allowing updating configurations that change with each request, 646# while running other code in config file only once. 647# 648# Otherwise, if it is false then gitweb would process config file only once; 649# if it is true then gitweb config would be run for each request. 650our$per_request_config=1; 651 652# read and parse gitweb config file given by its parameter. 653# returns true on success, false on recoverable error, allowing 654# to chain this subroutine, using first file that exists. 655# dies on errors during parsing config file, as it is unrecoverable. 656sub read_config_file { 657my$filename=shift; 658return unlessdefined$filename; 659# die if there are errors parsing config file 660if(-e $filename) { 661do$filename; 662die$@if$@; 663return1; 664} 665return; 666} 667 668our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM,$GITWEB_CONFIG_COMMON); 669sub evaluate_gitweb_config { 670our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 671our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 672our$GITWEB_CONFIG_COMMON=$ENV{'GITWEB_CONFIG_COMMON'} ||"++GITWEB_CONFIG_COMMON++"; 673 674# Protect agains duplications of file names, to not read config twice. 675# Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so 676# there possibility of duplication of filename there doesn't matter. 677$GITWEB_CONFIG=""if($GITWEB_CONFIGeq$GITWEB_CONFIG_COMMON); 678$GITWEB_CONFIG_SYSTEM=""if($GITWEB_CONFIG_SYSTEMeq$GITWEB_CONFIG_COMMON); 679 680# Common system-wide settings for convenience. 681# Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM. 682 read_config_file($GITWEB_CONFIG_COMMON); 683 684# Use first config file that exists. This means use the per-instance 685# GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG. 686 read_config_file($GITWEB_CONFIG)andreturn; 687 read_config_file($GITWEB_CONFIG_SYSTEM); 688} 689 690# Get loadavg of system, to compare against $maxload. 691# Currently it requires '/proc/loadavg' present to get loadavg; 692# if it is not present it returns 0, which means no load checking. 693sub get_loadavg { 694if( -e '/proc/loadavg'){ 695open my$fd,'<','/proc/loadavg' 696orreturn0; 697my@load=split(/\s+/,scalar<$fd>); 698close$fd; 699 700# The first three columns measure CPU and IO utilization of the last one, 701# five, and 10 minute periods. The fourth column shows the number of 702# currently running processes and the total number of processes in the m/n 703# format. The last column displays the last process ID used. 704return$load[0] ||0; 705} 706# additional checks for load average should go here for things that don't export 707# /proc/loadavg 708 709return0; 710} 711 712# version of the core git binary 713our$git_version; 714sub evaluate_git_version { 715our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 716$number_of_git_cmds++; 717} 718 719sub check_loadavg { 720if(defined$maxload&& get_loadavg() >$maxload) { 721 die_error(503,"The load average on the server is too high"); 722} 723} 724 725# ====================================================================== 726# input validation and dispatch 727 728# input parameters can be collected from a variety of sources (presently, CGI 729# and PATH_INFO), so we define an %input_params hash that collects them all 730# together during validation: this allows subsequent uses (e.g. href()) to be 731# agnostic of the parameter origin 732 733our%input_params= (); 734 735# input parameters are stored with the long parameter name as key. This will 736# also be used in the href subroutine to convert parameters to their CGI 737# equivalent, and since the href() usage is the most frequent one, we store 738# the name -> CGI key mapping here, instead of the reverse. 739# 740# XXX: Warning: If you touch this, check the search form for updating, 741# too. 742 743our@cgi_param_mapping= ( 744 project =>"p", 745 action =>"a", 746 file_name =>"f", 747 file_parent =>"fp", 748 hash =>"h", 749 hash_parent =>"hp", 750 hash_base =>"hb", 751 hash_parent_base =>"hpb", 752 page =>"pg", 753 order =>"o", 754 searchtext =>"s", 755 searchtype =>"st", 756 snapshot_format =>"sf", 757 extra_options =>"opt", 758 search_use_regexp =>"sr", 759 ctag =>"by_tag", 760# this must be last entry (for manipulation from JavaScript) 761 javascript =>"js" 762); 763our%cgi_param_mapping=@cgi_param_mapping; 764 765# we will also need to know the possible actions, for validation 766our%actions= ( 767"blame"=> \&git_blame, 768"blame_incremental"=> \&git_blame_incremental, 769"blame_data"=> \&git_blame_data, 770"blobdiff"=> \&git_blobdiff, 771"blobdiff_plain"=> \&git_blobdiff_plain, 772"blob"=> \&git_blob, 773"blob_plain"=> \&git_blob_plain, 774"commitdiff"=> \&git_commitdiff, 775"commitdiff_plain"=> \&git_commitdiff_plain, 776"commit"=> \&git_commit, 777"forks"=> \&git_forks, 778"heads"=> \&git_heads, 779"history"=> \&git_history, 780"log"=> \&git_log, 781"patch"=> \&git_patch, 782"patches"=> \&git_patches, 783"remotes"=> \&git_remotes, 784"rss"=> \&git_rss, 785"atom"=> \&git_atom, 786"search"=> \&git_search, 787"search_help"=> \&git_search_help, 788"shortlog"=> \&git_shortlog, 789"summary"=> \&git_summary, 790"tag"=> \&git_tag, 791"tags"=> \&git_tags, 792"tree"=> \&git_tree, 793"snapshot"=> \&git_snapshot, 794"object"=> \&git_object, 795# those below don't need $project 796"opml"=> \&git_opml, 797"project_list"=> \&git_project_list, 798"project_index"=> \&git_project_index, 799); 800 801# finally, we have the hash of allowed extra_options for the commands that 802# allow them 803our%allowed_options= ( 804"--no-merges"=> [qw(rss atom log shortlog history)], 805); 806 807# fill %input_params with the CGI parameters. All values except for 'opt' 808# should be single values, but opt can be an array. We should probably 809# build an array of parameters that can be multi-valued, but since for the time 810# being it's only this one, we just single it out 811sub evaluate_query_params { 812our$cgi; 813 814while(my($name,$symbol) =each%cgi_param_mapping) { 815if($symboleq'opt') { 816$input_params{$name} = [$cgi->param($symbol) ]; 817}else{ 818$input_params{$name} =$cgi->param($symbol); 819} 820} 821} 822 823# now read PATH_INFO and update the parameter list for missing parameters 824sub evaluate_path_info { 825return ifdefined$input_params{'project'}; 826return if!$path_info; 827$path_info=~ s,^/+,,; 828return if!$path_info; 829 830# find which part of PATH_INFO is project 831my$project=$path_info; 832$project=~ s,/+$,,; 833while($project&& !check_head_link("$projectroot/$project")) { 834$project=~ s,/*[^/]*$,,; 835} 836return unless$project; 837$input_params{'project'} =$project; 838 839# do not change any parameters if an action is given using the query string 840return if$input_params{'action'}; 841$path_info=~ s,^\Q$project\E/*,,; 842 843# next, check if we have an action 844my$action=$path_info; 845$action=~ s,/.*$,,; 846if(exists$actions{$action}) { 847$path_info=~ s,^$action/*,,; 848$input_params{'action'} =$action; 849} 850 851# list of actions that want hash_base instead of hash, but can have no 852# pathname (f) parameter 853my@wants_base= ( 854'tree', 855'history', 856); 857 858# we want to catch, among others 859# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 860my($parentrefname,$parentpathname,$refname,$pathname) = 861($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/); 862 863# first, analyze the 'current' part 864if(defined$pathname) { 865# we got "branch:filename" or "branch:dir/" 866# we could use git_get_type(branch:pathname), but: 867# - it needs $git_dir 868# - it does a git() call 869# - the convention of terminating directories with a slash 870# makes it superfluous 871# - embedding the action in the PATH_INFO would make it even 872# more superfluous 873$pathname=~ s,^/+,,; 874if(!$pathname||substr($pathname, -1)eq"/") { 875$input_params{'action'} ||="tree"; 876$pathname=~ s,/$,,; 877}else{ 878# the default action depends on whether we had parent info 879# or not 880if($parentrefname) { 881$input_params{'action'} ||="blobdiff_plain"; 882}else{ 883$input_params{'action'} ||="blob_plain"; 884} 885} 886$input_params{'hash_base'} ||=$refname; 887$input_params{'file_name'} ||=$pathname; 888}elsif(defined$refname) { 889# we got "branch". In this case we have to choose if we have to 890# set hash or hash_base. 891# 892# Most of the actions without a pathname only want hash to be 893# set, except for the ones specified in @wants_base that want 894# hash_base instead. It should also be noted that hand-crafted 895# links having 'history' as an action and no pathname or hash 896# set will fail, but that happens regardless of PATH_INFO. 897if(defined$parentrefname) { 898# if there is parent let the default be 'shortlog' action 899# (for http://git.example.com/repo.git/A..B links); if there 900# is no parent, dispatch will detect type of object and set 901# action appropriately if required (if action is not set) 902$input_params{'action'} ||="shortlog"; 903} 904if($input_params{'action'} && 905grep{$_eq$input_params{'action'} }@wants_base) { 906$input_params{'hash_base'} ||=$refname; 907}else{ 908$input_params{'hash'} ||=$refname; 909} 910} 911 912# next, handle the 'parent' part, if present 913if(defined$parentrefname) { 914# a missing pathspec defaults to the 'current' filename, allowing e.g. 915# someproject/blobdiff/oldrev..newrev:/filename 916if($parentpathname) { 917$parentpathname=~ s,^/+,,; 918$parentpathname=~ s,/$,,; 919$input_params{'file_parent'} ||=$parentpathname; 920}else{ 921$input_params{'file_parent'} ||=$input_params{'file_name'}; 922} 923# we assume that hash_parent_base is wanted if a path was specified, 924# or if the action wants hash_base instead of hash 925if(defined$input_params{'file_parent'} || 926grep{$_eq$input_params{'action'} }@wants_base) { 927$input_params{'hash_parent_base'} ||=$parentrefname; 928}else{ 929$input_params{'hash_parent'} ||=$parentrefname; 930} 931} 932 933# for the snapshot action, we allow URLs in the form 934# $project/snapshot/$hash.ext 935# where .ext determines the snapshot and gets removed from the 936# passed $refname to provide the $hash. 937# 938# To be able to tell that $refname includes the format extension, we 939# require the following two conditions to be satisfied: 940# - the hash input parameter MUST have been set from the $refname part 941# of the URL (i.e. they must be equal) 942# - the snapshot format MUST NOT have been defined already (e.g. from 943# CGI parameter sf) 944# It's also useless to try any matching unless $refname has a dot, 945# so we check for that too 946if(defined$input_params{'action'} && 947$input_params{'action'}eq'snapshot'&& 948defined$refname&&index($refname,'.') != -1&& 949$refnameeq$input_params{'hash'} && 950!defined$input_params{'snapshot_format'}) { 951# We loop over the known snapshot formats, checking for 952# extensions. Allowed extensions are both the defined suffix 953# (which includes the initial dot already) and the snapshot 954# format key itself, with a prepended dot 955while(my($fmt,$opt) =each%known_snapshot_formats) { 956my$hash=$refname; 957unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 958next; 959} 960my$sfx=$1; 961# a valid suffix was found, so set the snapshot format 962# and reset the hash parameter 963$input_params{'snapshot_format'} =$fmt; 964$input_params{'hash'} =$hash; 965# we also set the format suffix to the one requested 966# in the URL: this way a request for e.g. .tgz returns 967# a .tgz instead of a .tar.gz 968$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 969last; 970} 971} 972} 973 974our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 975$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 976$searchtext,$search_regexp); 977sub evaluate_and_validate_params { 978our$action=$input_params{'action'}; 979if(defined$action) { 980if(!validate_action($action)) { 981 die_error(400,"Invalid action parameter"); 982} 983} 984 985# parameters which are pathnames 986our$project=$input_params{'project'}; 987if(defined$project) { 988if(!validate_project($project)) { 989undef$project; 990 die_error(404,"No such project"); 991} 992} 993 994our$file_name=$input_params{'file_name'}; 995if(defined$file_name) { 996if(!validate_pathname($file_name)) { 997 die_error(400,"Invalid file parameter"); 998} 999}10001001our$file_parent=$input_params{'file_parent'};1002if(defined$file_parent) {1003if(!validate_pathname($file_parent)) {1004 die_error(400,"Invalid file parent parameter");1005}1006}10071008# parameters which are refnames1009our$hash=$input_params{'hash'};1010if(defined$hash) {1011if(!validate_refname($hash)) {1012 die_error(400,"Invalid hash parameter");1013}1014}10151016our$hash_parent=$input_params{'hash_parent'};1017if(defined$hash_parent) {1018if(!validate_refname($hash_parent)) {1019 die_error(400,"Invalid hash parent parameter");1020}1021}10221023our$hash_base=$input_params{'hash_base'};1024if(defined$hash_base) {1025if(!validate_refname($hash_base)) {1026 die_error(400,"Invalid hash base parameter");1027}1028}10291030our@extra_options= @{$input_params{'extra_options'}};1031# @extra_options is always defined, since it can only be (currently) set from1032# CGI, and $cgi->param() returns the empty array in array context if the param1033# is not set1034foreachmy$opt(@extra_options) {1035if(not exists$allowed_options{$opt}) {1036 die_error(400,"Invalid option parameter");1037}1038if(not grep(/^$action$/, @{$allowed_options{$opt}})) {1039 die_error(400,"Invalid option parameter for this action");1040}1041}10421043our$hash_parent_base=$input_params{'hash_parent_base'};1044if(defined$hash_parent_base) {1045if(!validate_refname($hash_parent_base)) {1046 die_error(400,"Invalid hash parent base parameter");1047}1048}10491050# other parameters1051our$page=$input_params{'page'};1052if(defined$page) {1053if($page=~m/[^0-9]/) {1054 die_error(400,"Invalid page parameter");1055}1056}10571058our$searchtype=$input_params{'searchtype'};1059if(defined$searchtype) {1060if($searchtype=~m/[^a-z]/) {1061 die_error(400,"Invalid searchtype parameter");1062}1063}10641065our$search_use_regexp=$input_params{'search_use_regexp'};10661067our$searchtext=$input_params{'searchtext'};1068our$search_regexp;1069if(defined$searchtext) {1070if(length($searchtext) <2) {1071 die_error(403,"At least two characters are required for search parameter");1072}1073$search_regexp=$search_use_regexp?$searchtext:quotemeta$searchtext;1074}1075}10761077# path to the current git repository1078our$git_dir;1079sub evaluate_git_dir {1080our$git_dir="$projectroot/$project"if$project;1081}10821083our(@snapshot_fmts,$git_avatar);1084sub configure_gitweb_features {1085# list of supported snapshot formats1086our@snapshot_fmts= gitweb_get_feature('snapshot');1087@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);10881089# check that the avatar feature is set to a known provider name,1090# and for each provider check if the dependencies are satisfied.1091# if the provider name is invalid or the dependencies are not met,1092# reset $git_avatar to the empty string.1093our($git_avatar) = gitweb_get_feature('avatar');1094if($git_avatareq'gravatar') {1095$git_avatar=''unless(eval{require Digest::MD5;1; });1096}elsif($git_avatareq'picon') {1097# no dependencies1098}else{1099$git_avatar='';1100}1101}11021103# custom error handler: 'die <message>' is Internal Server Error1104sub handle_errors_html {1105my$msg=shift;# it is already HTML escaped11061107# to avoid infinite loop where error occurs in die_error,1108# change handler to default handler, disabling handle_errors_html1109 set_message("Error occured when inside die_error:\n$msg");11101111# you cannot jump out of die_error when called as error handler;1112# the subroutine set via CGI::Carp::set_message is called _after_1113# HTTP headers are already written, so it cannot write them itself1114 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1115}1116set_message(\&handle_errors_html);11171118# dispatch1119sub dispatch {1120if(!defined$action) {1121if(defined$hash) {1122$action= git_get_type($hash);1123}elsif(defined$hash_base&&defined$file_name) {1124$action= git_get_type("$hash_base:$file_name");1125}elsif(defined$project) {1126$action='summary';1127}else{1128$action='project_list';1129}1130}1131if(!defined($actions{$action})) {1132 die_error(400,"Unknown action");1133}1134if($action!~m/^(?:opml|project_list|project_index)$/&&1135!$project) {1136 die_error(400,"Project needed");1137}1138$actions{$action}->();1139}11401141sub reset_timer {1142our$t0= [ gettimeofday() ]1143ifdefined$t0;1144our$number_of_git_cmds=0;1145}11461147our$first_request=1;1148sub run_request {1149 reset_timer();11501151 evaluate_uri();1152if($first_request) {1153 evaluate_gitweb_config();1154 evaluate_git_version();1155}1156if($per_request_config) {1157if(ref($per_request_config)eq'CODE') {1158$per_request_config->();1159}elsif(!$first_request) {1160 evaluate_gitweb_config();1161}1162}1163 check_loadavg();11641165# $projectroot and $projects_list might be set in gitweb config file1166$projects_list||=$projectroot;11671168 evaluate_query_params();1169 evaluate_path_info();1170 evaluate_and_validate_params();1171 evaluate_git_dir();11721173 configure_gitweb_features();11741175 dispatch();1176}11771178our$is_last_request=sub{1};1179our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1180our$CGI='CGI';1181our$cgi;1182sub configure_as_fcgi {1183require CGI::Fast;1184our$CGI='CGI::Fast';11851186my$request_number=0;1187# let each child service 100 requests1188our$is_last_request=sub{ ++$request_number>100};1189}1190sub evaluate_argv {1191my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1192 configure_as_fcgi()1193if$script_name=~/\.fcgi$/;11941195return unless(@ARGV);11961197require Getopt::Long;1198 Getopt::Long::GetOptions(1199'fastcgi|fcgi|f'=> \&configure_as_fcgi,1200'nproc|n=i'=>sub{1201my($arg,$val) =@_;1202return unlesseval{require FCGI::ProcManager;1; };1203my$proc_manager= FCGI::ProcManager->new({1204 n_processes =>$val,1205});1206our$pre_listen_hook=sub{$proc_manager->pm_manage() };1207our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1208our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1209},1210);1211}12121213sub run {1214 evaluate_argv();12151216$first_request=1;1217$pre_listen_hook->()1218if$pre_listen_hook;12191220 REQUEST:1221while($cgi=$CGI->new()) {1222$pre_dispatch_hook->()1223if$pre_dispatch_hook;12241225 run_request();12261227$post_dispatch_hook->()1228if$post_dispatch_hook;1229$first_request=0;12301231last REQUEST if($is_last_request->());1232}12331234 DONE_GITWEB:12351;1236}12371238run();12391240if(defined caller) {1241# wrapped in a subroutine processing requests,1242# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1243return;1244}else{1245# pure CGI script, serving single request1246exit;1247}12481249## ======================================================================1250## action links12511252# possible values of extra options1253# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1254# -replay => 1 - start from a current view (replay with modifications)1255# -path_info => 0|1 - don't use/use path_info URL (if possible)1256# -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone1257sub href {1258my%params=@_;1259# default is to use -absolute url() i.e. $my_uri1260my$href=$params{-full} ?$my_url:$my_uri;12611262# implicit -replay, must be first of implicit params1263$params{-replay} =1if(keys%params==1&&$params{-anchor});12641265$params{'project'} =$projectunlessexists$params{'project'};12661267if($params{-replay}) {1268while(my($name,$symbol) =each%cgi_param_mapping) {1269if(!exists$params{$name}) {1270$params{$name} =$input_params{$name};1271}1272}1273}12741275my$use_pathinfo= gitweb_check_feature('pathinfo');1276if(defined$params{'project'} &&1277(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1278# try to put as many parameters as possible in PATH_INFO:1279# - project name1280# - action1281# - hash_parent or hash_parent_base:/file_parent1282# - hash or hash_base:/filename1283# - the snapshot_format as an appropriate suffix12841285# When the script is the root DirectoryIndex for the domain,1286# $href here would be something like http://gitweb.example.com/1287# Thus, we strip any trailing / from $href, to spare us double1288# slashes in the final URL1289$href=~ s,/$,,;12901291# Then add the project name, if present1292$href.="/".esc_path_info($params{'project'});1293delete$params{'project'};12941295# since we destructively absorb parameters, we keep this1296# boolean that remembers if we're handling a snapshot1297my$is_snapshot=$params{'action'}eq'snapshot';12981299# Summary just uses the project path URL, any other action is1300# added to the URL1301if(defined$params{'action'}) {1302$href.="/".esc_path_info($params{'action'})1303unless$params{'action'}eq'summary';1304delete$params{'action'};1305}13061307# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1308# stripping nonexistent or useless pieces1309$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1310||$params{'hash_parent'} ||$params{'hash'});1311if(defined$params{'hash_base'}) {1312if(defined$params{'hash_parent_base'}) {1313$href.= esc_path_info($params{'hash_parent_base'});1314# skip the file_parent if it's the same as the file_name1315if(defined$params{'file_parent'}) {1316if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1317delete$params{'file_parent'};1318}elsif($params{'file_parent'} !~/\.\./) {1319$href.=":/".esc_path_info($params{'file_parent'});1320delete$params{'file_parent'};1321}1322}1323$href.="..";1324delete$params{'hash_parent'};1325delete$params{'hash_parent_base'};1326}elsif(defined$params{'hash_parent'}) {1327$href.= esc_path_info($params{'hash_parent'})."..";1328delete$params{'hash_parent'};1329}13301331$href.= esc_path_info($params{'hash_base'});1332if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1333$href.=":/".esc_path_info($params{'file_name'});1334delete$params{'file_name'};1335}1336delete$params{'hash'};1337delete$params{'hash_base'};1338}elsif(defined$params{'hash'}) {1339$href.= esc_path_info($params{'hash'});1340delete$params{'hash'};1341}13421343# If the action was a snapshot, we can absorb the1344# snapshot_format parameter too1345if($is_snapshot) {1346my$fmt=$params{'snapshot_format'};1347# snapshot_format should always be defined when href()1348# is called, but just in case some code forgets, we1349# fall back to the default1350$fmt||=$snapshot_fmts[0];1351$href.=$known_snapshot_formats{$fmt}{'suffix'};1352delete$params{'snapshot_format'};1353}1354}13551356# now encode the parameters explicitly1357my@result= ();1358for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1359my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1360if(defined$params{$name}) {1361if(ref($params{$name})eq"ARRAY") {1362foreachmy$par(@{$params{$name}}) {1363push@result,$symbol."=". esc_param($par);1364}1365}else{1366push@result,$symbol."=". esc_param($params{$name});1367}1368}1369}1370$href.="?".join(';',@result)ifscalar@result;13711372# final transformation: trailing spaces must be escaped (URI-encoded)1373$href=~s/(\s+)$/CGI::escape($1)/e;13741375if($params{-anchor}) {1376$href.="#".esc_param($params{-anchor});1377}13781379return$href;1380}138113821383## ======================================================================1384## validation, quoting/unquoting and escaping13851386sub validate_action {1387my$input=shift||returnundef;1388returnundefunlessexists$actions{$input};1389return$input;1390}13911392sub validate_project {1393my$input=shift||returnundef;1394if(!validate_pathname($input) ||1395!(-d "$projectroot/$input") ||1396!check_export_ok("$projectroot/$input") ||1397($strict_export&& !project_in_list($input))) {1398returnundef;1399}else{1400return$input;1401}1402}14031404sub validate_pathname {1405my$input=shift||returnundef;14061407# no '.' or '..' as elements of path, i.e. no '.' nor '..'1408# at the beginning, at the end, and between slashes.1409# also this catches doubled slashes1410if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1411returnundef;1412}1413# no null characters1414if($input=~m!\0!) {1415returnundef;1416}1417return$input;1418}14191420sub validate_refname {1421my$input=shift||returnundef;14221423# textual hashes are O.K.1424if($input=~m/^[0-9a-fA-F]{40}$/) {1425return$input;1426}1427# it must be correct pathname1428$input= validate_pathname($input)1429orreturnundef;1430# restrictions on ref name according to git-check-ref-format1431if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1432returnundef;1433}1434return$input;1435}14361437# decode sequences of octets in utf8 into Perl's internal form,1438# which is utf-8 with utf8 flag set if needed. gitweb writes out1439# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1440sub to_utf8 {1441my$str=shift;1442returnundefunlessdefined$str;1443if(utf8::valid($str)) {1444 utf8::decode($str);1445return$str;1446}else{1447return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1448}1449}14501451# quote unsafe chars, but keep the slash, even when it's not1452# correct, but quoted slashes look too horrible in bookmarks1453sub esc_param {1454my$str=shift;1455returnundefunlessdefined$str;1456$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1457$str=~s/ /\+/g;1458return$str;1459}14601461# the quoting rules for path_info fragment are slightly different1462sub esc_path_info {1463my$str=shift;1464returnundefunlessdefined$str;14651466# path_info doesn't treat '+' as space (specially), but '?' must be escaped1467$str=~s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;14681469return$str;1470}14711472# quote unsafe chars in whole URL, so some characters cannot be quoted1473sub esc_url {1474my$str=shift;1475returnundefunlessdefined$str;1476$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1477$str=~s/ /\+/g;1478return$str;1479}14801481# quote unsafe characters in HTML attributes1482sub esc_attr {14831484# for XHTML conformance escaping '"' to '"' is not enough1485return esc_html(@_);1486}14871488# replace invalid utf8 character with SUBSTITUTION sequence1489sub esc_html {1490my$str=shift;1491my%opts=@_;14921493returnundefunlessdefined$str;14941495$str= to_utf8($str);1496$str=$cgi->escapeHTML($str);1497if($opts{'-nbsp'}) {1498$str=~s/ / /g;1499}1500$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1501return$str;1502}15031504# quote control characters and escape filename to HTML1505sub esc_path {1506my$str=shift;1507my%opts=@_;15081509returnundefunlessdefined$str;15101511$str= to_utf8($str);1512$str=$cgi->escapeHTML($str);1513if($opts{'-nbsp'}) {1514$str=~s/ / /g;1515}1516$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1517return$str;1518}15191520# Make control characters "printable", using character escape codes (CEC)1521sub quot_cec {1522my$cntrl=shift;1523my%opts=@_;1524my%es= (# character escape codes, aka escape sequences1525"\t"=>'\t',# tab (HT)1526"\n"=>'\n',# line feed (LF)1527"\r"=>'\r',# carrige return (CR)1528"\f"=>'\f',# form feed (FF)1529"\b"=>'\b',# backspace (BS)1530"\a"=>'\a',# alarm (bell) (BEL)1531"\e"=>'\e',# escape (ESC)1532"\013"=>'\v',# vertical tab (VT)1533"\000"=>'\0',# nul character (NUL)1534);1535my$chr= ( (exists$es{$cntrl})1536?$es{$cntrl}1537:sprintf('\%2x',ord($cntrl)) );1538if($opts{-nohtml}) {1539return$chr;1540}else{1541return"<span class=\"cntrl\">$chr</span>";1542}1543}15441545# Alternatively use unicode control pictures codepoints,1546# Unicode "printable representation" (PR)1547sub quot_upr {1548my$cntrl=shift;1549my%opts=@_;15501551my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1552if($opts{-nohtml}) {1553return$chr;1554}else{1555return"<span class=\"cntrl\">$chr</span>";1556}1557}15581559# git may return quoted and escaped filenames1560sub unquote {1561my$str=shift;15621563sub unq {1564my$seq=shift;1565my%es= (# character escape codes, aka escape sequences1566't'=>"\t",# tab (HT, TAB)1567'n'=>"\n",# newline (NL)1568'r'=>"\r",# return (CR)1569'f'=>"\f",# form feed (FF)1570'b'=>"\b",# backspace (BS)1571'a'=>"\a",# alarm (bell) (BEL)1572'e'=>"\e",# escape (ESC)1573'v'=>"\013",# vertical tab (VT)1574);15751576if($seq=~m/^[0-7]{1,3}$/) {1577# octal char sequence1578returnchr(oct($seq));1579}elsif(exists$es{$seq}) {1580# C escape sequence, aka character escape code1581return$es{$seq};1582}1583# quoted ordinary character1584return$seq;1585}15861587if($str=~m/^"(.*)"$/) {1588# needs unquoting1589$str=$1;1590$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1591}1592return$str;1593}15941595# escape tabs (convert tabs to spaces)1596sub untabify {1597my$line=shift;15981599while((my$pos=index($line,"\t")) != -1) {1600if(my$count= (8- ($pos%8))) {1601my$spaces=' ' x $count;1602$line=~s/\t/$spaces/;1603}1604}16051606return$line;1607}16081609sub project_in_list {1610my$project=shift;1611my@list= git_get_projects_list();1612return@list&&scalar(grep{$_->{'path'}eq$project}@list);1613}16141615## ----------------------------------------------------------------------1616## HTML aware string manipulation16171618# Try to chop given string on a word boundary between position1619# $len and $len+$add_len. If there is no word boundary there,1620# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1621# (marking chopped part) would be longer than given string.1622sub chop_str {1623my$str=shift;1624my$len=shift;1625my$add_len=shift||10;1626my$where=shift||'right';# 'left' | 'center' | 'right'16271628# Make sure perl knows it is utf8 encoded so we don't1629# cut in the middle of a utf8 multibyte char.1630$str= to_utf8($str);16311632# allow only $len chars, but don't cut a word if it would fit in $add_len1633# if it doesn't fit, cut it if it's still longer than the dots we would add1634# remove chopped character entities entirely16351636# when chopping in the middle, distribute $len into left and right part1637# return early if chopping wouldn't make string shorter1638if($whereeq'center') {1639return$strif($len+5>=length($str));# filler is length 51640$len=int($len/2);1641}else{1642return$strif($len+4>=length($str));# filler is length 41643}16441645# regexps: ending and beginning with word part up to $add_len1646my$endre=qr/.{$len}\w{0,$add_len}/;1647my$begre=qr/\w{0,$add_len}.{$len}/;16481649if($whereeq'left') {1650$str=~m/^(.*?)($begre)$/;1651my($lead,$body) = ($1,$2);1652if(length($lead) >4) {1653$lead=" ...";1654}1655return"$lead$body";16561657}elsif($whereeq'center') {1658$str=~m/^($endre)(.*)$/;1659my($left,$str) = ($1,$2);1660$str=~m/^(.*?)($begre)$/;1661my($mid,$right) = ($1,$2);1662if(length($mid) >5) {1663$mid=" ... ";1664}1665return"$left$mid$right";16661667}else{1668$str=~m/^($endre)(.*)$/;1669my$body=$1;1670my$tail=$2;1671if(length($tail) >4) {1672$tail="... ";1673}1674return"$body$tail";1675}1676}16771678# takes the same arguments as chop_str, but also wraps a <span> around the1679# result with a title attribute if it does get chopped. Additionally, the1680# string is HTML-escaped.1681sub chop_and_escape_str {1682my($str) =@_;16831684my$chopped= chop_str(@_);1685if($choppedeq$str) {1686return esc_html($chopped);1687}else{1688$str=~s/[[:cntrl:]]/?/g;1689return$cgi->span({-title=>$str}, esc_html($chopped));1690}1691}16921693## ----------------------------------------------------------------------1694## functions returning short strings16951696# CSS class for given age value (in seconds)1697sub age_class {1698my$age=shift;16991700if(!defined$age) {1701return"noage";1702}elsif($age<60*60*2) {1703return"age0";1704}elsif($age<60*60*24*2) {1705return"age1";1706}else{1707return"age2";1708}1709}17101711# convert age in seconds to "nn units ago" string1712sub age_string {1713my$age=shift;1714my$age_str;17151716if($age>60*60*24*365*2) {1717$age_str= (int$age/60/60/24/365);1718$age_str.=" years ago";1719}elsif($age>60*60*24*(365/12)*2) {1720$age_str=int$age/60/60/24/(365/12);1721$age_str.=" months ago";1722}elsif($age>60*60*24*7*2) {1723$age_str=int$age/60/60/24/7;1724$age_str.=" weeks ago";1725}elsif($age>60*60*24*2) {1726$age_str=int$age/60/60/24;1727$age_str.=" days ago";1728}elsif($age>60*60*2) {1729$age_str=int$age/60/60;1730$age_str.=" hours ago";1731}elsif($age>60*2) {1732$age_str=int$age/60;1733$age_str.=" min ago";1734}elsif($age>2) {1735$age_str=int$age;1736$age_str.=" sec ago";1737}else{1738$age_str.=" right now";1739}1740return$age_str;1741}17421743useconstant{1744 S_IFINVALID =>0030000,1745 S_IFGITLINK =>0160000,1746};17471748# submodule/subproject, a commit object reference1749sub S_ISGITLINK {1750my$mode=shift;17511752return(($mode& S_IFMT) == S_IFGITLINK)1753}17541755# convert file mode in octal to symbolic file mode string1756sub mode_str {1757my$mode=oct shift;17581759if(S_ISGITLINK($mode)) {1760return'm---------';1761}elsif(S_ISDIR($mode& S_IFMT)) {1762return'drwxr-xr-x';1763}elsif(S_ISLNK($mode)) {1764return'lrwxrwxrwx';1765}elsif(S_ISREG($mode)) {1766# git cares only about the executable bit1767if($mode& S_IXUSR) {1768return'-rwxr-xr-x';1769}else{1770return'-rw-r--r--';1771};1772}else{1773return'----------';1774}1775}17761777# convert file mode in octal to file type string1778sub file_type {1779my$mode=shift;17801781if($mode!~m/^[0-7]+$/) {1782return$mode;1783}else{1784$mode=oct$mode;1785}17861787if(S_ISGITLINK($mode)) {1788return"submodule";1789}elsif(S_ISDIR($mode& S_IFMT)) {1790return"directory";1791}elsif(S_ISLNK($mode)) {1792return"symlink";1793}elsif(S_ISREG($mode)) {1794return"file";1795}else{1796return"unknown";1797}1798}17991800# convert file mode in octal to file type description string1801sub file_type_long {1802my$mode=shift;18031804if($mode!~m/^[0-7]+$/) {1805return$mode;1806}else{1807$mode=oct$mode;1808}18091810if(S_ISGITLINK($mode)) {1811return"submodule";1812}elsif(S_ISDIR($mode& S_IFMT)) {1813return"directory";1814}elsif(S_ISLNK($mode)) {1815return"symlink";1816}elsif(S_ISREG($mode)) {1817if($mode& S_IXUSR) {1818return"executable";1819}else{1820return"file";1821};1822}else{1823return"unknown";1824}1825}182618271828## ----------------------------------------------------------------------1829## functions returning short HTML fragments, or transforming HTML fragments1830## which don't belong to other sections18311832# format line of commit message.1833sub format_log_line_html {1834my$line=shift;18351836$line= esc_html($line, -nbsp=>1);1837$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1838$cgi->a({-href => href(action=>"object", hash=>$1),1839-class=>"text"},$1);1840}eg;18411842return$line;1843}18441845# format marker of refs pointing to given object18461847# the destination action is chosen based on object type and current context:1848# - for annotated tags, we choose the tag view unless it's the current view1849# already, in which case we go to shortlog view1850# - for other refs, we keep the current view if we're in history, shortlog or1851# log view, and select shortlog otherwise1852sub format_ref_marker {1853my($refs,$id) =@_;1854my$markers='';18551856if(defined$refs->{$id}) {1857foreachmy$ref(@{$refs->{$id}}) {1858# this code exploits the fact that non-lightweight tags are the1859# only indirect objects, and that they are the only objects for which1860# we want to use tag instead of shortlog as action1861my($type,$name) =qw();1862my$indirect= ($ref=~s/\^\{\}$//);1863# e.g. tags/v2.6.11 or heads/next1864if($ref=~m!^(.*?)s?/(.*)$!) {1865$type=$1;1866$name=$2;1867}else{1868$type="ref";1869$name=$ref;1870}18711872my$class=$type;1873$class.=" indirect"if$indirect;18741875my$dest_action="shortlog";18761877if($indirect) {1878$dest_action="tag"unless$actioneq"tag";1879}elsif($action=~/^(history|(short)?log)$/) {1880$dest_action=$action;1881}18821883my$dest="";1884$dest.="refs/"unless$ref=~ m!^refs/!;1885$dest.=$ref;18861887my$link=$cgi->a({1888-href => href(1889 action=>$dest_action,1890 hash=>$dest1891)},$name);18921893$markers.=" <span class=\"".esc_attr($class)."\"title=\"".esc_attr($ref)."\">".1894$link."</span>";1895}1896}18971898if($markers) {1899return' <span class="refs">'.$markers.'</span>';1900}else{1901return"";1902}1903}19041905# format, perhaps shortened and with markers, title line1906sub format_subject_html {1907my($long,$short,$href,$extra) =@_;1908$extra=''unlessdefined($extra);19091910if(length($short) <length($long)) {1911$long=~s/[[:cntrl:]]/?/g;1912return$cgi->a({-href =>$href, -class=>"list subject",1913-title => to_utf8($long)},1914 esc_html($short)) .$extra;1915}else{1916return$cgi->a({-href =>$href, -class=>"list subject"},1917 esc_html($long)) .$extra;1918}1919}19201921# Rather than recomputing the url for an email multiple times, we cache it1922# after the first hit. This gives a visible benefit in views where the avatar1923# for the same email is used repeatedly (e.g. shortlog).1924# The cache is shared by all avatar engines (currently gravatar only), which1925# are free to use it as preferred. Since only one avatar engine is used for any1926# given page, there's no risk for cache conflicts.1927our%avatar_cache= ();19281929# Compute the picon url for a given email, by using the picon search service over at1930# http://www.cs.indiana.edu/picons/search.html1931sub picon_url {1932my$email=lc shift;1933if(!$avatar_cache{$email}) {1934my($user,$domain) =split('@',$email);1935$avatar_cache{$email} =1936"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1937"$domain/$user/".1938"users+domains+unknown/up/single";1939}1940return$avatar_cache{$email};1941}19421943# Compute the gravatar url for a given email, if it's not in the cache already.1944# Gravatar stores only the part of the URL before the size, since that's the1945# one computationally more expensive. This also allows reuse of the cache for1946# different sizes (for this particular engine).1947sub gravatar_url {1948my$email=lc shift;1949my$size=shift;1950$avatar_cache{$email} ||=1951"http://www.gravatar.com/avatar/".1952 Digest::MD5::md5_hex($email) ."?s=";1953return$avatar_cache{$email} .$size;1954}19551956# Insert an avatar for the given $email at the given $size if the feature1957# is enabled.1958sub git_get_avatar {1959my($email,%opts) =@_;1960my$pre_white= ($opts{-pad_before} ?" ":"");1961my$post_white= ($opts{-pad_after} ?" ":"");1962$opts{-size} ||='default';1963my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1964my$url="";1965if($git_avatareq'gravatar') {1966$url= gravatar_url($email,$size);1967}elsif($git_avatareq'picon') {1968$url= picon_url($email);1969}1970# Other providers can be added by extending the if chain, defining $url1971# as needed. If no variant puts something in $url, we assume avatars1972# are completely disabled/unavailable.1973if($url) {1974return$pre_white.1975"<img width=\"$size\"".1976"class=\"avatar\"".1977"src=\"".esc_url($url)."\"".1978"alt=\"\"".1979"/>".$post_white;1980}else{1981return"";1982}1983}19841985sub format_search_author {1986my($author,$searchtype,$displaytext) =@_;1987my$have_search= gitweb_check_feature('search');19881989if($have_search) {1990my$performed="";1991if($searchtypeeq'author') {1992$performed="authored";1993}elsif($searchtypeeq'committer') {1994$performed="committed";1995}19961997return$cgi->a({-href => href(action=>"search", hash=>$hash,1998 searchtext=>$author,1999 searchtype=>$searchtype),class=>"list",2000 title=>"Search for commits$performedby$author"},2001$displaytext);20022003}else{2004return$displaytext;2005}2006}20072008# format the author name of the given commit with the given tag2009# the author name is chopped and escaped according to the other2010# optional parameters (see chop_str).2011sub format_author_html {2012my$tag=shift;2013my$co=shift;2014my$author= chop_and_escape_str($co->{'author_name'},@_);2015return"<$tagclass=\"author\">".2016 format_search_author($co->{'author_name'},"author",2017 git_get_avatar($co->{'author_email'}, -pad_after =>1) .2018$author) .2019"</$tag>";2020}20212022# format git diff header line, i.e. "diff --(git|combined|cc) ..."2023sub format_git_diff_header_line {2024my$line=shift;2025my$diffinfo=shift;2026my($from,$to) =@_;20272028if($diffinfo->{'nparents'}) {2029# combined diff2030$line=~s!^(diff (.*?) )"?.*$!$1!;2031if($to->{'href'}) {2032$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2033 esc_path($to->{'file'}));2034}else{# file was deleted (no href)2035$line.= esc_path($to->{'file'});2036}2037}else{2038# "ordinary" diff2039$line=~s!^(diff (.*?) )"?a/.*$!$1!;2040if($from->{'href'}) {2041$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},2042'a/'. esc_path($from->{'file'}));2043}else{# file was added (no href)2044$line.='a/'. esc_path($from->{'file'});2045}2046$line.=' ';2047if($to->{'href'}) {2048$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2049'b/'. esc_path($to->{'file'}));2050}else{# file was deleted2051$line.='b/'. esc_path($to->{'file'});2052}2053}20542055return"<div class=\"diff header\">$line</div>\n";2056}20572058# format extended diff header line, before patch itself2059sub format_extended_diff_header_line {2060my$line=shift;2061my$diffinfo=shift;2062my($from,$to) =@_;20632064# match <path>2065if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {2066$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},2067 esc_path($from->{'file'}));2068}2069if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {2070$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},2071 esc_path($to->{'file'}));2072}2073# match single <mode>2074if($line=~m/\s(\d{6})$/) {2075$line.='<span class="info"> ('.2076 file_type_long($1) .2077')</span>';2078}2079# match <hash>2080if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {2081# can match only for combined diff2082$line='index ';2083for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2084if($from->{'href'}[$i]) {2085$line.=$cgi->a({-href=>$from->{'href'}[$i],2086-class=>"hash"},2087substr($diffinfo->{'from_id'}[$i],0,7));2088}else{2089$line.='0' x 7;2090}2091# separator2092$line.=','if($i<$diffinfo->{'nparents'} -1);2093}2094$line.='..';2095if($to->{'href'}) {2096$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2097substr($diffinfo->{'to_id'},0,7));2098}else{2099$line.='0' x 7;2100}21012102}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {2103# can match only for ordinary diff2104my($from_link,$to_link);2105if($from->{'href'}) {2106$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},2107substr($diffinfo->{'from_id'},0,7));2108}else{2109$from_link='0' x 7;2110}2111if($to->{'href'}) {2112$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2113substr($diffinfo->{'to_id'},0,7));2114}else{2115$to_link='0' x 7;2116}2117my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});2118$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;2119}21202121return$line."<br/>\n";2122}21232124# format from-file/to-file diff header2125sub format_diff_from_to_header {2126my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2127my$line;2128my$result='';21292130$line=$from_line;2131#assert($line =~ m/^---/) if DEBUG;2132# no extra formatting for "^--- /dev/null"2133if(!$diffinfo->{'nparents'}) {2134# ordinary (single parent) diff2135if($line=~m!^--- "?a/!) {2136if($from->{'href'}) {2137$line='--- a/'.2138$cgi->a({-href=>$from->{'href'}, -class=>"path"},2139 esc_path($from->{'file'}));2140}else{2141$line='--- a/'.2142 esc_path($from->{'file'});2143}2144}2145$result.= qq!<div class="diff from_file">$line</div>\n!;21462147}else{2148# combined diff (merge commit)2149for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2150if($from->{'href'}[$i]) {2151$line='--- '.2152$cgi->a({-href=>href(action=>"blobdiff",2153 hash_parent=>$diffinfo->{'from_id'}[$i],2154 hash_parent_base=>$parents[$i],2155 file_parent=>$from->{'file'}[$i],2156 hash=>$diffinfo->{'to_id'},2157 hash_base=>$hash,2158 file_name=>$to->{'file'}),2159-class=>"path",2160-title=>"diff". ($i+1)},2161$i+1) .2162'/'.2163$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2164 esc_path($from->{'file'}[$i]));2165}else{2166$line='--- /dev/null';2167}2168$result.= qq!<div class="diff from_file">$line</div>\n!;2169}2170}21712172$line=$to_line;2173#assert($line =~ m/^\+\+\+/) if DEBUG;2174# no extra formatting for "^+++ /dev/null"2175if($line=~m!^\+\+\+ "?b/!) {2176if($to->{'href'}) {2177$line='+++ b/'.2178$cgi->a({-href=>$to->{'href'}, -class=>"path"},2179 esc_path($to->{'file'}));2180}else{2181$line='+++ b/'.2182 esc_path($to->{'file'});2183}2184}2185$result.= qq!<div class="diff to_file">$line</div>\n!;21862187return$result;2188}21892190# create note for patch simplified by combined diff2191sub format_diff_cc_simplified {2192my($diffinfo,@parents) =@_;2193my$result='';21942195$result.="<div class=\"diff header\">".2196"diff --cc ";2197if(!is_deleted($diffinfo)) {2198$result.=$cgi->a({-href => href(action=>"blob",2199 hash_base=>$hash,2200 hash=>$diffinfo->{'to_id'},2201 file_name=>$diffinfo->{'to_file'}),2202-class=>"path"},2203 esc_path($diffinfo->{'to_file'}));2204}else{2205$result.= esc_path($diffinfo->{'to_file'});2206}2207$result.="</div>\n".# class="diff header"2208"<div class=\"diff nodifferences\">".2209"Simple merge".2210"</div>\n";# class="diff nodifferences"22112212return$result;2213}22142215# format patch (diff) line (not to be used for diff headers)2216sub format_diff_line {2217my$line=shift;2218my($from,$to) =@_;2219my$diff_class="";22202221chomp$line;22222223if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2224# combined diff2225my$prefix=substr($line,0,scalar@{$from->{'href'}});2226if($line=~m/^\@{3}/) {2227$diff_class=" chunk_header";2228}elsif($line=~m/^\\/) {2229$diff_class=" incomplete";2230}elsif($prefix=~tr/+/+/) {2231$diff_class=" add";2232}elsif($prefix=~tr/-/-/) {2233$diff_class=" rem";2234}2235}else{2236# assume ordinary diff2237my$char=substr($line,0,1);2238if($chareq'+') {2239$diff_class=" add";2240}elsif($chareq'-') {2241$diff_class=" rem";2242}elsif($chareq'@') {2243$diff_class=" chunk_header";2244}elsif($chareq"\\") {2245$diff_class=" incomplete";2246}2247}2248$line= untabify($line);2249if($from&&$to&&$line=~m/^\@{2} /) {2250my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2251$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;22522253$from_lines=0unlessdefined$from_lines;2254$to_lines=0unlessdefined$to_lines;22552256if($from->{'href'}) {2257$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2258-class=>"list"},$from_text);2259}2260if($to->{'href'}) {2261$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2262-class=>"list"},$to_text);2263}2264$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2265"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2266return"<div class=\"diff$diff_class\">$line</div>\n";2267}elsif($from&&$to&&$line=~m/^\@{3}/) {2268my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2269my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);22702271@from_text=split(' ',$ranges);2272for(my$i=0;$i<@from_text; ++$i) {2273($from_start[$i],$from_nlines[$i]) =2274(split(',',substr($from_text[$i],1)),0);2275}22762277$to_text=pop@from_text;2278$to_start=pop@from_start;2279$to_nlines=pop@from_nlines;22802281$line="<span class=\"chunk_info\">$prefix";2282for(my$i=0;$i<@from_text; ++$i) {2283if($from->{'href'}[$i]) {2284$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2285-class=>"list"},$from_text[$i]);2286}else{2287$line.=$from_text[$i];2288}2289$line.=" ";2290}2291if($to->{'href'}) {2292$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2293-class=>"list"},$to_text);2294}else{2295$line.=$to_text;2296}2297$line.="$prefix</span>".2298"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2299return"<div class=\"diff$diff_class\">$line</div>\n";2300}2301return"<div class=\"diff$diff_class\">". esc_html($line, -nbsp=>1) ."</div>\n";2302}23032304# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2305# linked. Pass the hash of the tree/commit to snapshot.2306sub format_snapshot_links {2307my($hash) =@_;2308my$num_fmts=@snapshot_fmts;2309if($num_fmts>1) {2310# A parenthesized list of links bearing format names.2311# e.g. "snapshot (_tar.gz_ _zip_)"2312return"snapshot (".join(' ',map2313$cgi->a({2314-href => href(2315 action=>"snapshot",2316 hash=>$hash,2317 snapshot_format=>$_2318)2319},$known_snapshot_formats{$_}{'display'})2320,@snapshot_fmts) .")";2321}elsif($num_fmts==1) {2322# A single "snapshot" link whose tooltip bears the format name.2323# i.e. "_snapshot_"2324my($fmt) =@snapshot_fmts;2325return2326$cgi->a({2327-href => href(2328 action=>"snapshot",2329 hash=>$hash,2330 snapshot_format=>$fmt2331),2332-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2333},"snapshot");2334}else{# $num_fmts == 02335returnundef;2336}2337}23382339## ......................................................................2340## functions returning values to be passed, perhaps after some2341## transformation, to other functions; e.g. returning arguments to href()23422343# returns hash to be passed to href to generate gitweb URL2344# in -title key it returns description of link2345sub get_feed_info {2346my$format=shift||'Atom';2347my%res= (action =>lc($format));23482349# feed links are possible only for project views2350return unless(defined$project);2351# some views should link to OPML, or to generic project feed,2352# or don't have specific feed yet (so they should use generic)2353return if($action=~/^(?:tags|heads|forks|tag|search)$/x);23542355my$branch;2356# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2357# from tag links; this also makes possible to detect branch links2358if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2359(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2360$branch=$1;2361}2362# find log type for feed description (title)2363my$type='log';2364if(defined$file_name) {2365$type="history of$file_name";2366$type.="/"if($actioneq'tree');2367$type.=" on '$branch'"if(defined$branch);2368}else{2369$type="log of$branch"if(defined$branch);2370}23712372$res{-title} =$type;2373$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2374$res{'file_name'} =$file_name;23752376return%res;2377}23782379## ----------------------------------------------------------------------2380## git utility subroutines, invoking git commands23812382# returns path to the core git executable and the --git-dir parameter as list2383sub git_cmd {2384$number_of_git_cmds++;2385return$GIT,'--git-dir='.$git_dir;2386}23872388# quote the given arguments for passing them to the shell2389# quote_command("command", "arg 1", "arg with ' and ! characters")2390# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2391# Try to avoid using this function wherever possible.2392sub quote_command {2393returnjoin(' ',2394map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2395}23962397# get HEAD ref of given project as hash2398sub git_get_head_hash {2399return git_get_full_hash(shift,'HEAD');2400}24012402sub git_get_full_hash {2403return git_get_hash(@_);2404}24052406sub git_get_short_hash {2407return git_get_hash(@_,'--short=7');2408}24092410sub git_get_hash {2411my($project,$hash,@options) =@_;2412my$o_git_dir=$git_dir;2413my$retval=undef;2414$git_dir="$projectroot/$project";2415if(open my$fd,'-|', git_cmd(),'rev-parse',2416'--verify','-q',@options,$hash) {2417$retval= <$fd>;2418chomp$retvalifdefined$retval;2419close$fd;2420}2421if(defined$o_git_dir) {2422$git_dir=$o_git_dir;2423}2424return$retval;2425}24262427# get type of given object2428sub git_get_type {2429my$hash=shift;24302431open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2432my$type= <$fd>;2433close$fdorreturn;2434chomp$type;2435return$type;2436}24372438# repository configuration2439our$config_file='';2440our%config;24412442# store multiple values for single key as anonymous array reference2443# single values stored directly in the hash, not as [ <value> ]2444sub hash_set_multi {2445my($hash,$key,$value) =@_;24462447if(!exists$hash->{$key}) {2448$hash->{$key} =$value;2449}elsif(!ref$hash->{$key}) {2450$hash->{$key} = [$hash->{$key},$value];2451}else{2452push@{$hash->{$key}},$value;2453}2454}24552456# return hash of git project configuration2457# optionally limited to some section, e.g. 'gitweb'2458sub git_parse_project_config {2459my$section_regexp=shift;2460my%config;24612462local$/="\0";24632464open my$fh,"-|", git_cmd(),"config",'-z','-l',2465orreturn;24662467while(my$keyval= <$fh>) {2468chomp$keyval;2469my($key,$value) =split(/\n/,$keyval,2);24702471 hash_set_multi(\%config,$key,$value)2472if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2473}2474close$fh;24752476return%config;2477}24782479# convert config value to boolean: 'true' or 'false'2480# no value, number > 0, 'true' and 'yes' values are true2481# rest of values are treated as false (never as error)2482sub config_to_bool {2483my$val=shift;24842485return1if!defined$val;# section.key24862487# strip leading and trailing whitespace2488$val=~s/^\s+//;2489$val=~s/\s+$//;24902491return(($val=~/^\d+$/&&$val) ||# section.key = 12492($val=~/^(?:true|yes)$/i));# section.key = true2493}24942495# convert config value to simple decimal number2496# an optional value suffix of 'k', 'm', or 'g' will cause the value2497# to be multiplied by 1024, 1048576, or 10737418242498sub config_to_int {2499my$val=shift;25002501# strip leading and trailing whitespace2502$val=~s/^\s+//;2503$val=~s/\s+$//;25042505if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2506$unit=lc($unit);2507# unknown unit is treated as 12508return$num* ($uniteq'g'?1073741824:2509$uniteq'm'?1048576:2510$uniteq'k'?1024:1);2511}2512return$val;2513}25142515# convert config value to array reference, if needed2516sub config_to_multi {2517my$val=shift;25182519returnref($val) ?$val: (defined($val) ? [$val] : []);2520}25212522sub git_get_project_config {2523my($key,$type) =@_;25242525return unlessdefined$git_dir;25262527# key sanity check2528return unless($key);2529$key=~s/^gitweb\.//;2530return if($key=~m/\W/);25312532# type sanity check2533if(defined$type) {2534$type=~s/^--//;2535$type=undef2536unless($typeeq'bool'||$typeeq'int');2537}25382539# get config2540if(!defined$config_file||2541$config_filene"$git_dir/config") {2542%config= git_parse_project_config('gitweb');2543$config_file="$git_dir/config";2544}25452546# check if config variable (key) exists2547return unlessexists$config{"gitweb.$key"};25482549# ensure given type2550if(!defined$type) {2551return$config{"gitweb.$key"};2552}elsif($typeeq'bool') {2553# backward compatibility: 'git config --bool' returns true/false2554return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2555}elsif($typeeq'int') {2556return config_to_int($config{"gitweb.$key"});2557}2558return$config{"gitweb.$key"};2559}25602561# get hash of given path at given ref2562sub git_get_hash_by_path {2563my$base=shift;2564my$path=shift||returnundef;2565my$type=shift;25662567$path=~ s,/+$,,;25682569open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2570or die_error(500,"Open git-ls-tree failed");2571my$line= <$fd>;2572close$fdorreturnundef;25732574if(!defined$line) {2575# there is no tree or hash given by $path at $base2576returnundef;2577}25782579#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2580$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2581if(defined$type&&$typene$2) {2582# type doesn't match2583returnundef;2584}2585return$3;2586}25872588# get path of entry with given hash at given tree-ish (ref)2589# used to get 'from' filename for combined diff (merge commit) for renames2590sub git_get_path_by_hash {2591my$base=shift||return;2592my$hash=shift||return;25932594local$/="\0";25952596open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2597orreturnundef;2598while(my$line= <$fd>) {2599chomp$line;26002601#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2602#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2603if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2604close$fd;2605return$1;2606}2607}2608close$fd;2609returnundef;2610}26112612## ......................................................................2613## git utility functions, directly accessing git repository26142615# get the value of config variable either from file named as the variable2616# itself in the repository ($GIT_DIR/$name file), or from gitweb.$name2617# configuration variable in the repository config file.2618sub git_get_file_or_project_config {2619my($path,$name) =@_;26202621$git_dir="$projectroot/$path";2622open my$fd,'<',"$git_dir/$name"2623orreturn git_get_project_config($name);2624my$conf= <$fd>;2625close$fd;2626if(defined$conf) {2627chomp$conf;2628}2629return$conf;2630}26312632sub git_get_project_description {2633my$path=shift;2634return git_get_file_or_project_config($path,'description');2635}26362637sub git_get_project_category {2638my$path=shift;2639return git_get_file_or_project_config($path,'category');2640}264126422643# supported formats:2644# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2645# - if its contents is a number, use it as tag weight,2646# - otherwise add a tag with weight 12647# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2648# the same value multiple times increases tag weight2649# * `gitweb.ctag' multi-valued repo config variable2650sub git_get_project_ctags {2651my$project=shift;2652my$ctags= {};26532654$git_dir="$projectroot/$project";2655if(opendir my$dh,"$git_dir/ctags") {2656my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2657foreachmy$tagfile(@files) {2658open my$ct,'<',$tagfile2659ornext;2660my$val= <$ct>;2661chomp$valif$val;2662close$ct;26632664(my$ctag=$tagfile) =~ s#.*/##;2665if($val=~/^\d+$/) {2666$ctags->{$ctag} =$val;2667}else{2668$ctags->{$ctag} =1;2669}2670}2671closedir$dh;26722673}elsif(open my$fh,'<',"$git_dir/ctags") {2674while(my$line= <$fh>) {2675chomp$line;2676$ctags->{$line}++if$line;2677}2678close$fh;26792680}else{2681my$taglist= config_to_multi(git_get_project_config('ctag'));2682foreachmy$tag(@$taglist) {2683$ctags->{$tag}++;2684}2685}26862687return$ctags;2688}26892690# return hash, where keys are content tags ('ctags'),2691# and values are sum of weights of given tag in every project2692sub git_gather_all_ctags {2693my$projects=shift;2694my$ctags= {};26952696foreachmy$p(@$projects) {2697foreachmy$ct(keys%{$p->{'ctags'}}) {2698$ctags->{$ct} +=$p->{'ctags'}->{$ct};2699}2700}27012702return$ctags;2703}27042705sub git_populate_project_tagcloud {2706my$ctags=shift;27072708# First, merge different-cased tags; tags vote on casing2709my%ctags_lc;2710foreach(keys%$ctags) {2711$ctags_lc{lc$_}->{count} +=$ctags->{$_};2712if(not$ctags_lc{lc$_}->{topcount}2713or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2714$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2715$ctags_lc{lc$_}->{topname} =$_;2716}2717}27182719my$cloud;2720my$matched=$cgi->param('by_tag');2721if(eval{require HTML::TagCloud;1; }) {2722$cloud= HTML::TagCloud->new;2723foreachmy$ctag(sort keys%ctags_lc) {2724# Pad the title with spaces so that the cloud looks2725# less crammed.2726my$title= esc_html($ctags_lc{$ctag}->{topname});2727$title=~s/ / /g;2728$title=~s/^/ /g;2729$title=~s/$/ /g;2730if(defined$matched&&$matchedeq$ctag) {2731$title=qq(<span class="match">$title</span>);2732}2733$cloud->add($title, href(project=>undef, ctag=>$ctag),2734$ctags_lc{$ctag}->{count});2735}2736}else{2737$cloud= {};2738foreachmy$ctag(keys%ctags_lc) {2739my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2740if(defined$matched&&$matchedeq$ctag) {2741$title=qq(<span class="match">$title</span>);2742}2743$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};2744$cloud->{$ctag}{ctag} =2745$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);2746}2747}2748return$cloud;2749}27502751sub git_show_project_tagcloud {2752my($cloud,$count) =@_;2753if(ref$cloudeq'HTML::TagCloud') {2754return$cloud->html_and_css($count);2755}else{2756my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;2757return2758'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.2759join(', ',map{2760$cloud->{$_}->{'ctag'}2761}splice(@tags,0,$count)) .2762'</div>';2763}2764}27652766sub git_get_project_url_list {2767my$path=shift;27682769$git_dir="$projectroot/$path";2770open my$fd,'<',"$git_dir/cloneurl"2771orreturnwantarray?2772@{ config_to_multi(git_get_project_config('url')) } :2773 config_to_multi(git_get_project_config('url'));2774my@git_project_url_list=map{chomp;$_} <$fd>;2775close$fd;27762777returnwantarray?@git_project_url_list: \@git_project_url_list;2778}27792780sub git_get_projects_list {2781my$filter=shift||'';2782my@list;27832784$filter=~s/\.git$//;27852786if(-d $projects_list) {2787# search in directory2788my$dir=$projects_list;2789# remove the trailing "/"2790$dir=~s!/+$!!;2791my$pfxlen=length("$projects_list");2792my$pfxdepth= ($projects_list=~tr!/!!);2793# when filtering, search only given subdirectory2794if($filter) {2795$dir.="/$filter";2796$dir=~s!/+$!!;2797}27982799 File::Find::find({2800 follow_fast =>1,# follow symbolic links2801 follow_skip =>2,# ignore duplicates2802 dangling_symlinks =>0,# ignore dangling symlinks, silently2803 wanted =>sub{2804# global variables2805our$project_maxdepth;2806our$projectroot;2807# skip project-list toplevel, if we get it.2808return if(m!^[/.]$!);2809# only directories can be git repositories2810return unless(-d $_);2811# don't traverse too deep (Find is super slow on os x)2812# $project_maxdepth excludes depth of $projectroot2813if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2814$File::Find::prune =1;2815return;2816}28172818my$path=substr($File::Find::name,$pfxlen+1);2819# we check related file in $projectroot2820if(check_export_ok("$projectroot/$path")) {2821push@list, { path =>$path};2822$File::Find::prune =1;2823}2824},2825},"$dir");28262827}elsif(-f $projects_list) {2828# read from file(url-encoded):2829# 'git%2Fgit.git Linus+Torvalds'2830# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2831# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2832open my$fd,'<',$projects_listorreturn;2833 PROJECT:2834while(my$line= <$fd>) {2835chomp$line;2836my($path,$owner) =split' ',$line;2837$path= unescape($path);2838$owner= unescape($owner);2839if(!defined$path) {2840next;2841}2842# if $filter is rpovided, check if $path begins with $filter2843if($filter&&$path!~m!^\Q$filter\E/!) {2844next;2845}2846if(check_export_ok("$projectroot/$path")) {2847my$pr= {2848 path =>$path,2849 owner => to_utf8($owner),2850};2851push@list,$pr;2852}2853}2854close$fd;2855}2856return@list;2857}28582859# written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)2860# as side effects it sets 'forks' field to list of forks for forked projects2861sub filter_forks_from_projects_list {2862my$projects=shift;28632864my%trie;# prefix tree of directories (path components)2865# generate trie out of those directories that might contain forks2866foreachmy$pr(@$projects) {2867my$path=$pr->{'path'};2868$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory2869next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'2870next unless($path);# skip '.git' repository: tests, git-instaweb2871next unless(-d $path);# containing directory exists2872$pr->{'forks'} = [];# there can be 0 or more forks of project28732874# add to trie2875my@dirs=split('/',$path);2876# walk the trie, until either runs out of components or out of trie2877my$ref= \%trie;2878while(scalar@dirs&&2879exists($ref->{$dirs[0]})) {2880$ref=$ref->{shift@dirs};2881}2882# create rest of trie structure from rest of components2883foreachmy$dir(@dirs) {2884$ref=$ref->{$dir} = {};2885}2886# create end marker, store $pr as a data2887$ref->{''} =$prif(!exists$ref->{''});2888}28892890# filter out forks, by finding shortest prefix match for paths2891my@filtered;2892 PROJECT:2893foreachmy$pr(@$projects) {2894# trie lookup2895my$ref= \%trie;2896 DIR:2897foreachmy$dir(split('/',$pr->{'path'})) {2898if(exists$ref->{''}) {2899# found [shortest] prefix, is a fork - skip it2900push@{$ref->{''}{'forks'}},$pr;2901next PROJECT;2902}2903if(!exists$ref->{$dir}) {2904# not in trie, cannot have prefix, not a fork2905push@filtered,$pr;2906next PROJECT;2907}2908# If the dir is there, we just walk one step down the trie.2909$ref=$ref->{$dir};2910}2911# we ran out of trie2912# (shouldn't happen: it's either no match, or end marker)2913push@filtered,$pr;2914}29152916return@filtered;2917}29182919# note: fill_project_list_info must be run first,2920# for 'descr_long' and 'ctags' to be filled2921sub search_projects_list {2922my($projlist,%opts) =@_;2923my$tagfilter=$opts{'tagfilter'};2924my$searchtext=$opts{'searchtext'};29252926return@$projlist2927unless($tagfilter||$searchtext);29282929my@projects;2930 PROJECT:2931foreachmy$pr(@$projlist) {29322933if($tagfilter) {2934next unlessref($pr->{'ctags'})eq'HASH';2935next unless2936grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};2937}29382939if($searchtext) {2940next unless2941$pr->{'path'} =~/$searchtext/||2942$pr->{'descr_long'} =~/$searchtext/;2943}29442945push@projects,$pr;2946}29472948return@projects;2949}29502951our$gitweb_project_owner=undef;2952sub git_get_project_list_from_file {29532954return if(defined$gitweb_project_owner);29552956$gitweb_project_owner= {};2957# read from file (url-encoded):2958# 'git%2Fgit.git Linus+Torvalds'2959# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2960# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2961if(-f $projects_list) {2962open(my$fd,'<',$projects_list);2963while(my$line= <$fd>) {2964chomp$line;2965my($pr,$ow) =split' ',$line;2966$pr= unescape($pr);2967$ow= unescape($ow);2968$gitweb_project_owner->{$pr} = to_utf8($ow);2969}2970close$fd;2971}2972}29732974sub git_get_project_owner {2975my$project=shift;2976my$owner;29772978returnundefunless$project;2979$git_dir="$projectroot/$project";29802981if(!defined$gitweb_project_owner) {2982 git_get_project_list_from_file();2983}29842985if(exists$gitweb_project_owner->{$project}) {2986$owner=$gitweb_project_owner->{$project};2987}2988if(!defined$owner){2989$owner= git_get_project_config('owner');2990}2991if(!defined$owner) {2992$owner= get_file_owner("$git_dir");2993}29942995return$owner;2996}29972998sub git_get_last_activity {2999my($path) =@_;3000my$fd;30013002$git_dir="$projectroot/$path";3003open($fd,"-|", git_cmd(),'for-each-ref',3004'--format=%(committer)',3005'--sort=-committerdate',3006'--count=1',3007'refs/heads')orreturn;3008my$most_recent= <$fd>;3009close$fdorreturn;3010if(defined$most_recent&&3011$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {3012my$timestamp=$1;3013my$age=time-$timestamp;3014return($age, age_string($age));3015}3016return(undef,undef);3017}30183019# Implementation note: when a single remote is wanted, we cannot use 'git3020# remote show -n' because that command always work (assuming it's a remote URL3021# if it's not defined), and we cannot use 'git remote show' because that would3022# try to make a network roundtrip. So the only way to find if that particular3023# remote is defined is to walk the list provided by 'git remote -v' and stop if3024# and when we find what we want.3025sub git_get_remotes_list {3026my$wanted=shift;3027my%remotes= ();30283029open my$fd,'-|', git_cmd(),'remote','-v';3030return unless$fd;3031while(my$remote= <$fd>) {3032chomp$remote;3033$remote=~s!\t(.*?)\s+\((\w+)\)$!!;3034next if$wantedand not$remoteeq$wanted;3035my($url,$key) = ($1,$2);30363037$remotes{$remote} ||= {'heads'=> () };3038$remotes{$remote}{$key} =$url;3039}3040close$fdorreturn;3041returnwantarray?%remotes: \%remotes;3042}30433044# Takes a hash of remotes as first parameter and fills it by adding the3045# available remote heads for each of the indicated remotes.3046sub fill_remote_heads {3047my$remotes=shift;3048my@heads=map{"remotes/$_"}keys%$remotes;3049my@remoteheads= git_get_heads_list(undef,@heads);3050foreachmy$remote(keys%$remotes) {3051$remotes->{$remote}{'heads'} = [grep{3052$_->{'name'} =~s!^$remote/!!3053}@remoteheads];3054}3055}30563057sub git_get_references {3058my$type=shift||"";3059my%refs;3060# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113061# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3062open my$fd,"-|", git_cmd(),"show-ref","--dereference",3063($type? ("--","refs/$type") : ())# use -- <pattern> if $type3064orreturn;30653066while(my$line= <$fd>) {3067chomp$line;3068if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3069if(defined$refs{$1}) {3070push@{$refs{$1}},$2;3071}else{3072$refs{$1} = [$2];3073}3074}3075}3076close$fdorreturn;3077return \%refs;3078}30793080sub git_get_rev_name_tags {3081my$hash=shift||returnundef;30823083open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3084orreturn;3085my$name_rev= <$fd>;3086close$fd;30873088if($name_rev=~ m|^$hash tags/(.*)$|) {3089return$1;3090}else{3091# catches also '$hash undefined' output3092returnundef;3093}3094}30953096## ----------------------------------------------------------------------3097## parse to hash functions30983099sub parse_date {3100my$epoch=shift;3101my$tz=shift||"-0000";31023103my%date;3104my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3105my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3106my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3107$date{'hour'} =$hour;3108$date{'minute'} =$min;3109$date{'mday'} =$mday;3110$date{'day'} =$days[$wday];3111$date{'month'} =$months[$mon];3112$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3113$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3114$date{'mday-time'} =sprintf"%d%s%02d:%02d",3115$mday,$months[$mon],$hour,$min;3116$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",31171900+$year,1+$mon,$mday,$hour,$min,$sec;31183119my($tz_sign,$tz_hour,$tz_min) =3120($tz=~m/^([-+])(\d\d)(\d\d)$/);3121$tz_sign= ($tz_signeq'-'? -1: +1);3122my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3123($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3124$date{'hour_local'} =$hour;3125$date{'minute_local'} =$min;3126$date{'tz_local'} =$tz;3127$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",31281900+$year,$mon+1,$mday,3129$hour,$min,$sec,$tz);3130return%date;3131}31323133sub parse_tag {3134my$tag_id=shift;3135my%tag;3136my@comment;31373138open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3139$tag{'id'} =$tag_id;3140while(my$line= <$fd>) {3141chomp$line;3142if($line=~m/^object ([0-9a-fA-F]{40})$/) {3143$tag{'object'} =$1;3144}elsif($line=~m/^type (.+)$/) {3145$tag{'type'} =$1;3146}elsif($line=~m/^tag (.+)$/) {3147$tag{'name'} =$1;3148}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3149$tag{'author'} =$1;3150$tag{'author_epoch'} =$2;3151$tag{'author_tz'} =$3;3152if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3153$tag{'author_name'} =$1;3154$tag{'author_email'} =$2;3155}else{3156$tag{'author_name'} =$tag{'author'};3157}3158}elsif($line=~m/--BEGIN/) {3159push@comment,$line;3160last;3161}elsif($lineeq"") {3162last;3163}3164}3165push@comment, <$fd>;3166$tag{'comment'} = \@comment;3167close$fdorreturn;3168if(!defined$tag{'name'}) {3169return3170};3171return%tag3172}31733174sub parse_commit_text {3175my($commit_text,$withparents) =@_;3176my@commit_lines=split'\n',$commit_text;3177my%co;31783179pop@commit_lines;# Remove '\0'31803181if(!@commit_lines) {3182return;3183}31843185my$header=shift@commit_lines;3186if($header!~m/^[0-9a-fA-F]{40}/) {3187return;3188}3189($co{'id'},my@parents) =split' ',$header;3190while(my$line=shift@commit_lines) {3191last if$lineeq"\n";3192if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3193$co{'tree'} =$1;3194}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3195push@parents,$1;3196}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3197$co{'author'} = to_utf8($1);3198$co{'author_epoch'} =$2;3199$co{'author_tz'} =$3;3200if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3201$co{'author_name'} =$1;3202$co{'author_email'} =$2;3203}else{3204$co{'author_name'} =$co{'author'};3205}3206}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3207$co{'committer'} = to_utf8($1);3208$co{'committer_epoch'} =$2;3209$co{'committer_tz'} =$3;3210if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3211$co{'committer_name'} =$1;3212$co{'committer_email'} =$2;3213}else{3214$co{'committer_name'} =$co{'committer'};3215}3216}3217}3218if(!defined$co{'tree'}) {3219return;3220};3221$co{'parents'} = \@parents;3222$co{'parent'} =$parents[0];32233224foreachmy$title(@commit_lines) {3225$title=~s/^ //;3226if($titlene"") {3227$co{'title'} = chop_str($title,80,5);3228# remove leading stuff of merges to make the interesting part visible3229if(length($title) >50) {3230$title=~s/^Automatic //;3231$title=~s/^merge (of|with) /Merge ... /i;3232if(length($title) >50) {3233$title=~s/(http|rsync):\/\///;3234}3235if(length($title) >50) {3236$title=~s/(master|www|rsync)\.//;3237}3238if(length($title) >50) {3239$title=~s/kernel.org:?//;3240}3241if(length($title) >50) {3242$title=~s/\/pub\/scm//;3243}3244}3245$co{'title_short'} = chop_str($title,50,5);3246last;3247}3248}3249if(!defined$co{'title'} ||$co{'title'}eq"") {3250$co{'title'} =$co{'title_short'} ='(no commit message)';3251}3252# remove added spaces3253foreachmy$line(@commit_lines) {3254$line=~s/^ //;3255}3256$co{'comment'} = \@commit_lines;32573258my$age=time-$co{'committer_epoch'};3259$co{'age'} =$age;3260$co{'age_string'} = age_string($age);3261my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3262if($age>60*60*24*7*2) {3263$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3264$co{'age_string_age'} =$co{'age_string'};3265}else{3266$co{'age_string_date'} =$co{'age_string'};3267$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3268}3269return%co;3270}32713272sub parse_commit {3273my($commit_id) =@_;3274my%co;32753276local$/="\0";32773278open my$fd,"-|", git_cmd(),"rev-list",3279"--parents",3280"--header",3281"--max-count=1",3282$commit_id,3283"--",3284or die_error(500,"Open git-rev-list failed");3285%co= parse_commit_text(<$fd>,1);3286close$fd;32873288return%co;3289}32903291sub parse_commits {3292my($commit_id,$maxcount,$skip,$filename,@args) =@_;3293my@cos;32943295$maxcount||=1;3296$skip||=0;32973298local$/="\0";32993300open my$fd,"-|", git_cmd(),"rev-list",3301"--header",3302@args,3303("--max-count=".$maxcount),3304("--skip=".$skip),3305@extra_options,3306$commit_id,3307"--",3308($filename? ($filename) : ())3309or die_error(500,"Open git-rev-list failed");3310while(my$line= <$fd>) {3311my%co= parse_commit_text($line);3312push@cos, \%co;3313}3314close$fd;33153316returnwantarray?@cos: \@cos;3317}33183319# parse line of git-diff-tree "raw" output3320sub parse_difftree_raw_line {3321my$line=shift;3322my%res;33233324# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3325# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3326if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3327$res{'from_mode'} =$1;3328$res{'to_mode'} =$2;3329$res{'from_id'} =$3;3330$res{'to_id'} =$4;3331$res{'status'} =$5;3332$res{'similarity'} =$6;3333if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3334($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3335}else{3336$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3337}3338}3339# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3340# combined diff (for merge commit)3341elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3342$res{'nparents'} =length($1);3343$res{'from_mode'} = [split(' ',$2) ];3344$res{'to_mode'} =pop@{$res{'from_mode'}};3345$res{'from_id'} = [split(' ',$3) ];3346$res{'to_id'} =pop@{$res{'from_id'}};3347$res{'status'} = [split('',$4) ];3348$res{'to_file'} = unquote($5);3349}3350# 'c512b523472485aef4fff9e57b229d9d243c967f'3351elsif($line=~m/^([0-9a-fA-F]{40})$/) {3352$res{'commit'} =$1;3353}33543355returnwantarray?%res: \%res;3356}33573358# wrapper: return parsed line of git-diff-tree "raw" output3359# (the argument might be raw line, or parsed info)3360sub parsed_difftree_line {3361my$line_or_ref=shift;33623363if(ref($line_or_ref)eq"HASH") {3364# pre-parsed (or generated by hand)3365return$line_or_ref;3366}else{3367return parse_difftree_raw_line($line_or_ref);3368}3369}33703371# parse line of git-ls-tree output3372sub parse_ls_tree_line {3373my$line=shift;3374my%opts=@_;3375my%res;33763377if($opts{'-l'}) {3378#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3379$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;33803381$res{'mode'} =$1;3382$res{'type'} =$2;3383$res{'hash'} =$3;3384$res{'size'} =$4;3385if($opts{'-z'}) {3386$res{'name'} =$5;3387}else{3388$res{'name'} = unquote($5);3389}3390}else{3391#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3392$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;33933394$res{'mode'} =$1;3395$res{'type'} =$2;3396$res{'hash'} =$3;3397if($opts{'-z'}) {3398$res{'name'} =$4;3399}else{3400$res{'name'} = unquote($4);3401}3402}34033404returnwantarray?%res: \%res;3405}34063407# generates _two_ hashes, references to which are passed as 2 and 3 argument3408sub parse_from_to_diffinfo {3409my($diffinfo,$from,$to,@parents) =@_;34103411if($diffinfo->{'nparents'}) {3412# combined diff3413$from->{'file'} = [];3414$from->{'href'} = [];3415 fill_from_file_info($diffinfo,@parents)3416unlessexists$diffinfo->{'from_file'};3417for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3418$from->{'file'}[$i] =3419defined$diffinfo->{'from_file'}[$i] ?3420$diffinfo->{'from_file'}[$i] :3421$diffinfo->{'to_file'};3422if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3423$from->{'href'}[$i] = href(action=>"blob",3424 hash_base=>$parents[$i],3425 hash=>$diffinfo->{'from_id'}[$i],3426 file_name=>$from->{'file'}[$i]);3427}else{3428$from->{'href'}[$i] =undef;3429}3430}3431}else{3432# ordinary (not combined) diff3433$from->{'file'} =$diffinfo->{'from_file'};3434if($diffinfo->{'status'}ne"A") {# not new (added) file3435$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3436 hash=>$diffinfo->{'from_id'},3437 file_name=>$from->{'file'});3438}else{3439delete$from->{'href'};3440}3441}34423443$to->{'file'} =$diffinfo->{'to_file'};3444if(!is_deleted($diffinfo)) {# file exists in result3445$to->{'href'} = href(action=>"blob", hash_base=>$hash,3446 hash=>$diffinfo->{'to_id'},3447 file_name=>$to->{'file'});3448}else{3449delete$to->{'href'};3450}3451}34523453## ......................................................................3454## parse to array of hashes functions34553456sub git_get_heads_list {3457my($limit,@classes) =@_;3458@classes= ('heads')unless@classes;3459my@patterns=map{"refs/$_"}@classes;3460my@headslist;34613462open my$fd,'-|', git_cmd(),'for-each-ref',3463($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3464'--format=%(objectname) %(refname) %(subject)%00%(committer)',3465@patterns3466orreturn;3467while(my$line= <$fd>) {3468my%ref_item;34693470chomp$line;3471my($refinfo,$committerinfo) =split(/\0/,$line);3472my($hash,$name,$title) =split(' ',$refinfo,3);3473my($committer,$epoch,$tz) =3474($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3475$ref_item{'fullname'} =$name;3476$name=~s!^refs/(?:head|remote)s/!!;34773478$ref_item{'name'} =$name;3479$ref_item{'id'} =$hash;3480$ref_item{'title'} =$title||'(no commit message)';3481$ref_item{'epoch'} =$epoch;3482if($epoch) {3483$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3484}else{3485$ref_item{'age'} ="unknown";3486}34873488push@headslist, \%ref_item;3489}3490close$fd;34913492returnwantarray?@headslist: \@headslist;3493}34943495sub git_get_tags_list {3496my$limit=shift;3497my@tagslist;34983499open my$fd,'-|', git_cmd(),'for-each-ref',3500($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3501'--format=%(objectname) %(objecttype) %(refname) '.3502'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3503'refs/tags'3504orreturn;3505while(my$line= <$fd>) {3506my%ref_item;35073508chomp$line;3509my($refinfo,$creatorinfo) =split(/\0/,$line);3510my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3511my($creator,$epoch,$tz) =3512($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3513$ref_item{'fullname'} =$name;3514$name=~s!^refs/tags/!!;35153516$ref_item{'type'} =$type;3517$ref_item{'id'} =$id;3518$ref_item{'name'} =$name;3519if($typeeq"tag") {3520$ref_item{'subject'} =$title;3521$ref_item{'reftype'} =$reftype;3522$ref_item{'refid'} =$refid;3523}else{3524$ref_item{'reftype'} =$type;3525$ref_item{'refid'} =$id;3526}35273528if($typeeq"tag"||$typeeq"commit") {3529$ref_item{'epoch'} =$epoch;3530if($epoch) {3531$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3532}else{3533$ref_item{'age'} ="unknown";3534}3535}35363537push@tagslist, \%ref_item;3538}3539close$fd;35403541returnwantarray?@tagslist: \@tagslist;3542}35433544## ----------------------------------------------------------------------3545## filesystem-related functions35463547sub get_file_owner {3548my$path=shift;35493550my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3551my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3552if(!defined$gcos) {3553returnundef;3554}3555my$owner=$gcos;3556$owner=~s/[,;].*$//;3557return to_utf8($owner);3558}35593560# assume that file exists3561sub insert_file {3562my$filename=shift;35633564open my$fd,'<',$filename;3565print map{ to_utf8($_) } <$fd>;3566close$fd;3567}35683569## ......................................................................3570## mimetype related functions35713572sub mimetype_guess_file {3573my$filename=shift;3574my$mimemap=shift;3575-r $mimemaporreturnundef;35763577my%mimemap;3578open(my$mh,'<',$mimemap)orreturnundef;3579while(<$mh>) {3580next ifm/^#/;# skip comments3581my($mimetype,@exts) =split(/\s+/);3582foreachmy$ext(@exts) {3583$mimemap{$ext} =$mimetype;3584}3585}3586close($mh);35873588$filename=~/\.([^.]*)$/;3589return$mimemap{$1};3590}35913592sub mimetype_guess {3593my$filename=shift;3594my$mime;3595$filename=~/\./orreturnundef;35963597if($mimetypes_file) {3598my$file=$mimetypes_file;3599if($file!~m!^/!) {# if it is relative path3600# it is relative to project3601$file="$projectroot/$project/$file";3602}3603$mime= mimetype_guess_file($filename,$file);3604}3605$mime||= mimetype_guess_file($filename,'/etc/mime.types');3606return$mime;3607}36083609sub blob_mimetype {3610my$fd=shift;3611my$filename=shift;36123613if($filename) {3614my$mime= mimetype_guess($filename);3615$mimeandreturn$mime;3616}36173618# just in case3619return$default_blob_plain_mimetypeunless$fd;36203621if(-T $fd) {3622return'text/plain';3623}elsif(!$filename) {3624return'application/octet-stream';3625}elsif($filename=~m/\.png$/i) {3626return'image/png';3627}elsif($filename=~m/\.gif$/i) {3628return'image/gif';3629}elsif($filename=~m/\.jpe?g$/i) {3630return'image/jpeg';3631}else{3632return'application/octet-stream';3633}3634}36353636sub blob_contenttype {3637my($fd,$file_name,$type) =@_;36383639$type||= blob_mimetype($fd,$file_name);3640if($typeeq'text/plain'&&defined$default_text_plain_charset) {3641$type.="; charset=$default_text_plain_charset";3642}36433644return$type;3645}36463647# guess file syntax for syntax highlighting; return undef if no highlighting3648# the name of syntax can (in the future) depend on syntax highlighter used3649sub guess_file_syntax {3650my($highlight,$mimetype,$file_name) =@_;3651returnundefunless($highlight&&defined$file_name);3652my$basename= basename($file_name,'.in');3653return$highlight_basename{$basename}3654ifexists$highlight_basename{$basename};36553656$basename=~/\.([^.]*)$/;3657my$ext=$1orreturnundef;3658return$highlight_ext{$ext}3659ifexists$highlight_ext{$ext};36603661returnundef;3662}36633664# run highlighter and return FD of its output,3665# or return original FD if no highlighting3666sub run_highlighter {3667my($fd,$highlight,$syntax) =@_;3668return$fdunless($highlight&&defined$syntax);36693670close$fd;3671open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3672 quote_command($highlight_bin).3673" --replace-tabs=8 --fragment --syntax$syntax|"3674or die_error(500,"Couldn't open file or run syntax highlighter");3675return$fd;3676}36773678## ======================================================================3679## functions printing HTML: header, footer, error page36803681sub get_page_title {3682my$title= to_utf8($site_name);36833684return$titleunless(defined$project);3685$title.=" - ". to_utf8($project);36863687return$titleunless(defined$action);3688$title.="/$action";# $action is US-ASCII (7bit ASCII)36893690return$titleunless(defined$file_name);3691$title.=" - ". esc_path($file_name);3692if($actioneq"tree"&&$file_name!~ m|/$|) {3693$title.="/";3694}36953696return$title;3697}36983699sub get_content_type_html {3700# require explicit support from the UA if we are to send the page as3701# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3702# we have to do this because MSIE sometimes globs '*/*', pretending to3703# support xhtml+xml but choking when it gets what it asked for.3704if(defined$cgi->http('HTTP_ACCEPT') &&3705$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3706$cgi->Accept('application/xhtml+xml') !=0) {3707return'application/xhtml+xml';3708}else{3709return'text/html';3710}3711}37123713sub print_feed_meta {3714if(defined$project) {3715my%href_params= get_feed_info();3716if(!exists$href_params{'-title'}) {3717$href_params{'-title'} ='log';3718}37193720foreachmy$format(qw(RSS Atom)) {3721my$type=lc($format);3722my%link_attr= (3723'-rel'=>'alternate',3724'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3725'-type'=>"application/$type+xml"3726);37273728$href_params{'action'} =$type;3729$link_attr{'-href'} = href(%href_params);3730print"<link ".3731"rel=\"$link_attr{'-rel'}\"".3732"title=\"$link_attr{'-title'}\"".3733"href=\"$link_attr{'-href'}\"".3734"type=\"$link_attr{'-type'}\"".3735"/>\n";37363737$href_params{'extra_options'} ='--no-merges';3738$link_attr{'-href'} = href(%href_params);3739$link_attr{'-title'} .=' (no merges)';3740print"<link ".3741"rel=\"$link_attr{'-rel'}\"".3742"title=\"$link_attr{'-title'}\"".3743"href=\"$link_attr{'-href'}\"".3744"type=\"$link_attr{'-type'}\"".3745"/>\n";3746}37473748}else{3749printf('<link rel="alternate" title="%sprojects list" '.3750'href="%s" type="text/plain; charset=utf-8" />'."\n",3751 esc_attr($site_name), href(project=>undef, action=>"project_index"));3752printf('<link rel="alternate" title="%sprojects feeds" '.3753'href="%s" type="text/x-opml" />'."\n",3754 esc_attr($site_name), href(project=>undef, action=>"opml"));3755}3756}37573758sub print_header_links {3759my$status=shift;37603761# print out each stylesheet that exist, providing backwards capability3762# for those people who defined $stylesheet in a config file3763if(defined$stylesheet) {3764print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3765}else{3766foreachmy$stylesheet(@stylesheets) {3767next unless$stylesheet;3768print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3769}3770}3771 print_feed_meta()3772if($statuseq'200 OK');3773if(defined$favicon) {3774printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);3775}3776}37773778sub print_nav_breadcrumbs {3779my%opts=@_;37803781print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3782if(defined$project) {3783print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3784if(defined$action) {3785my$action_print=$action;3786if(defined$opts{-action_extra}) {3787$action_print=$cgi->a({-href => href(action=>$action)},3788$action);3789}3790print" /$action_print";3791}3792if(defined$opts{-action_extra}) {3793print" /$opts{-action_extra}";3794}3795print"\n";3796}3797}37983799sub print_search_form {3800if(!defined$searchtext) {3801$searchtext="";3802}3803my$search_hash;3804if(defined$hash_base) {3805$search_hash=$hash_base;3806}elsif(defined$hash) {3807$search_hash=$hash;3808}else{3809$search_hash="HEAD";3810}3811my$action=$my_uri;3812my$use_pathinfo= gitweb_check_feature('pathinfo');3813if($use_pathinfo) {3814$action.="/".esc_url($project);3815}3816print$cgi->startform(-method=>"get", -action =>$action) .3817"<div class=\"search\">\n".3818(!$use_pathinfo&&3819$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3820$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3821$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3822$cgi->popup_menu(-name =>'st', -default=>'commit',3823-values=> ['commit','grep','author','committer','pickaxe']) .3824$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3825" search:\n",3826$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3827"<span title=\"Extended regular expression\">".3828$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3829-checked =>$search_use_regexp) .3830"</span>".3831"</div>".3832$cgi->end_form() ."\n";3833}38343835sub git_header_html {3836my$status=shift||"200 OK";3837my$expires=shift;3838my%opts=@_;38393840my$title= get_page_title();3841my$content_type= get_content_type_html();3842print$cgi->header(-type=>$content_type, -charset =>'utf-8',3843-status=>$status, -expires =>$expires)3844unless($opts{'-no_http_header'});3845my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3846print<<EOF;3847<?xml version="1.0" encoding="utf-8"?>3848<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3849<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3850<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3851<!-- git core binaries version$git_version-->3852<head>3853<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3854<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3855<meta name="robots" content="index, nofollow"/>3856<title>$title</title>3857EOF3858# the stylesheet, favicon etc urls won't work correctly with path_info3859# unless we set the appropriate base URL3860if($ENV{'PATH_INFO'}) {3861print"<base href=\"".esc_url($base_url)."\"/>\n";3862}3863 print_header_links($status);3864print"</head>\n".3865"<body>\n";38663867if(defined$site_header&& -f $site_header) {3868 insert_file($site_header);3869}38703871print"<div class=\"page_header\">\n";3872if(defined$logo) {3873print$cgi->a({-href => esc_url($logo_url),3874-title =>$logo_label},3875$cgi->img({-src => esc_url($logo),3876-width =>72, -height =>27,3877-alt =>"git",3878-class=>"logo"}));3879}3880 print_nav_breadcrumbs(%opts);3881print"</div>\n";38823883my$have_search= gitweb_check_feature('search');3884if(defined$project&&$have_search) {3885 print_search_form();3886}3887}38883889sub git_footer_html {3890my$feed_class='rss_logo';38913892print"<div class=\"page_footer\">\n";3893if(defined$project) {3894my$descr= git_get_project_description($project);3895if(defined$descr) {3896print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3897}38983899my%href_params= get_feed_info();3900if(!%href_params) {3901$feed_class.=' generic';3902}3903$href_params{'-title'} ||='log';39043905foreachmy$format(qw(RSS Atom)) {3906$href_params{'action'} =lc($format);3907print$cgi->a({-href => href(%href_params),3908-title =>"$href_params{'-title'}$formatfeed",3909-class=>$feed_class},$format)."\n";3910}39113912}else{3913print$cgi->a({-href => href(project=>undef, action=>"opml"),3914-class=>$feed_class},"OPML") ." ";3915print$cgi->a({-href => href(project=>undef, action=>"project_index"),3916-class=>$feed_class},"TXT") ."\n";3917}3918print"</div>\n";# class="page_footer"39193920if(defined$t0&& gitweb_check_feature('timed')) {3921print"<div id=\"generating_info\">\n";3922print'This page took '.3923'<span id="generating_time" class="time_span">'.3924 tv_interval($t0, [ gettimeofday() ]).3925' seconds </span>'.3926' and '.3927'<span id="generating_cmd">'.3928$number_of_git_cmds.3929'</span> git commands '.3930" to generate.\n";3931print"</div>\n";# class="page_footer"3932}39333934if(defined$site_footer&& -f $site_footer) {3935 insert_file($site_footer);3936}39373938print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;3939if(defined$action&&3940$actioneq'blame_incremental') {3941print qq!<script type="text/javascript">\n!.3942 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.3943 qq!"!. href() .qq!");\n!.3944 qq!</script>\n!;3945}else{3946my($jstimezone,$tz_cookie,$datetime_class) =3947 gitweb_get_feature('javascript-timezone');39483949print qq!<script type="text/javascript">\n!.3950 qq!window.onload = function () {\n!;3951if(gitweb_check_feature('javascript-actions')) {3952print qq! fixLinks();\n!;3953}3954if($jstimezone&&$tz_cookie&&$datetime_class) {3955print qq! var tz_cookie = { name:'$tz_cookie', expires:14, path:'/'};\n!.# in days3956 qq! onloadTZSetup('$jstimezone', tz_cookie,'$datetime_class');\n!;3957}3958print qq!};\n!.3959 qq!</script>\n!;3960}39613962print"</body>\n".3963"</html>";3964}39653966# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])3967# Example: die_error(404, 'Hash not found')3968# By convention, use the following status codes (as defined in RFC 2616):3969# 400: Invalid or missing CGI parameters, or3970# requested object exists but has wrong type.3971# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3972# this server or project.3973# 404: Requested object/revision/project doesn't exist.3974# 500: The server isn't configured properly, or3975# an internal error occurred (e.g. failed assertions caused by bugs), or3976# an unknown error occurred (e.g. the git binary died unexpectedly).3977# 503: The server is currently unavailable (because it is overloaded,3978# or down for maintenance). Generally, this is a temporary state.3979sub die_error {3980my$status=shift||500;3981my$error= esc_html(shift) ||"Internal Server Error";3982my$extra=shift;3983my%opts=@_;39843985my%http_responses= (3986400=>'400 Bad Request',3987403=>'403 Forbidden',3988404=>'404 Not Found',3989500=>'500 Internal Server Error',3990503=>'503 Service Unavailable',3991);3992 git_header_html($http_responses{$status},undef,%opts);3993print<<EOF;3994<div class="page_body">3995<br /><br />3996$status-$error3997<br />3998EOF3999if(defined$extra) {4000print"<hr />\n".4001"$extra\n";4002}4003print"</div>\n";40044005 git_footer_html();4006goto DONE_GITWEB4007unless($opts{'-error_handler'});4008}40094010## ----------------------------------------------------------------------4011## functions printing or outputting HTML: navigation40124013sub git_print_page_nav {4014my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;4015$extra=''if!defined$extra;# pager or formats40164017my@navs=qw(summary shortlog log commit commitdiff tree);4018if($suppress) {4019@navs=grep{$_ne$suppress}@navs;4020}40214022my%arg=map{$_=> {action=>$_} }@navs;4023if(defined$head) {4024for(qw(commit commitdiff)) {4025$arg{$_}{'hash'} =$head;4026}4027if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {4028for(qw(shortlog log)) {4029$arg{$_}{'hash'} =$head;4030}4031}4032}40334034$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;4035$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;40364037my@actions= gitweb_get_feature('actions');4038my%repl= (4039'%'=>'%',4040'n'=>$project,# project name4041'f'=>$git_dir,# project path within filesystem4042'h'=>$treehead||'',# current hash ('h' parameter)4043'b'=>$treebase||'',# hash base ('hb' parameter)4044);4045while(@actions) {4046my($label,$link,$pos) =splice(@actions,0,3);4047# insert4048@navs=map{$_eq$pos? ($_,$label) :$_}@navs;4049# munch munch4050$link=~s/%([%nfhb])/$repl{$1}/g;4051$arg{$label}{'_href'} =$link;4052}40534054print"<div class=\"page_nav\">\n".4055(join" | ",4056map{$_eq$current?4057$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4058}@navs);4059print"<br/>\n$extra<br/>\n".4060"</div>\n";4061}40624063# returns a submenu for the nagivation of the refs views (tags, heads,4064# remotes) with the current view disabled and the remotes view only4065# available if the feature is enabled4066sub format_ref_views {4067my($current) =@_;4068my@ref_views=qw{tags heads};4069push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4070returnjoin" | ",map{4071$_eq$current?$_:4072$cgi->a({-href => href(action=>$_)},$_)4073}@ref_views4074}40754076sub format_paging_nav {4077my($action,$page,$has_next_link) =@_;4078my$paging_nav;407940804081if($page>0) {4082$paging_nav.=4083$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4084" ⋅ ".4085$cgi->a({-href => href(-replay=>1, page=>$page-1),4086-accesskey =>"p", -title =>"Alt-p"},"prev");4087}else{4088$paging_nav.="first ⋅ prev";4089}40904091if($has_next_link) {4092$paging_nav.=" ⋅ ".4093$cgi->a({-href => href(-replay=>1, page=>$page+1),4094-accesskey =>"n", -title =>"Alt-n"},"next");4095}else{4096$paging_nav.=" ⋅ next";4097}40984099return$paging_nav;4100}41014102## ......................................................................4103## functions printing or outputting HTML: div41044105sub git_print_header_div {4106my($action,$title,$hash,$hash_base) =@_;4107my%args= ();41084109$args{'action'} =$action;4110$args{'hash'} =$hashif$hash;4111$args{'hash_base'} =$hash_baseif$hash_base;41124113print"<div class=\"header\">\n".4114$cgi->a({-href => href(%args), -class=>"title"},4115$title?$title:$action) .4116"\n</div>\n";4117}41184119sub format_repo_url {4120my($name,$url) =@_;4121return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4122}41234124# Group output by placing it in a DIV element and adding a header.4125# Options for start_div() can be provided by passing a hash reference as the4126# first parameter to the function.4127# Options to git_print_header_div() can be provided by passing an array4128# reference. This must follow the options to start_div if they are present.4129# The content can be a scalar, which is output as-is, a scalar reference, which4130# is output after html escaping, an IO handle passed either as *handle or4131# *handle{IO}, or a function reference. In the latter case all following4132# parameters will be taken as argument to the content function call.4133sub git_print_section {4134my($div_args,$header_args,$content);4135my$arg=shift;4136if(ref($arg)eq'HASH') {4137$div_args=$arg;4138$arg=shift;4139}4140if(ref($arg)eq'ARRAY') {4141$header_args=$arg;4142$arg=shift;4143}4144$content=$arg;41454146print$cgi->start_div($div_args);4147 git_print_header_div(@$header_args);41484149if(ref($content)eq'CODE') {4150$content->(@_);4151}elsif(ref($content)eq'SCALAR') {4152print esc_html($$content);4153}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4154print<$content>;4155}elsif(!ref($content) &&defined($content)) {4156print$content;4157}41584159print$cgi->end_div;4160}41614162sub format_timestamp_html {4163my$date=shift;4164my$strtime=$date->{'rfc2822'};41654166my(undef,undef,$datetime_class) =4167 gitweb_get_feature('javascript-timezone');4168if($datetime_class) {4169$strtime= qq!<span class="$datetime_class">$strtime</span>!;4170}41714172my$localtime_format='(%02d:%02d%s)';4173if($date->{'hour_local'} <6) {4174$localtime_format='(<span class="atnight">%02d:%02d</span>%s)';4175}4176$strtime.=' '.4177sprintf($localtime_format,4178$date->{'hour_local'},$date->{'minute_local'},$date->{'tz_local'});41794180return$strtime;4181}41824183# Outputs the author name and date in long form4184sub git_print_authorship {4185my$co=shift;4186my%opts=@_;4187my$tag=$opts{-tag} ||'div';4188my$author=$co->{'author_name'};41894190my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4191print"<$tagclass=\"author_date\">".4192 format_search_author($author,"author", esc_html($author)) .4193" [".format_timestamp_html(\%ad)."]".4194 git_get_avatar($co->{'author_email'}, -pad_before =>1) .4195"</$tag>\n";4196}41974198# Outputs table rows containing the full author or committer information,4199# in the format expected for 'commit' view (& similar).4200# Parameters are a commit hash reference, followed by the list of people4201# to output information for. If the list is empty it defaults to both4202# author and committer.4203sub git_print_authorship_rows {4204my$co=shift;4205# too bad we can't use @people = @_ || ('author', 'committer')4206my@people=@_;4207@people= ('author','committer')unless@people;4208foreachmy$who(@people) {4209my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4210print"<tr><td>$who</td><td>".4211 format_search_author($co->{"${who}_name"},$who,4212 esc_html($co->{"${who}_name"})) ." ".4213 format_search_author($co->{"${who}_email"},$who,4214 esc_html("<".$co->{"${who}_email"} .">")) .4215"</td><td rowspan=\"2\">".4216 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4217"</td></tr>\n".4218"<tr>".4219"<td></td><td>".4220 format_timestamp_html(\%wd) .4221"</td>".4222"</tr>\n";4223}4224}42254226sub git_print_page_path {4227my$name=shift;4228my$type=shift;4229my$hb=shift;423042314232print"<div class=\"page_path\">";4233print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4234-title =>'tree root'}, to_utf8("[$project]"));4235print" / ";4236if(defined$name) {4237my@dirname=split'/',$name;4238my$basename=pop@dirname;4239my$fullname='';42404241foreachmy$dir(@dirname) {4242$fullname.= ($fullname?'/':'') .$dir;4243print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4244 hash_base=>$hb),4245-title =>$fullname}, esc_path($dir));4246print" / ";4247}4248if(defined$type&&$typeeq'blob') {4249print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4250 hash_base=>$hb),4251-title =>$name}, esc_path($basename));4252}elsif(defined$type&&$typeeq'tree') {4253print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4254 hash_base=>$hb),4255-title =>$name}, esc_path($basename));4256print" / ";4257}else{4258print esc_path($basename);4259}4260}4261print"<br/></div>\n";4262}42634264sub git_print_log {4265my$log=shift;4266my%opts=@_;42674268if($opts{'-remove_title'}) {4269# remove title, i.e. first line of log4270shift@$log;4271}4272# remove leading empty lines4273while(defined$log->[0] &&$log->[0]eq"") {4274shift@$log;4275}42764277# print log4278my$signoff=0;4279my$empty=0;4280foreachmy$line(@$log) {4281if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {4282$signoff=1;4283$empty=0;4284if(!$opts{'-remove_signoff'}) {4285print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4286next;4287}else{4288# remove signoff lines4289next;4290}4291}else{4292$signoff=0;4293}42944295# print only one empty line4296# do not print empty line after signoff4297if($lineeq"") {4298next if($empty||$signoff);4299$empty=1;4300}else{4301$empty=0;4302}43034304print format_log_line_html($line) ."<br/>\n";4305}43064307if($opts{'-final_empty_line'}) {4308# end with single empty line4309print"<br/>\n"unless$empty;4310}4311}43124313# return link target (what link points to)4314sub git_get_link_target {4315my$hash=shift;4316my$link_target;43174318# read link4319open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4320orreturn;4321{4322local$/=undef;4323$link_target= <$fd>;4324}4325close$fd4326orreturn;43274328return$link_target;4329}43304331# given link target, and the directory (basedir) the link is in,4332# return target of link relative to top directory (top tree);4333# return undef if it is not possible (including absolute links).4334sub normalize_link_target {4335my($link_target,$basedir) =@_;43364337# absolute symlinks (beginning with '/') cannot be normalized4338return if(substr($link_target,0,1)eq'/');43394340# normalize link target to path from top (root) tree (dir)4341my$path;4342if($basedir) {4343$path=$basedir.'/'.$link_target;4344}else{4345# we are in top (root) tree (dir)4346$path=$link_target;4347}43484349# remove //, /./, and /../4350my@path_parts;4351foreachmy$part(split('/',$path)) {4352# discard '.' and ''4353next if(!$part||$parteq'.');4354# handle '..'4355if($parteq'..') {4356if(@path_parts) {4357pop@path_parts;4358}else{4359# link leads outside repository (outside top dir)4360return;4361}4362}else{4363push@path_parts,$part;4364}4365}4366$path=join('/',@path_parts);43674368return$path;4369}43704371# print tree entry (row of git_tree), but without encompassing <tr> element4372sub git_print_tree_entry {4373my($t,$basedir,$hash_base,$have_blame) =@_;43744375my%base_key= ();4376$base_key{'hash_base'} =$hash_baseifdefined$hash_base;43774378# The format of a table row is: mode list link. Where mode is4379# the mode of the entry, list is the name of the entry, an href,4380# and link is the action links of the entry.43814382print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4383if(exists$t->{'size'}) {4384print"<td class=\"size\">$t->{'size'}</td>\n";4385}4386if($t->{'type'}eq"blob") {4387print"<td class=\"list\">".4388$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4389 file_name=>"$basedir$t->{'name'}",%base_key),4390-class=>"list"}, esc_path($t->{'name'}));4391if(S_ISLNK(oct$t->{'mode'})) {4392my$link_target= git_get_link_target($t->{'hash'});4393if($link_target) {4394my$norm_target= normalize_link_target($link_target,$basedir);4395if(defined$norm_target) {4396print" -> ".4397$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4398 file_name=>$norm_target),4399-title =>$norm_target}, esc_path($link_target));4400}else{4401print" -> ". esc_path($link_target);4402}4403}4404}4405print"</td>\n";4406print"<td class=\"link\">";4407print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4408 file_name=>"$basedir$t->{'name'}",%base_key)},4409"blob");4410if($have_blame) {4411print" | ".4412$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4413 file_name=>"$basedir$t->{'name'}",%base_key)},4414"blame");4415}4416if(defined$hash_base) {4417print" | ".4418$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4419 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4420"history");4421}4422print" | ".4423$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4424 file_name=>"$basedir$t->{'name'}")},4425"raw");4426print"</td>\n";44274428}elsif($t->{'type'}eq"tree") {4429print"<td class=\"list\">";4430print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4431 file_name=>"$basedir$t->{'name'}",4432%base_key)},4433 esc_path($t->{'name'}));4434print"</td>\n";4435print"<td class=\"link\">";4436print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4437 file_name=>"$basedir$t->{'name'}",4438%base_key)},4439"tree");4440if(defined$hash_base) {4441print" | ".4442$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4443 file_name=>"$basedir$t->{'name'}")},4444"history");4445}4446print"</td>\n";4447}else{4448# unknown object: we can only present history for it4449# (this includes 'commit' object, i.e. submodule support)4450print"<td class=\"list\">".4451 esc_path($t->{'name'}) .4452"</td>\n";4453print"<td class=\"link\">";4454if(defined$hash_base) {4455print$cgi->a({-href => href(action=>"history",4456 hash_base=>$hash_base,4457 file_name=>"$basedir$t->{'name'}")},4458"history");4459}4460print"</td>\n";4461}4462}44634464## ......................................................................4465## functions printing large fragments of HTML44664467# get pre-image filenames for merge (combined) diff4468sub fill_from_file_info {4469my($diff,@parents) =@_;44704471$diff->{'from_file'} = [ ];4472$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4473for(my$i=0;$i<$diff->{'nparents'};$i++) {4474if($diff->{'status'}[$i]eq'R'||4475$diff->{'status'}[$i]eq'C') {4476$diff->{'from_file'}[$i] =4477 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4478}4479}44804481return$diff;4482}44834484# is current raw difftree line of file deletion4485sub is_deleted {4486my$diffinfo=shift;44874488return$diffinfo->{'to_id'}eq('0' x 40);4489}44904491# does patch correspond to [previous] difftree raw line4492# $diffinfo - hashref of parsed raw diff format4493# $patchinfo - hashref of parsed patch diff format4494# (the same keys as in $diffinfo)4495sub is_patch_split {4496my($diffinfo,$patchinfo) =@_;44974498returndefined$diffinfo&&defined$patchinfo4499&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4500}450145024503sub git_difftree_body {4504my($difftree,$hash,@parents) =@_;4505my($parent) =$parents[0];4506my$have_blame= gitweb_check_feature('blame');4507print"<div class=\"list_head\">\n";4508if($#{$difftree} >10) {4509print(($#{$difftree} +1) ." files changed:\n");4510}4511print"</div>\n";45124513print"<table class=\"".4514(@parents>1?"combined ":"") .4515"diff_tree\">\n";45164517# header only for combined diff in 'commitdiff' view4518my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4519if($has_header) {4520# table header4521print"<thead><tr>\n".4522"<th></th><th></th>\n";# filename, patchN link4523for(my$i=0;$i<@parents;$i++) {4524my$par=$parents[$i];4525print"<th>".4526$cgi->a({-href => href(action=>"commitdiff",4527 hash=>$hash, hash_parent=>$par),4528-title =>'commitdiff to parent number '.4529($i+1) .': '.substr($par,0,7)},4530$i+1) .4531" </th>\n";4532}4533print"</tr></thead>\n<tbody>\n";4534}45354536my$alternate=1;4537my$patchno=0;4538foreachmy$line(@{$difftree}) {4539my$diff= parsed_difftree_line($line);45404541if($alternate) {4542print"<tr class=\"dark\">\n";4543}else{4544print"<tr class=\"light\">\n";4545}4546$alternate^=1;45474548if(exists$diff->{'nparents'}) {# combined diff45494550 fill_from_file_info($diff,@parents)4551unlessexists$diff->{'from_file'};45524553if(!is_deleted($diff)) {4554# file exists in the result (child) commit4555print"<td>".4556$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4557 file_name=>$diff->{'to_file'},4558 hash_base=>$hash),4559-class=>"list"}, esc_path($diff->{'to_file'})) .4560"</td>\n";4561}else{4562print"<td>".4563 esc_path($diff->{'to_file'}) .4564"</td>\n";4565}45664567if($actioneq'commitdiff') {4568# link to patch4569$patchno++;4570print"<td class=\"link\">".4571$cgi->a({-href => href(-anchor=>"patch$patchno")},4572"patch") .4573" | ".4574"</td>\n";4575}45764577my$has_history=0;4578my$not_deleted=0;4579for(my$i=0;$i<$diff->{'nparents'};$i++) {4580my$hash_parent=$parents[$i];4581my$from_hash=$diff->{'from_id'}[$i];4582my$from_path=$diff->{'from_file'}[$i];4583my$status=$diff->{'status'}[$i];45844585$has_history||= ($statusne'A');4586$not_deleted||= ($statusne'D');45874588if($statuseq'A') {4589print"<td class=\"link\"align=\"right\"> | </td>\n";4590}elsif($statuseq'D') {4591print"<td class=\"link\">".4592$cgi->a({-href => href(action=>"blob",4593 hash_base=>$hash,4594 hash=>$from_hash,4595 file_name=>$from_path)},4596"blob". ($i+1)) .4597" | </td>\n";4598}else{4599if($diff->{'to_id'}eq$from_hash) {4600print"<td class=\"link nochange\">";4601}else{4602print"<td class=\"link\">";4603}4604print$cgi->a({-href => href(action=>"blobdiff",4605 hash=>$diff->{'to_id'},4606 hash_parent=>$from_hash,4607 hash_base=>$hash,4608 hash_parent_base=>$hash_parent,4609 file_name=>$diff->{'to_file'},4610 file_parent=>$from_path)},4611"diff". ($i+1)) .4612" | </td>\n";4613}4614}46154616print"<td class=\"link\">";4617if($not_deleted) {4618print$cgi->a({-href => href(action=>"blob",4619 hash=>$diff->{'to_id'},4620 file_name=>$diff->{'to_file'},4621 hash_base=>$hash)},4622"blob");4623print" | "if($has_history);4624}4625if($has_history) {4626print$cgi->a({-href => href(action=>"history",4627 file_name=>$diff->{'to_file'},4628 hash_base=>$hash)},4629"history");4630}4631print"</td>\n";46324633print"</tr>\n";4634next;# instead of 'else' clause, to avoid extra indent4635}4636# else ordinary diff46374638my($to_mode_oct,$to_mode_str,$to_file_type);4639my($from_mode_oct,$from_mode_str,$from_file_type);4640if($diff->{'to_mode'}ne('0' x 6)) {4641$to_mode_oct=oct$diff->{'to_mode'};4642if(S_ISREG($to_mode_oct)) {# only for regular file4643$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4644}4645$to_file_type= file_type($diff->{'to_mode'});4646}4647if($diff->{'from_mode'}ne('0' x 6)) {4648$from_mode_oct=oct$diff->{'from_mode'};4649if(S_ISREG($from_mode_oct)) {# only for regular file4650$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4651}4652$from_file_type= file_type($diff->{'from_mode'});4653}46544655if($diff->{'status'}eq"A") {# created4656my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4657$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4658$mode_chng.="]</span>";4659print"<td>";4660print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4661 hash_base=>$hash, file_name=>$diff->{'file'}),4662-class=>"list"}, esc_path($diff->{'file'}));4663print"</td>\n";4664print"<td>$mode_chng</td>\n";4665print"<td class=\"link\">";4666if($actioneq'commitdiff') {4667# link to patch4668$patchno++;4669print$cgi->a({-href => href(-anchor=>"patch$patchno")},4670"patch") .4671" | ";4672}4673print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4674 hash_base=>$hash, file_name=>$diff->{'file'})},4675"blob");4676print"</td>\n";46774678}elsif($diff->{'status'}eq"D") {# deleted4679my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4680print"<td>";4681print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4682 hash_base=>$parent, file_name=>$diff->{'file'}),4683-class=>"list"}, esc_path($diff->{'file'}));4684print"</td>\n";4685print"<td>$mode_chng</td>\n";4686print"<td class=\"link\">";4687if($actioneq'commitdiff') {4688# link to patch4689$patchno++;4690print$cgi->a({-href => href(-anchor=>"patch$patchno")},4691"patch") .4692" | ";4693}4694print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4695 hash_base=>$parent, file_name=>$diff->{'file'})},4696"blob") ." | ";4697if($have_blame) {4698print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4699 file_name=>$diff->{'file'})},4700"blame") ." | ";4701}4702print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4703 file_name=>$diff->{'file'})},4704"history");4705print"</td>\n";47064707}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4708my$mode_chnge="";4709if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4710$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4711if($from_file_typene$to_file_type) {4712$mode_chnge.=" from$from_file_typeto$to_file_type";4713}4714if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4715if($from_mode_str&&$to_mode_str) {4716$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4717}elsif($to_mode_str) {4718$mode_chnge.=" mode:$to_mode_str";4719}4720}4721$mode_chnge.="]</span>\n";4722}4723print"<td>";4724print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4725 hash_base=>$hash, file_name=>$diff->{'file'}),4726-class=>"list"}, esc_path($diff->{'file'}));4727print"</td>\n";4728print"<td>$mode_chnge</td>\n";4729print"<td class=\"link\">";4730if($actioneq'commitdiff') {4731# link to patch4732$patchno++;4733print$cgi->a({-href => href(-anchor=>"patch$patchno")},4734"patch") .4735" | ";4736}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4737# "commit" view and modified file (not onlu mode changed)4738print$cgi->a({-href => href(action=>"blobdiff",4739 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4740 hash_base=>$hash, hash_parent_base=>$parent,4741 file_name=>$diff->{'file'})},4742"diff") .4743" | ";4744}4745print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4746 hash_base=>$hash, file_name=>$diff->{'file'})},4747"blob") ." | ";4748if($have_blame) {4749print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4750 file_name=>$diff->{'file'})},4751"blame") ." | ";4752}4753print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4754 file_name=>$diff->{'file'})},4755"history");4756print"</td>\n";47574758}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4759my%status_name= ('R'=>'moved','C'=>'copied');4760my$nstatus=$status_name{$diff->{'status'}};4761my$mode_chng="";4762if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4763# mode also for directories, so we cannot use $to_mode_str4764$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4765}4766print"<td>".4767$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4768 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4769-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4770"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4771$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4772 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4773-class=>"list"}, esc_path($diff->{'from_file'})) .4774" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4775"<td class=\"link\">";4776if($actioneq'commitdiff') {4777# link to patch4778$patchno++;4779print$cgi->a({-href => href(-anchor=>"patch$patchno")},4780"patch") .4781" | ";4782}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4783# "commit" view and modified file (not only pure rename or copy)4784print$cgi->a({-href => href(action=>"blobdiff",4785 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4786 hash_base=>$hash, hash_parent_base=>$parent,4787 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4788"diff") .4789" | ";4790}4791print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4792 hash_base=>$parent, file_name=>$diff->{'to_file'})},4793"blob") ." | ";4794if($have_blame) {4795print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4796 file_name=>$diff->{'to_file'})},4797"blame") ." | ";4798}4799print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4800 file_name=>$diff->{'to_file'})},4801"history");4802print"</td>\n";48034804}# we should not encounter Unmerged (U) or Unknown (X) status4805print"</tr>\n";4806}4807print"</tbody>"if$has_header;4808print"</table>\n";4809}48104811sub git_patchset_body {4812my($fd,$difftree,$hash,@hash_parents) =@_;4813my($hash_parent) =$hash_parents[0];48144815my$is_combined= (@hash_parents>1);4816my$patch_idx=0;4817my$patch_number=0;4818my$patch_line;4819my$diffinfo;4820my$to_name;4821my(%from,%to);48224823print"<div class=\"patchset\">\n";48244825# skip to first patch4826while($patch_line= <$fd>) {4827chomp$patch_line;48284829last if($patch_line=~m/^diff /);4830}48314832 PATCH:4833while($patch_line) {48344835# parse "git diff" header line4836if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4837# $1 is from_name, which we do not use4838$to_name= unquote($2);4839$to_name=~s!^b/!!;4840}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4841# $1 is 'cc' or 'combined', which we do not use4842$to_name= unquote($2);4843}else{4844$to_name=undef;4845}48464847# check if current patch belong to current raw line4848# and parse raw git-diff line if needed4849if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4850# this is continuation of a split patch4851print"<div class=\"patch cont\">\n";4852}else{4853# advance raw git-diff output if needed4854$patch_idx++ifdefined$diffinfo;48554856# read and prepare patch information4857$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);48584859# compact combined diff output can have some patches skipped4860# find which patch (using pathname of result) we are at now;4861if($is_combined) {4862while($to_namene$diffinfo->{'to_file'}) {4863print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4864 format_diff_cc_simplified($diffinfo,@hash_parents) .4865"</div>\n";# class="patch"48664867$patch_idx++;4868$patch_number++;48694870last if$patch_idx>$#$difftree;4871$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4872}4873}48744875# modifies %from, %to hashes4876 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);48774878# this is first patch for raw difftree line with $patch_idx index4879# we index @$difftree array from 0, but number patches from 14880print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4881}48824883# git diff header4884#assert($patch_line =~ m/^diff /) if DEBUG;4885#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4886$patch_number++;4887# print "git diff" header4888print format_git_diff_header_line($patch_line,$diffinfo,4889 \%from, \%to);48904891# print extended diff header4892print"<div class=\"diff extended_header\">\n";4893 EXTENDED_HEADER:4894while($patch_line= <$fd>) {4895chomp$patch_line;48964897last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);48984899print format_extended_diff_header_line($patch_line,$diffinfo,4900 \%from, \%to);4901}4902print"</div>\n";# class="diff extended_header"49034904# from-file/to-file diff header4905if(!$patch_line) {4906print"</div>\n";# class="patch"4907last PATCH;4908}4909next PATCH if($patch_line=~m/^diff /);4910#assert($patch_line =~ m/^---/) if DEBUG;49114912my$last_patch_line=$patch_line;4913$patch_line= <$fd>;4914chomp$patch_line;4915#assert($patch_line =~ m/^\+\+\+/) if DEBUG;49164917print format_diff_from_to_header($last_patch_line,$patch_line,4918$diffinfo, \%from, \%to,4919@hash_parents);49204921# the patch itself4922 LINE:4923while($patch_line= <$fd>) {4924chomp$patch_line;49254926next PATCH if($patch_line=~m/^diff /);49274928print format_diff_line($patch_line, \%from, \%to);4929}49304931}continue{4932print"</div>\n";# class="patch"4933}49344935# for compact combined (--cc) format, with chunk and patch simplification4936# the patchset might be empty, but there might be unprocessed raw lines4937for(++$patch_idxif$patch_number>0;4938$patch_idx<@$difftree;4939++$patch_idx) {4940# read and prepare patch information4941$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);49424943# generate anchor for "patch" links in difftree / whatchanged part4944print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4945 format_diff_cc_simplified($diffinfo,@hash_parents) .4946"</div>\n";# class="patch"49474948$patch_number++;4949}49504951if($patch_number==0) {4952if(@hash_parents>1) {4953print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4954}else{4955print"<div class=\"diff nodifferences\">No differences found</div>\n";4956}4957}49584959print"</div>\n";# class="patchset"4960}49614962# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49634964# fills project list info (age, description, owner, category, forks)4965# for each project in the list, removing invalid projects from4966# returned list4967# NOTE: modifies $projlist, but does not remove entries from it4968sub fill_project_list_info {4969my$projlist=shift;4970my@projects;49714972my$show_ctags= gitweb_check_feature('ctags');4973 PROJECT:4974foreachmy$pr(@$projlist) {4975my(@activity) = git_get_last_activity($pr->{'path'});4976unless(@activity) {4977next PROJECT;4978}4979($pr->{'age'},$pr->{'age_string'}) =@activity;4980if(!defined$pr->{'descr'}) {4981my$descr= git_get_project_description($pr->{'path'}) ||"";4982$descr= to_utf8($descr);4983$pr->{'descr_long'} =$descr;4984$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);4985}4986if(!defined$pr->{'owner'}) {4987$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";4988}4989if($show_ctags) {4990$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});4991}4992if($projects_list_group_categories&& !defined$pr->{'category'}) {4993my$cat= git_get_project_category($pr->{'path'}) ||4994$project_list_default_category;4995$pr->{'category'} = to_utf8($cat);4996}49974998push@projects,$pr;4999}50005001return@projects;5002}50035004sub sort_projects_list {5005my($projlist,$order) =@_;5006my@projects;50075008my%order_info= (5009 project => { key =>'path', type =>'str'},5010 descr => { key =>'descr_long', type =>'str'},5011 owner => { key =>'owner', type =>'str'},5012 age => { key =>'age', type =>'num'}5013);5014my$oi=$order_info{$order};5015return@$projlistunlessdefined$oi;5016if($oi->{'type'}eq'str') {5017@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@$projlist;5018}else{5019@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@$projlist;5020}50215022return@projects;5023}50245025# returns a hash of categories, containing the list of project5026# belonging to each category5027sub build_projlist_by_category {5028my($projlist,$from,$to) =@_;5029my%categories;50305031$from=0unlessdefined$from;5032$to=$#$projlistif(!defined$to||$#$projlist<$to);50335034for(my$i=$from;$i<=$to;$i++) {5035my$pr=$projlist->[$i];5036push@{$categories{$pr->{'category'} }},$pr;5037}50385039returnwantarray?%categories: \%categories;5040}50415042# print 'sort by' <th> element, generating 'sort by $name' replay link5043# if that order is not selected5044sub print_sort_th {5045print format_sort_th(@_);5046}50475048sub format_sort_th {5049my($name,$order,$header) =@_;5050my$sort_th="";5051$header||=ucfirst($name);50525053if($ordereq$name) {5054$sort_th.="<th>$header</th>\n";5055}else{5056$sort_th.="<th>".5057$cgi->a({-href => href(-replay=>1, order=>$name),5058-class=>"header"},$header) .5059"</th>\n";5060}50615062return$sort_th;5063}50645065sub git_project_list_rows {5066my($projlist,$from,$to,$check_forks) =@_;50675068$from=0unlessdefined$from;5069$to=$#$projlistif(!defined$to||$#$projlist<$to);50705071my$alternate=1;5072for(my$i=$from;$i<=$to;$i++) {5073my$pr=$projlist->[$i];50745075if($alternate) {5076print"<tr class=\"dark\">\n";5077}else{5078print"<tr class=\"light\">\n";5079}5080$alternate^=1;50815082if($check_forks) {5083print"<td>";5084if($pr->{'forks'}) {5085my$nforks=scalar@{$pr->{'forks'}};5086if($nforks>0) {5087print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5088-title =>"$nforksforks"},"+");5089}else{5090print$cgi->span({-title =>"$nforksforks"},"+");5091}5092}5093print"</td>\n";5094}5095print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5096-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".5097"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5098-class=>"list", -title =>$pr->{'descr_long'}},5099 esc_html($pr->{'descr'})) ."</td>\n".5100"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5101print"<td class=\"". age_class($pr->{'age'}) ."\">".5102(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".5103"<td class=\"link\">".5104$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5105$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5106$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5107$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5108($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5109"</td>\n".5110"</tr>\n";5111}5112}51135114sub git_project_list_body {5115# actually uses global variable $project5116my($projlist,$order,$from,$to,$extra,$no_header) =@_;5117my@projects=@$projlist;51185119my$check_forks= gitweb_check_feature('forks');5120my$show_ctags= gitweb_check_feature('ctags');5121my$tagfilter=$show_ctags?$cgi->param('by_tag') :undef;5122$check_forks=undef5123if($tagfilter||$searchtext);51245125# filtering out forks before filling info allows to do less work5126@projects= filter_forks_from_projects_list(\@projects)5127if($check_forks);5128@projects= fill_project_list_info(\@projects);5129# searching projects require filling to be run before it5130@projects= search_projects_list(\@projects,5131'searchtext'=>$searchtext,5132'tagfilter'=>$tagfilter)5133if($tagfilter||$searchtext);51345135$order||=$default_projects_order;5136$from=0unlessdefined$from;5137$to=$#projectsif(!defined$to||$#projects<$to);51385139# short circuit5140if($from>$to) {5141print"<center>\n".5142"<b>No such projects found</b><br />\n".5143"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5144"</center>\n<br />\n";5145return;5146}51475148@projects= sort_projects_list(\@projects,$order);51495150if($show_ctags) {5151my$ctags= git_gather_all_ctags(\@projects);5152my$cloud= git_populate_project_tagcloud($ctags);5153print git_show_project_tagcloud($cloud,64);5154}51555156print"<table class=\"project_list\">\n";5157unless($no_header) {5158print"<tr>\n";5159if($check_forks) {5160print"<th></th>\n";5161}5162 print_sort_th('project',$order,'Project');5163 print_sort_th('descr',$order,'Description');5164 print_sort_th('owner',$order,'Owner');5165 print_sort_th('age',$order,'Last Change');5166print"<th></th>\n".# for links5167"</tr>\n";5168}51695170if($projects_list_group_categories) {5171# only display categories with projects in the $from-$to window5172@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5173my%categories= build_projlist_by_category(\@projects,$from,$to);5174foreachmy$cat(sort keys%categories) {5175unless($cateq"") {5176print"<tr>\n";5177if($check_forks) {5178print"<td></td>\n";5179}5180print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5181print"</tr>\n";5182}51835184 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5185}5186}else{5187 git_project_list_rows(\@projects,$from,$to,$check_forks);5188}51895190if(defined$extra) {5191print"<tr>\n";5192if($check_forks) {5193print"<td></td>\n";5194}5195print"<td colspan=\"5\">$extra</td>\n".5196"</tr>\n";5197}5198print"</table>\n";5199}52005201sub git_log_body {5202# uses global variable $project5203my($commitlist,$from,$to,$refs,$extra) =@_;52045205$from=0unlessdefined$from;5206$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);52075208for(my$i=0;$i<=$to;$i++) {5209my%co= %{$commitlist->[$i]};5210next if!%co;5211my$commit=$co{'id'};5212my$ref= format_ref_marker($refs,$commit);5213 git_print_header_div('commit',5214"<span class=\"age\">$co{'age_string'}</span>".5215 esc_html($co{'title'}) .$ref,5216$commit);5217print"<div class=\"title_text\">\n".5218"<div class=\"log_link\">\n".5219$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5220" | ".5221$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5222" | ".5223$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5224"<br/>\n".5225"</div>\n";5226 git_print_authorship(\%co, -tag =>'span');5227print"<br/>\n</div>\n";52285229print"<div class=\"log_body\">\n";5230 git_print_log($co{'comment'}, -final_empty_line=>1);5231print"</div>\n";5232}5233if($extra) {5234print"<div class=\"page_nav\">\n";5235print"$extra\n";5236print"</div>\n";5237}5238}52395240sub git_shortlog_body {5241# uses global variable $project5242my($commitlist,$from,$to,$refs,$extra) =@_;52435244$from=0unlessdefined$from;5245$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);52465247print"<table class=\"shortlog\">\n";5248my$alternate=1;5249for(my$i=$from;$i<=$to;$i++) {5250my%co= %{$commitlist->[$i]};5251my$commit=$co{'id'};5252my$ref= format_ref_marker($refs,$commit);5253if($alternate) {5254print"<tr class=\"dark\">\n";5255}else{5256print"<tr class=\"light\">\n";5257}5258$alternate^=1;5259# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5260print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5261 format_author_html('td', \%co,10) ."<td>";5262print format_subject_html($co{'title'},$co{'title_short'},5263 href(action=>"commit", hash=>$commit),$ref);5264print"</td>\n".5265"<td class=\"link\">".5266$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5267$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5268$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5269my$snapshot_links= format_snapshot_links($commit);5270if(defined$snapshot_links) {5271print" | ".$snapshot_links;5272}5273print"</td>\n".5274"</tr>\n";5275}5276if(defined$extra) {5277print"<tr>\n".5278"<td colspan=\"4\">$extra</td>\n".5279"</tr>\n";5280}5281print"</table>\n";5282}52835284sub git_history_body {5285# Warning: assumes constant type (blob or tree) during history5286my($commitlist,$from,$to,$refs,$extra,5287$file_name,$file_hash,$ftype) =@_;52885289$from=0unlessdefined$from;5290$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});52915292print"<table class=\"history\">\n";5293my$alternate=1;5294for(my$i=$from;$i<=$to;$i++) {5295my%co= %{$commitlist->[$i]};5296if(!%co) {5297next;5298}5299my$commit=$co{'id'};53005301my$ref= format_ref_marker($refs,$commit);53025303if($alternate) {5304print"<tr class=\"dark\">\n";5305}else{5306print"<tr class=\"light\">\n";5307}5308$alternate^=1;5309print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5310# shortlog: format_author_html('td', \%co, 10)5311 format_author_html('td', \%co,15,3) ."<td>";5312# originally git_history used chop_str($co{'title'}, 50)5313print format_subject_html($co{'title'},$co{'title_short'},5314 href(action=>"commit", hash=>$commit),$ref);5315print"</td>\n".5316"<td class=\"link\">".5317$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5318$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");53195320if($ftypeeq'blob') {5321my$blob_current=$file_hash;5322my$blob_parent= git_get_hash_by_path($commit,$file_name);5323if(defined$blob_current&&defined$blob_parent&&5324$blob_currentne$blob_parent) {5325print" | ".5326$cgi->a({-href => href(action=>"blobdiff",5327 hash=>$blob_current, hash_parent=>$blob_parent,5328 hash_base=>$hash_base, hash_parent_base=>$commit,5329 file_name=>$file_name)},5330"diff to current");5331}5332}5333print"</td>\n".5334"</tr>\n";5335}5336if(defined$extra) {5337print"<tr>\n".5338"<td colspan=\"4\">$extra</td>\n".5339"</tr>\n";5340}5341print"</table>\n";5342}53435344sub git_tags_body {5345# uses global variable $project5346my($taglist,$from,$to,$extra) =@_;5347$from=0unlessdefined$from;5348$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);53495350print"<table class=\"tags\">\n";5351my$alternate=1;5352for(my$i=$from;$i<=$to;$i++) {5353my$entry=$taglist->[$i];5354my%tag=%$entry;5355my$comment=$tag{'subject'};5356my$comment_short;5357if(defined$comment) {5358$comment_short= chop_str($comment,30,5);5359}5360if($alternate) {5361print"<tr class=\"dark\">\n";5362}else{5363print"<tr class=\"light\">\n";5364}5365$alternate^=1;5366if(defined$tag{'age'}) {5367print"<td><i>$tag{'age'}</i></td>\n";5368}else{5369print"<td></td>\n";5370}5371print"<td>".5372$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5373-class=>"list name"}, esc_html($tag{'name'})) .5374"</td>\n".5375"<td>";5376if(defined$comment) {5377print format_subject_html($comment,$comment_short,5378 href(action=>"tag", hash=>$tag{'id'}));5379}5380print"</td>\n".5381"<td class=\"selflink\">";5382if($tag{'type'}eq"tag") {5383print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");5384}else{5385print" ";5386}5387print"</td>\n".5388"<td class=\"link\">"." | ".5389$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});5390if($tag{'reftype'}eq"commit") {5391print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .5392" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");5393}elsif($tag{'reftype'}eq"blob") {5394print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");5395}5396print"</td>\n".5397"</tr>";5398}5399if(defined$extra) {5400print"<tr>\n".5401"<td colspan=\"5\">$extra</td>\n".5402"</tr>\n";5403}5404print"</table>\n";5405}54065407sub git_heads_body {5408# uses global variable $project5409my($headlist,$head,$from,$to,$extra) =@_;5410$from=0unlessdefined$from;5411$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);54125413print"<table class=\"heads\">\n";5414my$alternate=1;5415for(my$i=$from;$i<=$to;$i++) {5416my$entry=$headlist->[$i];5417my%ref=%$entry;5418my$curr=$ref{'id'}eq$head;5419if($alternate) {5420print"<tr class=\"dark\">\n";5421}else{5422print"<tr class=\"light\">\n";5423}5424$alternate^=1;5425print"<td><i>$ref{'age'}</i></td>\n".5426($curr?"<td class=\"current_head\">":"<td>") .5427$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),5428-class=>"list name"},esc_html($ref{'name'})) .5429"</td>\n".5430"<td class=\"link\">".5431$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".5432$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".5433$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .5434"</td>\n".5435"</tr>";5436}5437if(defined$extra) {5438print"<tr>\n".5439"<td colspan=\"3\">$extra</td>\n".5440"</tr>\n";5441}5442print"</table>\n";5443}54445445# Display a single remote block5446sub git_remote_block {5447my($remote,$rdata,$limit,$head) =@_;54485449my$heads=$rdata->{'heads'};5450my$fetch=$rdata->{'fetch'};5451my$push=$rdata->{'push'};54525453my$urls_table="<table class=\"projects_list\">\n";54545455if(defined$fetch) {5456if($fetcheq$push) {5457$urls_table.= format_repo_url("URL",$fetch);5458}else{5459$urls_table.= format_repo_url("Fetch URL",$fetch);5460$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;5461}5462}elsif(defined$push) {5463$urls_table.= format_repo_url("Push URL",$push);5464}else{5465$urls_table.= format_repo_url("","No remote URL");5466}54675468$urls_table.="</table>\n";54695470my$dots;5471if(defined$limit&&$limit<@$heads) {5472$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");5473}54745475print$urls_table;5476 git_heads_body($heads,$head,0,$limit,$dots);5477}54785479# Display a list of remote names with the respective fetch and push URLs5480sub git_remotes_list {5481my($remotedata,$limit) =@_;5482print"<table class=\"heads\">\n";5483my$alternate=1;5484my@remotes=sort keys%$remotedata;54855486my$limited=$limit&&$limit<@remotes;54875488$#remotes=$limit-1if$limited;54895490while(my$remote=shift@remotes) {5491my$rdata=$remotedata->{$remote};5492my$fetch=$rdata->{'fetch'};5493my$push=$rdata->{'push'};5494if($alternate) {5495print"<tr class=\"dark\">\n";5496}else{5497print"<tr class=\"light\">\n";5498}5499$alternate^=1;5500print"<td>".5501$cgi->a({-href=> href(action=>'remotes', hash=>$remote),5502-class=>"list name"},esc_html($remote)) .5503"</td>";5504print"<td class=\"link\">".5505(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .5506" | ".5507(defined$push?$cgi->a({-href=>$push},"push") :"push") .5508"</td>";55095510print"</tr>\n";5511}55125513if($limited) {5514print"<tr>\n".5515"<td colspan=\"3\">".5516$cgi->a({-href => href(action=>"remotes")},"...") .5517"</td>\n"."</tr>\n";5518}55195520print"</table>";5521}55225523# Display remote heads grouped by remote, unless there are too many5524# remotes, in which case we only display the remote names5525sub git_remotes_body {5526my($remotedata,$limit,$head) =@_;5527if($limitand$limit<keys%$remotedata) {5528 git_remotes_list($remotedata,$limit);5529}else{5530 fill_remote_heads($remotedata);5531while(my($remote,$rdata) =each%$remotedata) {5532 git_print_section({-class=>"remote", -id=>$remote},5533["remotes",$remote,$remote],sub{5534 git_remote_block($remote,$rdata,$limit,$head);5535});5536}5537}5538}55395540sub git_search_message {5541my%co=@_;55425543my$greptype;5544if($searchtypeeq'commit') {5545$greptype="--grep=";5546}elsif($searchtypeeq'author') {5547$greptype="--author=";5548}elsif($searchtypeeq'committer') {5549$greptype="--committer=";5550}5551$greptype.=$searchtext;5552my@commitlist= parse_commits($hash,101, (100*$page),undef,5553$greptype,'--regexp-ignore-case',5554$search_use_regexp?'--extended-regexp':'--fixed-strings');55555556my$paging_nav='';5557if($page>0) {5558$paging_nav.=5559$cgi->a({-href => href(-replay=>1, page=>undef)},5560"first") .5561" ⋅ ".5562$cgi->a({-href => href(-replay=>1, page=>$page-1),5563-accesskey =>"p", -title =>"Alt-p"},"prev");5564}else{5565$paging_nav.="first ⋅ prev";5566}5567my$next_link='';5568if($#commitlist>=100) {5569$next_link=5570$cgi->a({-href => href(-replay=>1, page=>$page+1),5571-accesskey =>"n", -title =>"Alt-n"},"next");5572$paging_nav.=" ⋅$next_link";5573}else{5574$paging_nav.=" ⋅ next";5575}55765577 git_header_html();55785579 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);5580 git_print_header_div('commit', esc_html($co{'title'}),$hash);5581if($page==0&& !@commitlist) {5582print"<p>No match.</p>\n";5583}else{5584 git_search_grep_body(\@commitlist,0,99,$next_link);5585}55865587 git_footer_html();5588}55895590sub git_search_changes {5591my%co=@_;55925593local$/="\n";5594open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,5595'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",5596($search_use_regexp?'--pickaxe-regex': ())5597or die_error(500,"Open git-log failed");55985599 git_header_html();56005601 git_print_page_nav('','',$hash,$co{'tree'},$hash);5602 git_print_header_div('commit', esc_html($co{'title'}),$hash);56035604print"<table class=\"pickaxe search\">\n";5605my$alternate=1;5606undef%co;5607my@files;5608while(my$line= <$fd>) {5609chomp$line;5610next unless$line;56115612my%set= parse_difftree_raw_line($line);5613if(defined$set{'commit'}) {5614# finish previous commit5615if(%co) {5616print"</td>\n".5617"<td class=\"link\">".5618$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},5619"commit") .5620" | ".5621$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},5622 hash_base=>$co{'id'})},5623"tree") .5624"</td>\n".5625"</tr>\n";5626}56275628if($alternate) {5629print"<tr class=\"dark\">\n";5630}else{5631print"<tr class=\"light\">\n";5632}5633$alternate^=1;5634%co= parse_commit($set{'commit'});5635my$author= chop_and_escape_str($co{'author_name'},15,5);5636print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5637"<td><i>$author</i></td>\n".5638"<td>".5639$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5640-class=>"list subject"},5641 chop_and_escape_str($co{'title'},50) ."<br/>");5642}elsif(defined$set{'to_id'}) {5643next if($set{'to_id'} =~m/^0{40}$/);56445645print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},5646 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),5647-class=>"list"},5648"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .5649"<br/>\n";5650}5651}5652close$fd;56535654# finish last commit (warning: repetition!)5655if(%co) {5656print"</td>\n".5657"<td class=\"link\">".5658$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},5659"commit") .5660" | ".5661$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},5662 hash_base=>$co{'id'})},5663"tree") .5664"</td>\n".5665"</tr>\n";5666}56675668print"</table>\n";56695670 git_footer_html();5671}56725673sub git_search_files {5674my%co=@_;56755676local$/="\n";5677open my$fd,"-|", git_cmd(),'grep','-n',5678$search_use_regexp? ('-E','-i') :'-F',5679$searchtext,$co{'tree'}5680or die_error(500,"Open git-grep failed");56815682 git_header_html();56835684 git_print_page_nav('','',$hash,$co{'tree'},$hash);5685 git_print_header_div('commit', esc_html($co{'title'}),$hash);56865687print"<table class=\"grep_search\">\n";5688my$alternate=1;5689my$matches=0;5690my$lastfile='';5691while(my$line= <$fd>) {5692chomp$line;5693my($file,$lno,$ltext,$binary);5694last if($matches++>1000);5695if($line=~/^Binary file (.+) matches$/) {5696$file=$1;5697$binary=1;5698}else{5699(undef,$file,$lno,$ltext) =split(/:/,$line,4);5700}5701if($filene$lastfile) {5702$lastfileand print"</td></tr>\n";5703if($alternate++) {5704print"<tr class=\"dark\">\n";5705}else{5706print"<tr class=\"light\">\n";5707}5708print"<td class=\"list\">".5709$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},5710 file_name=>"$file"),5711-class=>"list"}, esc_path($file));5712print"</td><td>\n";5713$lastfile=$file;5714}5715if($binary) {5716print"<div class=\"binary\">Binary file</div>\n";5717}else{5718$ltext= untabify($ltext);5719if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {5720$ltext= esc_html($1, -nbsp=>1);5721$ltext.='<span class="match">';5722$ltext.= esc_html($2, -nbsp=>1);5723$ltext.='</span>';5724$ltext.= esc_html($3, -nbsp=>1);5725}else{5726$ltext= esc_html($ltext, -nbsp=>1);5727}5728print"<div class=\"pre\">".5729$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},5730 file_name=>"$file").'#l'.$lno,5731-class=>"linenr"},sprintf('%4i',$lno))5732.' '.$ltext."</div>\n";5733}5734}5735if($lastfile) {5736print"</td></tr>\n";5737if($matches>1000) {5738print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";5739}5740}else{5741print"<div class=\"diff nodifferences\">No matches found</div>\n";5742}5743close$fd;57445745print"</table>\n";57465747 git_footer_html();5748}57495750sub git_search_grep_body {5751my($commitlist,$from,$to,$extra) =@_;5752$from=0unlessdefined$from;5753$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);57545755print"<table class=\"commit_search\">\n";5756my$alternate=1;5757for(my$i=$from;$i<=$to;$i++) {5758my%co= %{$commitlist->[$i]};5759if(!%co) {5760next;5761}5762my$commit=$co{'id'};5763if($alternate) {5764print"<tr class=\"dark\">\n";5765}else{5766print"<tr class=\"light\">\n";5767}5768$alternate^=1;5769print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5770 format_author_html('td', \%co,15,5) .5771"<td>".5772$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5773-class=>"list subject"},5774 chop_and_escape_str($co{'title'},50) ."<br/>");5775my$comment=$co{'comment'};5776foreachmy$line(@$comment) {5777if($line=~m/^(.*?)($search_regexp)(.*)$/i) {5778my($lead,$match,$trail) = ($1,$2,$3);5779$match= chop_str($match,70,5,'center');5780my$contextlen=int((80-length($match))/2);5781$contextlen=30if($contextlen>30);5782$lead= chop_str($lead,$contextlen,10,'left');5783$trail= chop_str($trail,$contextlen,10,'right');57845785$lead= esc_html($lead);5786$match= esc_html($match);5787$trail= esc_html($trail);57885789print"$lead<span class=\"match\">$match</span>$trail<br />";5790}5791}5792print"</td>\n".5793"<td class=\"link\">".5794$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .5795" | ".5796$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .5797" | ".5798$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");5799print"</td>\n".5800"</tr>\n";5801}5802if(defined$extra) {5803print"<tr>\n".5804"<td colspan=\"3\">$extra</td>\n".5805"</tr>\n";5806}5807print"</table>\n";5808}58095810## ======================================================================5811## ======================================================================5812## actions58135814sub git_project_list {5815my$order=$input_params{'order'};5816if(defined$order&&$order!~m/none|project|descr|owner|age/) {5817 die_error(400,"Unknown order parameter");5818}58195820my@list= git_get_projects_list();5821if(!@list) {5822 die_error(404,"No projects found");5823}58245825 git_header_html();5826if(defined$home_text&& -f $home_text) {5827print"<div class=\"index_include\">\n";5828 insert_file($home_text);5829print"</div>\n";5830}5831print$cgi->startform(-method=>"get") .5832"<p class=\"projsearch\">Search:\n".5833$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".5834"</p>".5835$cgi->end_form() ."\n";5836 git_project_list_body(\@list,$order);5837 git_footer_html();5838}58395840sub git_forks {5841my$order=$input_params{'order'};5842if(defined$order&&$order!~m/none|project|descr|owner|age/) {5843 die_error(400,"Unknown order parameter");5844}58455846my@list= git_get_projects_list($project);5847if(!@list) {5848 die_error(404,"No forks found");5849}58505851 git_header_html();5852 git_print_page_nav('','');5853 git_print_header_div('summary',"$projectforks");5854 git_project_list_body(\@list,$order);5855 git_footer_html();5856}58575858sub git_project_index {5859my@projects= git_get_projects_list();5860if(!@projects) {5861 die_error(404,"No projects found");5862}58635864print$cgi->header(5865-type =>'text/plain',5866-charset =>'utf-8',5867-content_disposition =>'inline; filename="index.aux"');58685869foreachmy$pr(@projects) {5870if(!exists$pr->{'owner'}) {5871$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");5872}58735874my($path,$owner) = ($pr->{'path'},$pr->{'owner'});5875# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '5876$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5877$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5878$path=~s/ /\+/g;5879$owner=~s/ /\+/g;58805881print"$path$owner\n";5882}5883}58845885sub git_summary {5886my$descr= git_get_project_description($project) ||"none";5887my%co= parse_commit("HEAD");5888my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();5889my$head=$co{'id'};5890my$remote_heads= gitweb_check_feature('remote_heads');58915892my$owner= git_get_project_owner($project);58935894my$refs= git_get_references();5895# These get_*_list functions return one more to allow us to see if5896# there are more ...5897my@taglist= git_get_tags_list(16);5898my@headlist= git_get_heads_list(16);5899my%remotedata=$remote_heads? git_get_remotes_list() : ();5900my@forklist;5901my$check_forks= gitweb_check_feature('forks');59025903if($check_forks) {5904# find forks of a project5905@forklist= git_get_projects_list($project);5906# filter out forks of forks5907@forklist= filter_forks_from_projects_list(\@forklist)5908if(@forklist);5909}59105911 git_header_html();5912 git_print_page_nav('summary','',$head);59135914print"<div class=\"title\"> </div>\n";5915print"<table class=\"projects_list\">\n".5916"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".5917"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";5918if(defined$cd{'rfc2822'}) {5919print"<tr id=\"metadata_lchange\"><td>last change</td>".5920"<td>".format_timestamp_html(\%cd)."</td></tr>\n";5921}59225923# use per project git URL list in $projectroot/$project/cloneurl5924# or make project git URL from git base URL and project name5925my$url_tag="URL";5926my@url_list= git_get_project_url_list($project);5927@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;5928foreachmy$git_url(@url_list) {5929next unless$git_url;5930print format_repo_url($url_tag,$git_url);5931$url_tag="";5932}59335934# Tag cloud5935my$show_ctags= gitweb_check_feature('ctags');5936if($show_ctags) {5937my$ctags= git_get_project_ctags($project);5938if(%$ctags) {5939# without ability to add tags, don't show if there are none5940my$cloud= git_populate_project_tagcloud($ctags);5941print"<tr id=\"metadata_ctags\">".5942"<td>content tags</td>".5943"<td>".git_show_project_tagcloud($cloud,48)."</td>".5944"</tr>\n";5945}5946}59475948print"</table>\n";59495950# If XSS prevention is on, we don't include README.html.5951# TODO: Allow a readme in some safe format.5952if(!$prevent_xss&& -s "$projectroot/$project/README.html") {5953print"<div class=\"title\">readme</div>\n".5954"<div class=\"readme\">\n";5955 insert_file("$projectroot/$project/README.html");5956print"\n</div>\n";# class="readme"5957}59585959# we need to request one more than 16 (0..15) to check if5960# those 16 are all5961my@commitlist=$head? parse_commits($head,17) : ();5962if(@commitlist) {5963 git_print_header_div('shortlog');5964 git_shortlog_body(\@commitlist,0,15,$refs,5965$#commitlist<=15?undef:5966$cgi->a({-href => href(action=>"shortlog")},"..."));5967}59685969if(@taglist) {5970 git_print_header_div('tags');5971 git_tags_body(\@taglist,0,15,5972$#taglist<=15?undef:5973$cgi->a({-href => href(action=>"tags")},"..."));5974}59755976if(@headlist) {5977 git_print_header_div('heads');5978 git_heads_body(\@headlist,$head,0,15,5979$#headlist<=15?undef:5980$cgi->a({-href => href(action=>"heads")},"..."));5981}59825983if(%remotedata) {5984 git_print_header_div('remotes');5985 git_remotes_body(\%remotedata,15,$head);5986}59875988if(@forklist) {5989 git_print_header_div('forks');5990 git_project_list_body(\@forklist,'age',0,15,5991$#forklist<=15?undef:5992$cgi->a({-href => href(action=>"forks")},"..."),5993'no_header');5994}59955996 git_footer_html();5997}59985999sub git_tag {6000my%tag= parse_tag($hash);60016002if(!%tag) {6003 die_error(404,"Unknown tag object");6004}60056006my$head= git_get_head_hash($project);6007 git_header_html();6008 git_print_page_nav('','',$head,undef,$head);6009 git_print_header_div('commit', esc_html($tag{'name'}),$hash);6010print"<div class=\"title_text\">\n".6011"<table class=\"object_header\">\n".6012"<tr>\n".6013"<td>object</td>\n".6014"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6015$tag{'object'}) ."</td>\n".6016"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6017$tag{'type'}) ."</td>\n".6018"</tr>\n";6019if(defined($tag{'author'})) {6020 git_print_authorship_rows(\%tag,'author');6021}6022print"</table>\n\n".6023"</div>\n";6024print"<div class=\"page_body\">";6025my$comment=$tag{'comment'};6026foreachmy$line(@$comment) {6027chomp$line;6028print esc_html($line, -nbsp=>1) ."<br/>\n";6029}6030print"</div>\n";6031 git_footer_html();6032}60336034sub git_blame_common {6035my$format=shift||'porcelain';6036if($formateq'porcelain'&&$cgi->param('js')) {6037$format='incremental';6038$action='blame_incremental';# for page title etc6039}60406041# permissions6042 gitweb_check_feature('blame')6043or die_error(403,"Blame view not allowed");60446045# error checking6046 die_error(400,"No file name given")unless$file_name;6047$hash_base||= git_get_head_hash($project);6048 die_error(404,"Couldn't find base commit")unless$hash_base;6049my%co= parse_commit($hash_base)6050or die_error(404,"Commit not found");6051my$ftype="blob";6052if(!defined$hash) {6053$hash= git_get_hash_by_path($hash_base,$file_name,"blob")6054or die_error(404,"Error looking up file");6055}else{6056$ftype= git_get_type($hash);6057if($ftype!~"blob") {6058 die_error(400,"Object is not a blob");6059}6060}60616062my$fd;6063if($formateq'incremental') {6064# get file contents (as base)6065open$fd,"-|", git_cmd(),'cat-file','blob',$hash6066or die_error(500,"Open git-cat-file failed");6067}elsif($formateq'data') {6068# run git-blame --incremental6069open$fd,"-|", git_cmd(),"blame","--incremental",6070$hash_base,"--",$file_name6071or die_error(500,"Open git-blame --incremental failed");6072}else{6073# run git-blame --porcelain6074open$fd,"-|", git_cmd(),"blame",'-p',6075$hash_base,'--',$file_name6076or die_error(500,"Open git-blame --porcelain failed");6077}60786079# incremental blame data returns early6080if($formateq'data') {6081print$cgi->header(6082-type=>"text/plain", -charset =>"utf-8",6083-status=>"200 OK");6084local$| =1;# output autoflush6085printwhile<$fd>;6086close$fd6087or print"ERROR$!\n";60886089print'END';6090if(defined$t0&& gitweb_check_feature('timed')) {6091print' '.6092 tv_interval($t0, [ gettimeofday() ]).6093' '.$number_of_git_cmds;6094}6095print"\n";60966097return;6098}60996100# page header6101 git_header_html();6102my$formats_nav=6103$cgi->a({-href => href(action=>"blob", -replay=>1)},6104"blob") .6105" | ";6106if($formateq'incremental') {6107$formats_nav.=6108$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},6109"blame") ." (non-incremental)";6110}else{6111$formats_nav.=6112$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},6113"blame") ." (incremental)";6114}6115$formats_nav.=6116" | ".6117$cgi->a({-href => href(action=>"history", -replay=>1)},6118"history") .6119" | ".6120$cgi->a({-href => href(action=>$action, file_name=>$file_name)},6121"HEAD");6122 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6123 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6124 git_print_page_path($file_name,$ftype,$hash_base);61256126# page body6127if($formateq'incremental') {6128print"<noscript>\n<div class=\"error\"><center><b>\n".6129"This page requires JavaScript to run.\nUse ".6130$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},6131'this page').6132" instead.\n".6133"</b></center></div>\n</noscript>\n";61346135print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;6136}61376138print qq!<div class="page_body">\n!;6139print qq!<div id="progress_info">.../ ...</div>\n!6140if($formateq'incremental');6141print qq!<table id="blame_table"class="blame" width="100%">\n!.6142#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.6143 qq!<thead>\n!.6144 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.6145 qq!</thead>\n!.6146 qq!<tbody>\n!;61476148my@rev_color=qw(light dark);6149my$num_colors=scalar(@rev_color);6150my$current_color=0;61516152if($formateq'incremental') {6153my$color_class=$rev_color[$current_color];61546155#contents of a file6156my$linenr=0;6157 LINE:6158while(my$line= <$fd>) {6159chomp$line;6160$linenr++;61616162print qq!<tr id="l$linenr"class="$color_class">!.6163 qq!<td class="sha1"><a href=""> </a></td>!.6164 qq!<td class="linenr">!.6165 qq!<a class="linenr" href="">$linenr</a></td>!;6166print qq!<td class="pre">! . esc_html($line) ."</td>\n";6167print qq!</tr>\n!;6168}61696170}else{# porcelain, i.e. ordinary blame6171my%metainfo= ();# saves information about commits61726173# blame data6174 LINE:6175while(my$line= <$fd>) {6176chomp$line;6177# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]6178# no <lines in group> for subsequent lines in group of lines6179my($full_rev,$orig_lineno,$lineno,$group_size) =6180($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);6181if(!exists$metainfo{$full_rev}) {6182$metainfo{$full_rev} = {'nprevious'=>0};6183}6184my$meta=$metainfo{$full_rev};6185my$data;6186while($data= <$fd>) {6187chomp$data;6188last if($data=~s/^\t//);# contents of line6189if($data=~/^(\S+)(?: (.*))?$/) {6190$meta->{$1} =$2unlessexists$meta->{$1};6191}6192if($data=~/^previous /) {6193$meta->{'nprevious'}++;6194}6195}6196my$short_rev=substr($full_rev,0,8);6197my$author=$meta->{'author'};6198my%date=6199 parse_date($meta->{'author-time'},$meta->{'author-tz'});6200my$date=$date{'iso-tz'};6201if($group_size) {6202$current_color= ($current_color+1) %$num_colors;6203}6204my$tr_class=$rev_color[$current_color];6205$tr_class.=' boundary'if(exists$meta->{'boundary'});6206$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);6207$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);6208print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";6209if($group_size) {6210print"<td class=\"sha1\"";6211print" title=\"". esc_html($author) .",$date\"";6212print" rowspan=\"$group_size\""if($group_size>1);6213print">";6214print$cgi->a({-href => href(action=>"commit",6215 hash=>$full_rev,6216 file_name=>$file_name)},6217 esc_html($short_rev));6218if($group_size>=2) {6219my@author_initials= ($author=~/\b([[:upper:]])\B/g);6220if(@author_initials) {6221print"<br />".6222 esc_html(join('',@author_initials));6223# or join('.', ...)6224}6225}6226print"</td>\n";6227}6228# 'previous' <sha1 of parent commit> <filename at commit>6229if(exists$meta->{'previous'} &&6230$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {6231$meta->{'parent'} =$1;6232$meta->{'file_parent'} = unquote($2);6233}6234my$linenr_commit=6235exists($meta->{'parent'}) ?6236$meta->{'parent'} :$full_rev;6237my$linenr_filename=6238exists($meta->{'file_parent'}) ?6239$meta->{'file_parent'} : unquote($meta->{'filename'});6240my$blamed= href(action =>'blame',6241 file_name =>$linenr_filename,6242 hash_base =>$linenr_commit);6243print"<td class=\"linenr\">";6244print$cgi->a({ -href =>"$blamed#l$orig_lineno",6245-class=>"linenr"},6246 esc_html($lineno));6247print"</td>";6248print"<td class=\"pre\">". esc_html($data) ."</td>\n";6249print"</tr>\n";6250}# end while62516252}62536254# footer6255print"</tbody>\n".6256"</table>\n";# class="blame"6257print"</div>\n";# class="blame_body"6258close$fd6259or print"Reading blob failed\n";62606261 git_footer_html();6262}62636264sub git_blame {6265 git_blame_common();6266}62676268sub git_blame_incremental {6269 git_blame_common('incremental');6270}62716272sub git_blame_data {6273 git_blame_common('data');6274}62756276sub git_tags {6277my$head= git_get_head_hash($project);6278 git_header_html();6279 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6280 git_print_header_div('summary',$project);62816282my@tagslist= git_get_tags_list();6283if(@tagslist) {6284 git_tags_body(\@tagslist);6285}6286 git_footer_html();6287}62886289sub git_heads {6290my$head= git_get_head_hash($project);6291 git_header_html();6292 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6293 git_print_header_div('summary',$project);62946295my@headslist= git_get_heads_list();6296if(@headslist) {6297 git_heads_body(\@headslist,$head);6298}6299 git_footer_html();6300}63016302# used both for single remote view and for list of all the remotes6303sub git_remotes {6304 gitweb_check_feature('remote_heads')6305or die_error(403,"Remote heads view is disabled");63066307my$head= git_get_head_hash($project);6308my$remote=$input_params{'hash'};63096310my$remotedata= git_get_remotes_list($remote);6311 die_error(500,"Unable to get remote information")unlessdefined$remotedata;63126313unless(%$remotedata) {6314 die_error(404,defined$remote?6315"Remote$remotenot found":6316"No remotes found");6317}63186319 git_header_html(undef,undef, -action_extra =>$remote);6320 git_print_page_nav('','',$head,undef,$head,6321 format_ref_views($remote?'':'remotes'));63226323 fill_remote_heads($remotedata);6324if(defined$remote) {6325 git_print_header_div('remotes',"$remoteremote for$project");6326 git_remote_block($remote,$remotedata->{$remote},undef,$head);6327}else{6328 git_print_header_div('summary',"$projectremotes");6329 git_remotes_body($remotedata,undef,$head);6330}63316332 git_footer_html();6333}63346335sub git_blob_plain {6336my$type=shift;6337my$expires;63386339if(!defined$hash) {6340if(defined$file_name) {6341my$base=$hash_base|| git_get_head_hash($project);6342$hash= git_get_hash_by_path($base,$file_name,"blob")6343or die_error(404,"Cannot find file");6344}else{6345 die_error(400,"No file name defined");6346}6347}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6348# blobs defined by non-textual hash id's can be cached6349$expires="+1d";6350}63516352open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6353or die_error(500,"Open git-cat-file blob '$hash' failed");63546355# content-type (can include charset)6356$type= blob_contenttype($fd,$file_name,$type);63576358# "save as" filename, even when no $file_name is given6359my$save_as="$hash";6360if(defined$file_name) {6361$save_as=$file_name;6362}elsif($type=~m/^text\//) {6363$save_as.='.txt';6364}63656366# With XSS prevention on, blobs of all types except a few known safe6367# ones are served with "Content-Disposition: attachment" to make sure6368# they don't run in our security domain. For certain image types,6369# blob view writes an <img> tag referring to blob_plain view, and we6370# want to be sure not to break that by serving the image as an6371# attachment (though Firefox 3 doesn't seem to care).6372my$sandbox=$prevent_xss&&6373$type!~m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;63746375# serve text/* as text/plain6376if($prevent_xss&&6377($type=~m!^text/[a-z]+\b(.*)$!||6378($type=~m!^[a-z]+/[a-z]\+xml\b(.*)$!&& -T $fd))) {6379my$rest=$1;6380$rest=defined$rest?$rest:'';6381$type="text/plain$rest";6382}63836384print$cgi->header(6385-type =>$type,6386-expires =>$expires,6387-content_disposition =>6388($sandbox?'attachment':'inline')6389.'; filename="'.$save_as.'"');6390local$/=undef;6391binmode STDOUT,':raw';6392print<$fd>;6393binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6394close$fd;6395}63966397sub git_blob {6398my$expires;63996400if(!defined$hash) {6401if(defined$file_name) {6402my$base=$hash_base|| git_get_head_hash($project);6403$hash= git_get_hash_by_path($base,$file_name,"blob")6404or die_error(404,"Cannot find file");6405}else{6406 die_error(400,"No file name defined");6407}6408}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6409# blobs defined by non-textual hash id's can be cached6410$expires="+1d";6411}64126413my$have_blame= gitweb_check_feature('blame');6414open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6415or die_error(500,"Couldn't cat$file_name,$hash");6416my$mimetype= blob_mimetype($fd,$file_name);6417# use 'blob_plain' (aka 'raw') view for files that cannot be displayed6418if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {6419close$fd;6420return git_blob_plain($mimetype);6421}6422# we can have blame only for text/* mimetype6423$have_blame&&= ($mimetype=~m!^text/!);64246425my$highlight= gitweb_check_feature('highlight');6426my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);6427$fd= run_highlighter($fd,$highlight,$syntax)6428if$syntax;64296430 git_header_html(undef,$expires);6431my$formats_nav='';6432if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6433if(defined$file_name) {6434if($have_blame) {6435$formats_nav.=6436$cgi->a({-href => href(action=>"blame", -replay=>1)},6437"blame") .6438" | ";6439}6440$formats_nav.=6441$cgi->a({-href => href(action=>"history", -replay=>1)},6442"history") .6443" | ".6444$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6445"raw") .6446" | ".6447$cgi->a({-href => href(action=>"blob",6448 hash_base=>"HEAD", file_name=>$file_name)},6449"HEAD");6450}else{6451$formats_nav.=6452$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6453"raw");6454}6455 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6456 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6457}else{6458print"<div class=\"page_nav\">\n".6459"<br/><br/></div>\n".6460"<div class=\"title\">".esc_html($hash)."</div>\n";6461}6462 git_print_page_path($file_name,"blob",$hash_base);6463print"<div class=\"page_body\">\n";6464if($mimetype=~m!^image/!) {6465print qq!<img type="!.esc_attr($mimetype).qq!"!;6466if($file_name) {6467print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;6468}6469print qq! src="! .6470 href(action=>"blob_plain", hash=>$hash,6471 hash_base=>$hash_base, file_name=>$file_name) .6472 qq!"/>\n!;6473}else{6474my$nr;6475while(my$line= <$fd>) {6476chomp$line;6477$nr++;6478$line= untabify($line);6479printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,6480$nr, esc_attr(href(-replay =>1)),$nr,$nr,$syntax? to_utf8($line) : esc_html($line, -nbsp=>1);6481}6482}6483close$fd6484or print"Reading blob failed.\n";6485print"</div>";6486 git_footer_html();6487}64886489sub git_tree {6490if(!defined$hash_base) {6491$hash_base="HEAD";6492}6493if(!defined$hash) {6494if(defined$file_name) {6495$hash= git_get_hash_by_path($hash_base,$file_name,"tree");6496}else{6497$hash=$hash_base;6498}6499}6500 die_error(404,"No such tree")unlessdefined($hash);65016502my$show_sizes= gitweb_check_feature('show-sizes');6503my$have_blame= gitweb_check_feature('blame');65046505my@entries= ();6506{6507local$/="\0";6508open my$fd,"-|", git_cmd(),"ls-tree",'-z',6509($show_sizes?'-l': ()),@extra_options,$hash6510or die_error(500,"Open git-ls-tree failed");6511@entries=map{chomp;$_} <$fd>;6512close$fd6513or die_error(404,"Reading tree failed");6514}65156516my$refs= git_get_references();6517my$ref= format_ref_marker($refs,$hash_base);6518 git_header_html();6519my$basedir='';6520if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6521my@views_nav= ();6522if(defined$file_name) {6523push@views_nav,6524$cgi->a({-href => href(action=>"history", -replay=>1)},6525"history"),6526$cgi->a({-href => href(action=>"tree",6527 hash_base=>"HEAD", file_name=>$file_name)},6528"HEAD"),6529}6530my$snapshot_links= format_snapshot_links($hash);6531if(defined$snapshot_links) {6532# FIXME: Should be available when we have no hash base as well.6533push@views_nav,$snapshot_links;6534}6535 git_print_page_nav('tree','',$hash_base,undef,undef,6536join(' | ',@views_nav));6537 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);6538}else{6539undef$hash_base;6540print"<div class=\"page_nav\">\n";6541print"<br/><br/></div>\n";6542print"<div class=\"title\">".esc_html($hash)."</div>\n";6543}6544if(defined$file_name) {6545$basedir=$file_name;6546if($basedirne''&&substr($basedir, -1)ne'/') {6547$basedir.='/';6548}6549 git_print_page_path($file_name,'tree',$hash_base);6550}6551print"<div class=\"page_body\">\n";6552print"<table class=\"tree\">\n";6553my$alternate=1;6554# '..' (top directory) link if possible6555if(defined$hash_base&&6556defined$file_name&&$file_name=~m![^/]+$!) {6557if($alternate) {6558print"<tr class=\"dark\">\n";6559}else{6560print"<tr class=\"light\">\n";6561}6562$alternate^=1;65636564my$up=$file_name;6565$up=~s!/?[^/]+$!!;6566undef$upunless$up;6567# based on git_print_tree_entry6568print'<td class="mode">'. mode_str('040000') ."</td>\n";6569print'<td class="size"> </td>'."\n"if$show_sizes;6570print'<td class="list">';6571print$cgi->a({-href => href(action=>"tree",6572 hash_base=>$hash_base,6573 file_name=>$up)},6574"..");6575print"</td>\n";6576print"<td class=\"link\"></td>\n";65776578print"</tr>\n";6579}6580foreachmy$line(@entries) {6581my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);65826583if($alternate) {6584print"<tr class=\"dark\">\n";6585}else{6586print"<tr class=\"light\">\n";6587}6588$alternate^=1;65896590 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);65916592print"</tr>\n";6593}6594print"</table>\n".6595"</div>";6596 git_footer_html();6597}65986599sub snapshot_name {6600my($project,$hash) =@_;66016602# path/to/project.git -> project6603# path/to/project/.git -> project6604my$name= to_utf8($project);6605$name=~ s,([^/])/*\.git$,$1,;6606$name= basename($name);6607# sanitize name6608$name=~s/[[:cntrl:]]/?/g;66096610my$ver=$hash;6611if($hash=~/^[0-9a-fA-F]+$/) {6612# shorten SHA-1 hash6613my$full_hash= git_get_full_hash($project,$hash);6614if($full_hash=~/^$hash/&&length($hash) >7) {6615$ver= git_get_short_hash($project,$hash);6616}6617}elsif($hash=~m!^refs/tags/(.*)$!) {6618# tags don't need shortened SHA-1 hash6619$ver=$1;6620}else{6621# branches and other need shortened SHA-1 hash6622if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {6623$ver=$1;6624}6625$ver.='-'. git_get_short_hash($project,$hash);6626}6627# in case of hierarchical branch names6628$ver=~s!/!.!g;66296630# name = project-version_string6631$name="$name-$ver";66326633returnwantarray? ($name,$name) :$name;6634}66356636sub git_snapshot {6637my$format=$input_params{'snapshot_format'};6638if(!@snapshot_fmts) {6639 die_error(403,"Snapshots not allowed");6640}6641# default to first supported snapshot format6642$format||=$snapshot_fmts[0];6643if($format!~m/^[a-z0-9]+$/) {6644 die_error(400,"Invalid snapshot format parameter");6645}elsif(!exists($known_snapshot_formats{$format})) {6646 die_error(400,"Unknown snapshot format");6647}elsif($known_snapshot_formats{$format}{'disabled'}) {6648 die_error(403,"Snapshot format not allowed");6649}elsif(!grep($_eq$format,@snapshot_fmts)) {6650 die_error(403,"Unsupported snapshot format");6651}66526653my$type= git_get_type("$hash^{}");6654if(!$type) {6655 die_error(404,'Object does not exist');6656}elsif($typeeq'blob') {6657 die_error(400,'Object is not a tree-ish');6658}66596660my($name,$prefix) = snapshot_name($project,$hash);6661my$filename="$name$known_snapshot_formats{$format}{'suffix'}";6662my$cmd= quote_command(6663 git_cmd(),'archive',6664"--format=$known_snapshot_formats{$format}{'format'}",6665"--prefix=$prefix/",$hash);6666if(exists$known_snapshot_formats{$format}{'compressor'}) {6667$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});6668}66696670$filename=~s/(["\\])/\\$1/g;6671print$cgi->header(6672-type =>$known_snapshot_formats{$format}{'type'},6673-content_disposition =>'inline; filename="'.$filename.'"',6674-status =>'200 OK');66756676open my$fd,"-|",$cmd6677or die_error(500,"Execute git-archive failed");6678binmode STDOUT,':raw';6679print<$fd>;6680binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6681close$fd;6682}66836684sub git_log_generic {6685my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;66866687my$head= git_get_head_hash($project);6688if(!defined$base) {6689$base=$head;6690}6691if(!defined$page) {6692$page=0;6693}6694my$refs= git_get_references();66956696my$commit_hash=$base;6697if(defined$parent) {6698$commit_hash="$parent..$base";6699}6700my@commitlist=6701 parse_commits($commit_hash,101, (100*$page),6702defined$file_name? ($file_name,"--full-history") : ());67036704my$ftype;6705if(!defined$file_hash&&defined$file_name) {6706# some commits could have deleted file in question,6707# and not have it in tree, but one of them has to have it6708for(my$i=0;$i<@commitlist;$i++) {6709$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);6710last ifdefined$file_hash;6711}6712}6713if(defined$file_hash) {6714$ftype= git_get_type($file_hash);6715}6716if(defined$file_name&& !defined$ftype) {6717 die_error(500,"Unknown type of object");6718}6719my%co;6720if(defined$file_name) {6721%co= parse_commit($base)6722or die_error(404,"Unknown commit object");6723}672467256726my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);6727my$next_link='';6728if($#commitlist>=100) {6729$next_link=6730$cgi->a({-href => href(-replay=>1, page=>$page+1),6731-accesskey =>"n", -title =>"Alt-n"},"next");6732}6733my$patch_max= gitweb_get_feature('patches');6734if($patch_max&& !defined$file_name) {6735if($patch_max<0||@commitlist<=$patch_max) {6736$paging_nav.=" ⋅ ".6737$cgi->a({-href => href(action=>"patches", -replay=>1)},6738"patches");6739}6740}67416742 git_header_html();6743 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);6744if(defined$file_name) {6745 git_print_header_div('commit', esc_html($co{'title'}),$base);6746}else{6747 git_print_header_div('summary',$project)6748}6749 git_print_page_path($file_name,$ftype,$hash_base)6750if(defined$file_name);67516752$body_subr->(\@commitlist,0,99,$refs,$next_link,6753$file_name,$file_hash,$ftype);67546755 git_footer_html();6756}67576758sub git_log {6759 git_log_generic('log', \&git_log_body,6760$hash,$hash_parent);6761}67626763sub git_commit {6764$hash||=$hash_base||"HEAD";6765my%co= parse_commit($hash)6766or die_error(404,"Unknown commit object");67676768my$parent=$co{'parent'};6769my$parents=$co{'parents'};# listref67706771# we need to prepare $formats_nav before any parameter munging6772my$formats_nav;6773if(!defined$parent) {6774# --root commitdiff6775$formats_nav.='(initial)';6776}elsif(@$parents==1) {6777# single parent commit6778$formats_nav.=6779'(parent: '.6780$cgi->a({-href => href(action=>"commit",6781 hash=>$parent)},6782 esc_html(substr($parent,0,7))) .6783')';6784}else{6785# merge commit6786$formats_nav.=6787'(merge: '.6788join(' ',map{6789$cgi->a({-href => href(action=>"commit",6790 hash=>$_)},6791 esc_html(substr($_,0,7)));6792}@$parents) .6793')';6794}6795if(gitweb_check_feature('patches') &&@$parents<=1) {6796$formats_nav.=" | ".6797$cgi->a({-href => href(action=>"patch", -replay=>1)},6798"patch");6799}68006801if(!defined$parent) {6802$parent="--root";6803}6804my@difftree;6805open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",6806@diff_opts,6807(@$parents<=1?$parent:'-c'),6808$hash,"--"6809or die_error(500,"Open git-diff-tree failed");6810@difftree=map{chomp;$_} <$fd>;6811close$fdor die_error(404,"Reading git-diff-tree failed");68126813# non-textual hash id's can be cached6814my$expires;6815if($hash=~m/^[0-9a-fA-F]{40}$/) {6816$expires="+1d";6817}6818my$refs= git_get_references();6819my$ref= format_ref_marker($refs,$co{'id'});68206821 git_header_html(undef,$expires);6822 git_print_page_nav('commit','',6823$hash,$co{'tree'},$hash,6824$formats_nav);68256826if(defined$co{'parent'}) {6827 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);6828}else{6829 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);6830}6831print"<div class=\"title_text\">\n".6832"<table class=\"object_header\">\n";6833 git_print_authorship_rows(\%co);6834print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";6835print"<tr>".6836"<td>tree</td>".6837"<td class=\"sha1\">".6838$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),6839class=>"list"},$co{'tree'}) .6840"</td>".6841"<td class=\"link\">".6842$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},6843"tree");6844my$snapshot_links= format_snapshot_links($hash);6845if(defined$snapshot_links) {6846print" | ".$snapshot_links;6847}6848print"</td>".6849"</tr>\n";68506851foreachmy$par(@$parents) {6852print"<tr>".6853"<td>parent</td>".6854"<td class=\"sha1\">".6855$cgi->a({-href => href(action=>"commit", hash=>$par),6856class=>"list"},$par) .6857"</td>".6858"<td class=\"link\">".6859$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .6860" | ".6861$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .6862"</td>".6863"</tr>\n";6864}6865print"</table>".6866"</div>\n";68676868print"<div class=\"page_body\">\n";6869 git_print_log($co{'comment'});6870print"</div>\n";68716872 git_difftree_body(\@difftree,$hash,@$parents);68736874 git_footer_html();6875}68766877sub git_object {6878# object is defined by:6879# - hash or hash_base alone6880# - hash_base and file_name6881my$type;68826883# - hash or hash_base alone6884if($hash|| ($hash_base&& !defined$file_name)) {6885my$object_id=$hash||$hash_base;68866887open my$fd,"-|", quote_command(6888 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'6889or die_error(404,"Object does not exist");6890$type= <$fd>;6891chomp$type;6892close$fd6893or die_error(404,"Object does not exist");68946895# - hash_base and file_name6896}elsif($hash_base&&defined$file_name) {6897$file_name=~ s,/+$,,;68986899system(git_cmd(),"cat-file",'-e',$hash_base) ==06900or die_error(404,"Base object does not exist");69016902# here errors should not hapen6903open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name6904or die_error(500,"Open git-ls-tree failed");6905my$line= <$fd>;6906close$fd;69076908#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'6909unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {6910 die_error(404,"File or directory for given base does not exist");6911}6912$type=$2;6913$hash=$3;6914}else{6915 die_error(400,"Not enough information to find object");6916}69176918print$cgi->redirect(-uri => href(action=>$type, -full=>1,6919 hash=>$hash, hash_base=>$hash_base,6920 file_name=>$file_name),6921-status =>'302 Found');6922}69236924sub git_blobdiff {6925my$format=shift||'html';69266927my$fd;6928my@difftree;6929my%diffinfo;6930my$expires;69316932# preparing $fd and %diffinfo for git_patchset_body6933# new style URI6934if(defined$hash_base&&defined$hash_parent_base) {6935if(defined$file_name) {6936# read raw output6937open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6938$hash_parent_base,$hash_base,6939"--", (defined$file_parent?$file_parent: ()),$file_name6940or die_error(500,"Open git-diff-tree failed");6941@difftree=map{chomp;$_} <$fd>;6942close$fd6943or die_error(404,"Reading git-diff-tree failed");6944@difftree6945or die_error(404,"Blob diff not found");69466947}elsif(defined$hash&&6948$hash=~/[0-9a-fA-F]{40}/) {6949# try to find filename from $hash69506951# read filtered raw output6952open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6953$hash_parent_base,$hash_base,"--"6954or die_error(500,"Open git-diff-tree failed");6955@difftree=6956# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'6957# $hash == to_id6958grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}6959map{chomp;$_} <$fd>;6960close$fd6961or die_error(404,"Reading git-diff-tree failed");6962@difftree6963or die_error(404,"Blob diff not found");69646965}else{6966 die_error(400,"Missing one of the blob diff parameters");6967}69686969if(@difftree>1) {6970 die_error(400,"Ambiguous blob diff specification");6971}69726973%diffinfo= parse_difftree_raw_line($difftree[0]);6974$file_parent||=$diffinfo{'from_file'} ||$file_name;6975$file_name||=$diffinfo{'to_file'};69766977$hash_parent||=$diffinfo{'from_id'};6978$hash||=$diffinfo{'to_id'};69796980# non-textual hash id's can be cached6981if($hash_base=~m/^[0-9a-fA-F]{40}$/&&6982$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {6983$expires='+1d';6984}69856986# open patch output6987open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6988'-p', ($formateq'html'?"--full-index": ()),6989$hash_parent_base,$hash_base,6990"--", (defined$file_parent?$file_parent: ()),$file_name6991or die_error(500,"Open git-diff-tree failed");6992}69936994# old/legacy style URI -- not generated anymore since 1.4.3.6995if(!%diffinfo) {6996 die_error('404 Not Found',"Missing one of the blob diff parameters")6997}69986999# header7000if($formateq'html') {7001my$formats_nav=7002$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},7003"raw");7004 git_header_html(undef,$expires);7005if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7006 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7007 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7008}else{7009print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";7010print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";7011}7012if(defined$file_name) {7013 git_print_page_path($file_name,"blob",$hash_base);7014}else{7015print"<div class=\"page_path\"></div>\n";7016}70177018}elsif($formateq'plain') {7019print$cgi->header(7020-type =>'text/plain',7021-charset =>'utf-8',7022-expires =>$expires,7023-content_disposition =>'inline; filename="'."$file_name".'.patch"');70247025print"X-Git-Url: ".$cgi->self_url() ."\n\n";70267027}else{7028 die_error(400,"Unknown blobdiff format");7029}70307031# patch7032if($formateq'html') {7033print"<div class=\"page_body\">\n";70347035 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);7036close$fd;70377038print"</div>\n";# class="page_body"7039 git_footer_html();70407041}else{7042while(my$line= <$fd>) {7043$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;7044$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;70457046print$line;70477048last if$line=~m!^\+\+\+!;7049}7050local$/=undef;7051print<$fd>;7052close$fd;7053}7054}70557056sub git_blobdiff_plain {7057 git_blobdiff('plain');7058}70597060sub git_commitdiff {7061my%params=@_;7062my$format=$params{-format} ||'html';70637064my($patch_max) = gitweb_get_feature('patches');7065if($formateq'patch') {7066 die_error(403,"Patch view not allowed")unless$patch_max;7067}70687069$hash||=$hash_base||"HEAD";7070my%co= parse_commit($hash)7071or die_error(404,"Unknown commit object");70727073# choose format for commitdiff for merge7074if(!defined$hash_parent&& @{$co{'parents'}} >1) {7075$hash_parent='--cc';7076}7077# we need to prepare $formats_nav before almost any parameter munging7078my$formats_nav;7079if($formateq'html') {7080$formats_nav=7081$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},7082"raw");7083if($patch_max&& @{$co{'parents'}} <=1) {7084$formats_nav.=" | ".7085$cgi->a({-href => href(action=>"patch", -replay=>1)},7086"patch");7087}70887089if(defined$hash_parent&&7090$hash_parentne'-c'&&$hash_parentne'--cc') {7091# commitdiff with two commits given7092my$hash_parent_short=$hash_parent;7093if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {7094$hash_parent_short=substr($hash_parent,0,7);7095}7096$formats_nav.=7097' (from';7098for(my$i=0;$i< @{$co{'parents'}};$i++) {7099if($co{'parents'}[$i]eq$hash_parent) {7100$formats_nav.=' parent '. ($i+1);7101last;7102}7103}7104$formats_nav.=': '.7105$cgi->a({-href => href(action=>"commitdiff",7106 hash=>$hash_parent)},7107 esc_html($hash_parent_short)) .7108')';7109}elsif(!$co{'parent'}) {7110# --root commitdiff7111$formats_nav.=' (initial)';7112}elsif(scalar@{$co{'parents'}} ==1) {7113# single parent commit7114$formats_nav.=7115' (parent: '.7116$cgi->a({-href => href(action=>"commitdiff",7117 hash=>$co{'parent'})},7118 esc_html(substr($co{'parent'},0,7))) .7119')';7120}else{7121# merge commit7122if($hash_parenteq'--cc') {7123$formats_nav.=' | '.7124$cgi->a({-href => href(action=>"commitdiff",7125 hash=>$hash, hash_parent=>'-c')},7126'combined');7127}else{# $hash_parent eq '-c'7128$formats_nav.=' | '.7129$cgi->a({-href => href(action=>"commitdiff",7130 hash=>$hash, hash_parent=>'--cc')},7131'compact');7132}7133$formats_nav.=7134' (merge: '.7135join(' ',map{7136$cgi->a({-href => href(action=>"commitdiff",7137 hash=>$_)},7138 esc_html(substr($_,0,7)));7139} @{$co{'parents'}} ) .7140')';7141}7142}71437144my$hash_parent_param=$hash_parent;7145if(!defined$hash_parent_param) {7146# --cc for multiple parents, --root for parentless7147$hash_parent_param=7148@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';7149}71507151# read commitdiff7152my$fd;7153my@difftree;7154if($formateq'html') {7155open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7156"--no-commit-id","--patch-with-raw","--full-index",7157$hash_parent_param,$hash,"--"7158or die_error(500,"Open git-diff-tree failed");71597160while(my$line= <$fd>) {7161chomp$line;7162# empty line ends raw part of diff-tree output7163last unless$line;7164push@difftree,scalar parse_difftree_raw_line($line);7165}71667167}elsif($formateq'plain') {7168open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7169'-p',$hash_parent_param,$hash,"--"7170or die_error(500,"Open git-diff-tree failed");7171}elsif($formateq'patch') {7172# For commit ranges, we limit the output to the number of7173# patches specified in the 'patches' feature.7174# For single commits, we limit the output to a single patch,7175# diverging from the git-format-patch default.7176my@commit_spec= ();7177if($hash_parent) {7178if($patch_max>0) {7179push@commit_spec,"-$patch_max";7180}7181push@commit_spec,'-n',"$hash_parent..$hash";7182}else{7183if($params{-single}) {7184push@commit_spec,'-1';7185}else{7186if($patch_max>0) {7187push@commit_spec,"-$patch_max";7188}7189push@commit_spec,"-n";7190}7191push@commit_spec,'--root',$hash;7192}7193open$fd,"-|", git_cmd(),"format-patch",@diff_opts,7194'--encoding=utf8','--stdout',@commit_spec7195or die_error(500,"Open git-format-patch failed");7196}else{7197 die_error(400,"Unknown commitdiff format");7198}71997200# non-textual hash id's can be cached7201my$expires;7202if($hash=~m/^[0-9a-fA-F]{40}$/) {7203$expires="+1d";7204}72057206# write commit message7207if($formateq'html') {7208my$refs= git_get_references();7209my$ref= format_ref_marker($refs,$co{'id'});72107211 git_header_html(undef,$expires);7212 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);7213 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);7214print"<div class=\"title_text\">\n".7215"<table class=\"object_header\">\n";7216 git_print_authorship_rows(\%co);7217print"</table>".7218"</div>\n";7219print"<div class=\"page_body\">\n";7220if(@{$co{'comment'}} >1) {7221print"<div class=\"log\">\n";7222 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);7223print"</div>\n";# class="log"7224}72257226}elsif($formateq'plain') {7227my$refs= git_get_references("tags");7228my$tagname= git_get_rev_name_tags($hash);7229my$filename= basename($project) ."-$hash.patch";72307231print$cgi->header(7232-type =>'text/plain',7233-charset =>'utf-8',7234-expires =>$expires,7235-content_disposition =>'inline; filename="'."$filename".'"');7236my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});7237print"From: ". to_utf8($co{'author'}) ."\n";7238print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";7239print"Subject: ". to_utf8($co{'title'}) ."\n";72407241print"X-Git-Tag:$tagname\n"if$tagname;7242print"X-Git-Url: ".$cgi->self_url() ."\n\n";72437244foreachmy$line(@{$co{'comment'}}) {7245print to_utf8($line) ."\n";7246}7247print"---\n\n";7248}elsif($formateq'patch') {7249my$filename= basename($project) ."-$hash.patch";72507251print$cgi->header(7252-type =>'text/plain',7253-charset =>'utf-8',7254-expires =>$expires,7255-content_disposition =>'inline; filename="'."$filename".'"');7256}72577258# write patch7259if($formateq'html') {7260my$use_parents= !defined$hash_parent||7261$hash_parenteq'-c'||$hash_parenteq'--cc';7262 git_difftree_body(\@difftree,$hash,7263$use_parents? @{$co{'parents'}} :$hash_parent);7264print"<br/>\n";72657266 git_patchset_body($fd, \@difftree,$hash,7267$use_parents? @{$co{'parents'}} :$hash_parent);7268close$fd;7269print"</div>\n";# class="page_body"7270 git_footer_html();72717272}elsif($formateq'plain') {7273local$/=undef;7274print<$fd>;7275close$fd7276or print"Reading git-diff-tree failed\n";7277}elsif($formateq'patch') {7278local$/=undef;7279print<$fd>;7280close$fd7281or print"Reading git-format-patch failed\n";7282}7283}72847285sub git_commitdiff_plain {7286 git_commitdiff(-format =>'plain');7287}72887289# format-patch-style patches7290sub git_patch {7291 git_commitdiff(-format =>'patch', -single =>1);7292}72937294sub git_patches {7295 git_commitdiff(-format =>'patch');7296}72977298sub git_history {7299 git_log_generic('history', \&git_history_body,7300$hash_base,$hash_parent_base,7301$file_name,$hash);7302}73037304sub git_search {7305$searchtype||='commit';73067307# check if appropriate features are enabled7308 gitweb_check_feature('search')7309or die_error(403,"Search is disabled");7310if($searchtypeeq'pickaxe') {7311# pickaxe may take all resources of your box and run for several minutes7312# with every query - so decide by yourself how public you make this feature7313 gitweb_check_feature('pickaxe')7314or die_error(403,"Pickaxe search is disabled");7315}7316if($searchtypeeq'grep') {7317# grep search might be potentially CPU-intensive, too7318 gitweb_check_feature('grep')7319or die_error(403,"Grep search is disabled");7320}73217322if(!defined$searchtext) {7323 die_error(400,"Text field is empty");7324}7325if(!defined$hash) {7326$hash= git_get_head_hash($project);7327}7328my%co= parse_commit($hash);7329if(!%co) {7330 die_error(404,"Unknown commit object");7331}7332if(!defined$page) {7333$page=0;7334}73357336if($searchtypeeq'commit'||7337$searchtypeeq'author'||7338$searchtypeeq'committer') {7339 git_search_message(%co);7340}elsif($searchtypeeq'pickaxe') {7341 git_search_changes(%co);7342}elsif($searchtypeeq'grep') {7343 git_search_files(%co);7344}else{7345 die_error(400,"Unknown search type");7346}7347}73487349sub git_search_help {7350 git_header_html();7351 git_print_page_nav('','',$hash,$hash,$hash);7352print<<EOT;7353<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without7354regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,7355the pattern entered is recognized as the POSIX extended7356<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case7357insensitive).</p>7358<dl>7359<dt><b>commit</b></dt>7360<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>7361EOT7362my$have_grep= gitweb_check_feature('grep');7363if($have_grep) {7364print<<EOT;7365<dt><b>grep</b></dt>7366<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing7367 a different one) are searched for the given pattern. On large trees, this search can take7368a while and put some strain on the server, so please use it with some consideration. Note that7369due to git-grep peculiarity, currently if regexp mode is turned off, the matches are7370case-sensitive.</dd>7371EOT7372}7373print<<EOT;7374<dt><b>author</b></dt>7375<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>7376<dt><b>committer</b></dt>7377<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>7378EOT7379my$have_pickaxe= gitweb_check_feature('pickaxe');7380if($have_pickaxe) {7381print<<EOT;7382<dt><b>pickaxe</b></dt>7383<dd>All commits that caused the string to appear or disappear from any file (changes that7384added, removed or "modified" the string) will be listed. This search can take a while and7385takes a lot of strain on the server, so please use it wisely. Note that since you may be7386interested even in changes just changing the case as well, this search is case sensitive.</dd>7387EOT7388}7389print"</dl>\n";7390 git_footer_html();7391}73927393sub git_shortlog {7394 git_log_generic('shortlog', \&git_shortlog_body,7395$hash,$hash_parent);7396}73977398## ......................................................................7399## feeds (RSS, Atom; OPML)74007401sub git_feed {7402my$format=shift||'atom';7403my$have_blame= gitweb_check_feature('blame');74047405# Atom: http://www.atomenabled.org/developers/syndication/7406# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ7407if($formatne'rss'&&$formatne'atom') {7408 die_error(400,"Unknown web feed format");7409}74107411# log/feed of current (HEAD) branch, log of given branch, history of file/directory7412my$head=$hash||'HEAD';7413my@commitlist= parse_commits($head,150,0,$file_name);74147415my%latest_commit;7416my%latest_date;7417my$content_type="application/$format+xml";7418if(defined$cgi->http('HTTP_ACCEPT') &&7419$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {7420# browser (feed reader) prefers text/xml7421$content_type='text/xml';7422}7423if(defined($commitlist[0])) {7424%latest_commit= %{$commitlist[0]};7425my$latest_epoch=$latest_commit{'committer_epoch'};7426%latest_date= parse_date($latest_epoch,$latest_commit{'comitter_tz'});7427my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7428if(defined$if_modified) {7429my$since;7430if(eval{require HTTP::Date;1; }) {7431$since= HTTP::Date::str2time($if_modified);7432}elsif(eval{require Time::ParseDate;1; }) {7433$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7434}7435if(defined$since&&$latest_epoch<=$since) {7436print$cgi->header(7437-type =>$content_type,7438-charset =>'utf-8',7439-last_modified =>$latest_date{'rfc2822'},7440-status =>'304 Not Modified');7441return;7442}7443}7444print$cgi->header(7445-type =>$content_type,7446-charset =>'utf-8',7447-last_modified =>$latest_date{'rfc2822'});7448}else{7449print$cgi->header(7450-type =>$content_type,7451-charset =>'utf-8');7452}74537454# Optimization: skip generating the body if client asks only7455# for Last-Modified date.7456return if($cgi->request_method()eq'HEAD');74577458# header variables7459my$title="$site_name-$project/$action";7460my$feed_type='log';7461if(defined$hash) {7462$title.=" - '$hash'";7463$feed_type='branch log';7464if(defined$file_name) {7465$title.=" ::$file_name";7466$feed_type='history';7467}7468}elsif(defined$file_name) {7469$title.=" -$file_name";7470$feed_type='history';7471}7472$title.="$feed_type";7473my$descr= git_get_project_description($project);7474if(defined$descr) {7475$descr= esc_html($descr);7476}else{7477$descr="$project".7478($formateq'rss'?'RSS':'Atom') .7479" feed";7480}7481my$owner= git_get_project_owner($project);7482$owner= esc_html($owner);74837484#header7485my$alt_url;7486if(defined$file_name) {7487$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);7488}elsif(defined$hash) {7489$alt_url= href(-full=>1, action=>"log", hash=>$hash);7490}else{7491$alt_url= href(-full=>1, action=>"summary");7492}7493print qq!<?xml version="1.0" encoding="utf-8"?>\n!;7494if($formateq'rss') {7495print<<XML;7496<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">7497<channel>7498XML7499print"<title>$title</title>\n".7500"<link>$alt_url</link>\n".7501"<description>$descr</description>\n".7502"<language>en</language>\n".7503# project owner is responsible for 'editorial' content7504"<managingEditor>$owner</managingEditor>\n";7505if(defined$logo||defined$favicon) {7506# prefer the logo to the favicon, since RSS7507# doesn't allow both7508my$img= esc_url($logo||$favicon);7509print"<image>\n".7510"<url>$img</url>\n".7511"<title>$title</title>\n".7512"<link>$alt_url</link>\n".7513"</image>\n";7514}7515if(%latest_date) {7516print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";7517print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";7518}7519print"<generator>gitweb v.$version/$git_version</generator>\n";7520}elsif($formateq'atom') {7521print<<XML;7522<feed xmlns="http://www.w3.org/2005/Atom">7523XML7524print"<title>$title</title>\n".7525"<subtitle>$descr</subtitle>\n".7526'<link rel="alternate" type="text/html" href="'.7527$alt_url.'" />'."\n".7528'<link rel="self" type="'.$content_type.'" href="'.7529$cgi->self_url() .'" />'."\n".7530"<id>". href(-full=>1) ."</id>\n".7531# use project owner for feed author7532"<author><name>$owner</name></author>\n";7533if(defined$favicon) {7534print"<icon>". esc_url($favicon) ."</icon>\n";7535}7536if(defined$logo) {7537# not twice as wide as tall: 72 x 27 pixels7538print"<logo>". esc_url($logo) ."</logo>\n";7539}7540if(!%latest_date) {7541# dummy date to keep the feed valid until commits trickle in:7542print"<updated>1970-01-01T00:00:00Z</updated>\n";7543}else{7544print"<updated>$latest_date{'iso-8601'}</updated>\n";7545}7546print"<generator version='$version/$git_version'>gitweb</generator>\n";7547}75487549# contents7550for(my$i=0;$i<=$#commitlist;$i++) {7551my%co= %{$commitlist[$i]};7552my$commit=$co{'id'};7553# we read 150, we always show 30 and the ones more recent than 48 hours7554if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {7555last;7556}7557my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});75587559# get list of changed files7560open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7561$co{'parent'} ||"--root",7562$co{'id'},"--", (defined$file_name?$file_name: ())7563ornext;7564my@difftree=map{chomp;$_} <$fd>;7565close$fd7566ornext;75677568# print element (entry, item)7569my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);7570if($formateq'rss') {7571print"<item>\n".7572"<title>". esc_html($co{'title'}) ."</title>\n".7573"<author>". esc_html($co{'author'}) ."</author>\n".7574"<pubDate>$cd{'rfc2822'}</pubDate>\n".7575"<guid isPermaLink=\"true\">$co_url</guid>\n".7576"<link>$co_url</link>\n".7577"<description>". esc_html($co{'title'}) ."</description>\n".7578"<content:encoded>".7579"<![CDATA[\n";7580}elsif($formateq'atom') {7581print"<entry>\n".7582"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".7583"<updated>$cd{'iso-8601'}</updated>\n".7584"<author>\n".7585" <name>". esc_html($co{'author_name'}) ."</name>\n";7586if($co{'author_email'}) {7587print" <email>". esc_html($co{'author_email'}) ."</email>\n";7588}7589print"</author>\n".7590# use committer for contributor7591"<contributor>\n".7592" <name>". esc_html($co{'committer_name'}) ."</name>\n";7593if($co{'committer_email'}) {7594print" <email>". esc_html($co{'committer_email'}) ."</email>\n";7595}7596print"</contributor>\n".7597"<published>$cd{'iso-8601'}</published>\n".7598"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".7599"<id>$co_url</id>\n".7600"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".7601"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";7602}7603my$comment=$co{'comment'};7604print"<pre>\n";7605foreachmy$line(@$comment) {7606$line= esc_html($line);7607print"$line\n";7608}7609print"</pre><ul>\n";7610foreachmy$difftree_line(@difftree) {7611my%difftree= parse_difftree_raw_line($difftree_line);7612next if!$difftree{'from_id'};76137614my$file=$difftree{'file'} ||$difftree{'to_file'};76157616print"<li>".7617"[".7618$cgi->a({-href => href(-full=>1, action=>"blobdiff",7619 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},7620 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},7621 file_name=>$file, file_parent=>$difftree{'from_file'}),7622-title =>"diff"},'D');7623if($have_blame) {7624print$cgi->a({-href => href(-full=>1, action=>"blame",7625 file_name=>$file, hash_base=>$commit),7626-title =>"blame"},'B');7627}7628# if this is not a feed of a file history7629if(!defined$file_name||$file_namene$file) {7630print$cgi->a({-href => href(-full=>1, action=>"history",7631 file_name=>$file, hash=>$commit),7632-title =>"history"},'H');7633}7634$file= esc_path($file);7635print"] ".7636"$file</li>\n";7637}7638if($formateq'rss') {7639print"</ul>]]>\n".7640"</content:encoded>\n".7641"</item>\n";7642}elsif($formateq'atom') {7643print"</ul>\n</div>\n".7644"</content>\n".7645"</entry>\n";7646}7647}76487649# end of feed7650if($formateq'rss') {7651print"</channel>\n</rss>\n";7652}elsif($formateq'atom') {7653print"</feed>\n";7654}7655}76567657sub git_rss {7658 git_feed('rss');7659}76607661sub git_atom {7662 git_feed('atom');7663}76647665sub git_opml {7666my@list= git_get_projects_list();7667if(!@list) {7668 die_error(404,"No projects found");7669}76707671print$cgi->header(7672-type =>'text/xml',7673-charset =>'utf-8',7674-content_disposition =>'inline; filename="opml.xml"');76757676print<<XML;7677<?xml version="1.0" encoding="utf-8"?>7678<opml version="1.0">7679<head>7680 <title>$site_nameOPML Export</title>7681</head>7682<body>7683<outline text="git RSS feeds">7684XML76857686foreachmy$pr(@list) {7687my%proj=%$pr;7688my$head= git_get_head_hash($proj{'path'});7689if(!defined$head) {7690next;7691}7692$git_dir="$projectroot/$proj{'path'}";7693my%co= parse_commit($head);7694if(!%co) {7695next;7696}76977698my$path= esc_html(chop_str($proj{'path'},25,5));7699my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);7700my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);7701print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";7702}7703print<<XML;7704</outline>7705</body>7706</opml>7707XML7708}