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# only subsection, if exists, is case sensitive,2530# and not lowercased by 'git config -z -l'2531if(my($hi,$mi,$lo) = ($key=~/^([^.]*)\.(.*)\.([^.]*)$/)) {2532$key=join(".",lc($hi),$mi,lc($lo));2533}else{2534$key=lc($key);2535}2536$key=~s/^gitweb\.//;2537return if($key=~m/\W/);25382539# type sanity check2540if(defined$type) {2541$type=~s/^--//;2542$type=undef2543unless($typeeq'bool'||$typeeq'int');2544}25452546# get config2547if(!defined$config_file||2548$config_filene"$git_dir/config") {2549%config= git_parse_project_config('gitweb');2550$config_file="$git_dir/config";2551}25522553# check if config variable (key) exists2554return unlessexists$config{"gitweb.$key"};25552556# ensure given type2557if(!defined$type) {2558return$config{"gitweb.$key"};2559}elsif($typeeq'bool') {2560# backward compatibility: 'git config --bool' returns true/false2561return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2562}elsif($typeeq'int') {2563return config_to_int($config{"gitweb.$key"});2564}2565return$config{"gitweb.$key"};2566}25672568# get hash of given path at given ref2569sub git_get_hash_by_path {2570my$base=shift;2571my$path=shift||returnundef;2572my$type=shift;25732574$path=~ s,/+$,,;25752576open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2577or die_error(500,"Open git-ls-tree failed");2578my$line= <$fd>;2579close$fdorreturnundef;25802581if(!defined$line) {2582# there is no tree or hash given by $path at $base2583returnundef;2584}25852586#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2587$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2588if(defined$type&&$typene$2) {2589# type doesn't match2590returnundef;2591}2592return$3;2593}25942595# get path of entry with given hash at given tree-ish (ref)2596# used to get 'from' filename for combined diff (merge commit) for renames2597sub git_get_path_by_hash {2598my$base=shift||return;2599my$hash=shift||return;26002601local$/="\0";26022603open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2604orreturnundef;2605while(my$line= <$fd>) {2606chomp$line;26072608#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2609#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2610if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2611close$fd;2612return$1;2613}2614}2615close$fd;2616returnundef;2617}26182619## ......................................................................2620## git utility functions, directly accessing git repository26212622# get the value of config variable either from file named as the variable2623# itself in the repository ($GIT_DIR/$name file), or from gitweb.$name2624# configuration variable in the repository config file.2625sub git_get_file_or_project_config {2626my($path,$name) =@_;26272628$git_dir="$projectroot/$path";2629open my$fd,'<',"$git_dir/$name"2630orreturn git_get_project_config($name);2631my$conf= <$fd>;2632close$fd;2633if(defined$conf) {2634chomp$conf;2635}2636return$conf;2637}26382639sub git_get_project_description {2640my$path=shift;2641return git_get_file_or_project_config($path,'description');2642}26432644sub git_get_project_category {2645my$path=shift;2646return git_get_file_or_project_config($path,'category');2647}264826492650# supported formats:2651# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2652# - if its contents is a number, use it as tag weight,2653# - otherwise add a tag with weight 12654# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2655# the same value multiple times increases tag weight2656# * `gitweb.ctag' multi-valued repo config variable2657sub git_get_project_ctags {2658my$project=shift;2659my$ctags= {};26602661$git_dir="$projectroot/$project";2662if(opendir my$dh,"$git_dir/ctags") {2663my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2664foreachmy$tagfile(@files) {2665open my$ct,'<',$tagfile2666ornext;2667my$val= <$ct>;2668chomp$valif$val;2669close$ct;26702671(my$ctag=$tagfile) =~ s#.*/##;2672if($val=~/^\d+$/) {2673$ctags->{$ctag} =$val;2674}else{2675$ctags->{$ctag} =1;2676}2677}2678closedir$dh;26792680}elsif(open my$fh,'<',"$git_dir/ctags") {2681while(my$line= <$fh>) {2682chomp$line;2683$ctags->{$line}++if$line;2684}2685close$fh;26862687}else{2688my$taglist= config_to_multi(git_get_project_config('ctag'));2689foreachmy$tag(@$taglist) {2690$ctags->{$tag}++;2691}2692}26932694return$ctags;2695}26962697# return hash, where keys are content tags ('ctags'),2698# and values are sum of weights of given tag in every project2699sub git_gather_all_ctags {2700my$projects=shift;2701my$ctags= {};27022703foreachmy$p(@$projects) {2704foreachmy$ct(keys%{$p->{'ctags'}}) {2705$ctags->{$ct} +=$p->{'ctags'}->{$ct};2706}2707}27082709return$ctags;2710}27112712sub git_populate_project_tagcloud {2713my$ctags=shift;27142715# First, merge different-cased tags; tags vote on casing2716my%ctags_lc;2717foreach(keys%$ctags) {2718$ctags_lc{lc$_}->{count} +=$ctags->{$_};2719if(not$ctags_lc{lc$_}->{topcount}2720or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2721$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2722$ctags_lc{lc$_}->{topname} =$_;2723}2724}27252726my$cloud;2727my$matched=$cgi->param('by_tag');2728if(eval{require HTML::TagCloud;1; }) {2729$cloud= HTML::TagCloud->new;2730foreachmy$ctag(sort keys%ctags_lc) {2731# Pad the title with spaces so that the cloud looks2732# less crammed.2733my$title= esc_html($ctags_lc{$ctag}->{topname});2734$title=~s/ / /g;2735$title=~s/^/ /g;2736$title=~s/$/ /g;2737if(defined$matched&&$matchedeq$ctag) {2738$title=qq(<span class="match">$title</span>);2739}2740$cloud->add($title, href(project=>undef, ctag=>$ctag),2741$ctags_lc{$ctag}->{count});2742}2743}else{2744$cloud= {};2745foreachmy$ctag(keys%ctags_lc) {2746my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2747if(defined$matched&&$matchedeq$ctag) {2748$title=qq(<span class="match">$title</span>);2749}2750$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};2751$cloud->{$ctag}{ctag} =2752$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);2753}2754}2755return$cloud;2756}27572758sub git_show_project_tagcloud {2759my($cloud,$count) =@_;2760if(ref$cloudeq'HTML::TagCloud') {2761return$cloud->html_and_css($count);2762}else{2763my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;2764return2765'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.2766join(', ',map{2767$cloud->{$_}->{'ctag'}2768}splice(@tags,0,$count)) .2769'</div>';2770}2771}27722773sub git_get_project_url_list {2774my$path=shift;27752776$git_dir="$projectroot/$path";2777open my$fd,'<',"$git_dir/cloneurl"2778orreturnwantarray?2779@{ config_to_multi(git_get_project_config('url')) } :2780 config_to_multi(git_get_project_config('url'));2781my@git_project_url_list=map{chomp;$_} <$fd>;2782close$fd;27832784returnwantarray?@git_project_url_list: \@git_project_url_list;2785}27862787sub git_get_projects_list {2788my$filter=shift||'';2789my@list;27902791$filter=~s/\.git$//;27922793if(-d $projects_list) {2794# search in directory2795my$dir=$projects_list;2796# remove the trailing "/"2797$dir=~s!/+$!!;2798my$pfxlen=length("$projects_list");2799my$pfxdepth= ($projects_list=~tr!/!!);2800# when filtering, search only given subdirectory2801if($filter) {2802$dir.="/$filter";2803$dir=~s!/+$!!;2804}28052806 File::Find::find({2807 follow_fast =>1,# follow symbolic links2808 follow_skip =>2,# ignore duplicates2809 dangling_symlinks =>0,# ignore dangling symlinks, silently2810 wanted =>sub{2811# global variables2812our$project_maxdepth;2813our$projectroot;2814# skip project-list toplevel, if we get it.2815return if(m!^[/.]$!);2816# only directories can be git repositories2817return unless(-d $_);2818# don't traverse too deep (Find is super slow on os x)2819# $project_maxdepth excludes depth of $projectroot2820if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2821$File::Find::prune =1;2822return;2823}28242825my$path=substr($File::Find::name,$pfxlen+1);2826# we check related file in $projectroot2827if(check_export_ok("$projectroot/$path")) {2828push@list, { path =>$path};2829$File::Find::prune =1;2830}2831},2832},"$dir");28332834}elsif(-f $projects_list) {2835# read from file(url-encoded):2836# 'git%2Fgit.git Linus+Torvalds'2837# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2838# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2839open my$fd,'<',$projects_listorreturn;2840 PROJECT:2841while(my$line= <$fd>) {2842chomp$line;2843my($path,$owner) =split' ',$line;2844$path= unescape($path);2845$owner= unescape($owner);2846if(!defined$path) {2847next;2848}2849# if $filter is rpovided, check if $path begins with $filter2850if($filter&&$path!~m!^\Q$filter\E/!) {2851next;2852}2853if(check_export_ok("$projectroot/$path")) {2854my$pr= {2855 path =>$path,2856 owner => to_utf8($owner),2857};2858push@list,$pr;2859}2860}2861close$fd;2862}2863return@list;2864}28652866# written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)2867# as side effects it sets 'forks' field to list of forks for forked projects2868sub filter_forks_from_projects_list {2869my$projects=shift;28702871my%trie;# prefix tree of directories (path components)2872# generate trie out of those directories that might contain forks2873foreachmy$pr(@$projects) {2874my$path=$pr->{'path'};2875$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory2876next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'2877next unless($path);# skip '.git' repository: tests, git-instaweb2878next unless(-d $path);# containing directory exists2879$pr->{'forks'} = [];# there can be 0 or more forks of project28802881# add to trie2882my@dirs=split('/',$path);2883# walk the trie, until either runs out of components or out of trie2884my$ref= \%trie;2885while(scalar@dirs&&2886exists($ref->{$dirs[0]})) {2887$ref=$ref->{shift@dirs};2888}2889# create rest of trie structure from rest of components2890foreachmy$dir(@dirs) {2891$ref=$ref->{$dir} = {};2892}2893# create end marker, store $pr as a data2894$ref->{''} =$prif(!exists$ref->{''});2895}28962897# filter out forks, by finding shortest prefix match for paths2898my@filtered;2899 PROJECT:2900foreachmy$pr(@$projects) {2901# trie lookup2902my$ref= \%trie;2903 DIR:2904foreachmy$dir(split('/',$pr->{'path'})) {2905if(exists$ref->{''}) {2906# found [shortest] prefix, is a fork - skip it2907push@{$ref->{''}{'forks'}},$pr;2908next PROJECT;2909}2910if(!exists$ref->{$dir}) {2911# not in trie, cannot have prefix, not a fork2912push@filtered,$pr;2913next PROJECT;2914}2915# If the dir is there, we just walk one step down the trie.2916$ref=$ref->{$dir};2917}2918# we ran out of trie2919# (shouldn't happen: it's either no match, or end marker)2920push@filtered,$pr;2921}29222923return@filtered;2924}29252926# note: fill_project_list_info must be run first,2927# for 'descr_long' and 'ctags' to be filled2928sub search_projects_list {2929my($projlist,%opts) =@_;2930my$tagfilter=$opts{'tagfilter'};2931my$searchtext=$opts{'searchtext'};29322933return@$projlist2934unless($tagfilter||$searchtext);29352936my@projects;2937 PROJECT:2938foreachmy$pr(@$projlist) {29392940if($tagfilter) {2941next unlessref($pr->{'ctags'})eq'HASH';2942next unless2943grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};2944}29452946if($searchtext) {2947next unless2948$pr->{'path'} =~/$searchtext/||2949$pr->{'descr_long'} =~/$searchtext/;2950}29512952push@projects,$pr;2953}29542955return@projects;2956}29572958our$gitweb_project_owner=undef;2959sub git_get_project_list_from_file {29602961return if(defined$gitweb_project_owner);29622963$gitweb_project_owner= {};2964# read from file (url-encoded):2965# 'git%2Fgit.git Linus+Torvalds'2966# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2967# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2968if(-f $projects_list) {2969open(my$fd,'<',$projects_list);2970while(my$line= <$fd>) {2971chomp$line;2972my($pr,$ow) =split' ',$line;2973$pr= unescape($pr);2974$ow= unescape($ow);2975$gitweb_project_owner->{$pr} = to_utf8($ow);2976}2977close$fd;2978}2979}29802981sub git_get_project_owner {2982my$project=shift;2983my$owner;29842985returnundefunless$project;2986$git_dir="$projectroot/$project";29872988if(!defined$gitweb_project_owner) {2989 git_get_project_list_from_file();2990}29912992if(exists$gitweb_project_owner->{$project}) {2993$owner=$gitweb_project_owner->{$project};2994}2995if(!defined$owner){2996$owner= git_get_project_config('owner');2997}2998if(!defined$owner) {2999$owner= get_file_owner("$git_dir");3000}30013002return$owner;3003}30043005sub git_get_last_activity {3006my($path) =@_;3007my$fd;30083009$git_dir="$projectroot/$path";3010open($fd,"-|", git_cmd(),'for-each-ref',3011'--format=%(committer)',3012'--sort=-committerdate',3013'--count=1',3014'refs/heads')orreturn;3015my$most_recent= <$fd>;3016close$fdorreturn;3017if(defined$most_recent&&3018$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {3019my$timestamp=$1;3020my$age=time-$timestamp;3021return($age, age_string($age));3022}3023return(undef,undef);3024}30253026# Implementation note: when a single remote is wanted, we cannot use 'git3027# remote show -n' because that command always work (assuming it's a remote URL3028# if it's not defined), and we cannot use 'git remote show' because that would3029# try to make a network roundtrip. So the only way to find if that particular3030# remote is defined is to walk the list provided by 'git remote -v' and stop if3031# and when we find what we want.3032sub git_get_remotes_list {3033my$wanted=shift;3034my%remotes= ();30353036open my$fd,'-|', git_cmd(),'remote','-v';3037return unless$fd;3038while(my$remote= <$fd>) {3039chomp$remote;3040$remote=~s!\t(.*?)\s+\((\w+)\)$!!;3041next if$wantedand not$remoteeq$wanted;3042my($url,$key) = ($1,$2);30433044$remotes{$remote} ||= {'heads'=> () };3045$remotes{$remote}{$key} =$url;3046}3047close$fdorreturn;3048returnwantarray?%remotes: \%remotes;3049}30503051# Takes a hash of remotes as first parameter and fills it by adding the3052# available remote heads for each of the indicated remotes.3053sub fill_remote_heads {3054my$remotes=shift;3055my@heads=map{"remotes/$_"}keys%$remotes;3056my@remoteheads= git_get_heads_list(undef,@heads);3057foreachmy$remote(keys%$remotes) {3058$remotes->{$remote}{'heads'} = [grep{3059$_->{'name'} =~s!^$remote/!!3060}@remoteheads];3061}3062}30633064sub git_get_references {3065my$type=shift||"";3066my%refs;3067# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113068# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3069open my$fd,"-|", git_cmd(),"show-ref","--dereference",3070($type? ("--","refs/$type") : ())# use -- <pattern> if $type3071orreturn;30723073while(my$line= <$fd>) {3074chomp$line;3075if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3076if(defined$refs{$1}) {3077push@{$refs{$1}},$2;3078}else{3079$refs{$1} = [$2];3080}3081}3082}3083close$fdorreturn;3084return \%refs;3085}30863087sub git_get_rev_name_tags {3088my$hash=shift||returnundef;30893090open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3091orreturn;3092my$name_rev= <$fd>;3093close$fd;30943095if($name_rev=~ m|^$hash tags/(.*)$|) {3096return$1;3097}else{3098# catches also '$hash undefined' output3099returnundef;3100}3101}31023103## ----------------------------------------------------------------------3104## parse to hash functions31053106sub parse_date {3107my$epoch=shift;3108my$tz=shift||"-0000";31093110my%date;3111my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3112my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3113my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3114$date{'hour'} =$hour;3115$date{'minute'} =$min;3116$date{'mday'} =$mday;3117$date{'day'} =$days[$wday];3118$date{'month'} =$months[$mon];3119$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3120$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3121$date{'mday-time'} =sprintf"%d%s%02d:%02d",3122$mday,$months[$mon],$hour,$min;3123$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",31241900+$year,1+$mon,$mday,$hour,$min,$sec;31253126my($tz_sign,$tz_hour,$tz_min) =3127($tz=~m/^([-+])(\d\d)(\d\d)$/);3128$tz_sign= ($tz_signeq'-'? -1: +1);3129my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3130($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3131$date{'hour_local'} =$hour;3132$date{'minute_local'} =$min;3133$date{'tz_local'} =$tz;3134$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",31351900+$year,$mon+1,$mday,3136$hour,$min,$sec,$tz);3137return%date;3138}31393140sub parse_tag {3141my$tag_id=shift;3142my%tag;3143my@comment;31443145open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3146$tag{'id'} =$tag_id;3147while(my$line= <$fd>) {3148chomp$line;3149if($line=~m/^object ([0-9a-fA-F]{40})$/) {3150$tag{'object'} =$1;3151}elsif($line=~m/^type (.+)$/) {3152$tag{'type'} =$1;3153}elsif($line=~m/^tag (.+)$/) {3154$tag{'name'} =$1;3155}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3156$tag{'author'} =$1;3157$tag{'author_epoch'} =$2;3158$tag{'author_tz'} =$3;3159if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3160$tag{'author_name'} =$1;3161$tag{'author_email'} =$2;3162}else{3163$tag{'author_name'} =$tag{'author'};3164}3165}elsif($line=~m/--BEGIN/) {3166push@comment,$line;3167last;3168}elsif($lineeq"") {3169last;3170}3171}3172push@comment, <$fd>;3173$tag{'comment'} = \@comment;3174close$fdorreturn;3175if(!defined$tag{'name'}) {3176return3177};3178return%tag3179}31803181sub parse_commit_text {3182my($commit_text,$withparents) =@_;3183my@commit_lines=split'\n',$commit_text;3184my%co;31853186pop@commit_lines;# Remove '\0'31873188if(!@commit_lines) {3189return;3190}31913192my$header=shift@commit_lines;3193if($header!~m/^[0-9a-fA-F]{40}/) {3194return;3195}3196($co{'id'},my@parents) =split' ',$header;3197while(my$line=shift@commit_lines) {3198last if$lineeq"\n";3199if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3200$co{'tree'} =$1;3201}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3202push@parents,$1;3203}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3204$co{'author'} = to_utf8($1);3205$co{'author_epoch'} =$2;3206$co{'author_tz'} =$3;3207if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3208$co{'author_name'} =$1;3209$co{'author_email'} =$2;3210}else{3211$co{'author_name'} =$co{'author'};3212}3213}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3214$co{'committer'} = to_utf8($1);3215$co{'committer_epoch'} =$2;3216$co{'committer_tz'} =$3;3217if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3218$co{'committer_name'} =$1;3219$co{'committer_email'} =$2;3220}else{3221$co{'committer_name'} =$co{'committer'};3222}3223}3224}3225if(!defined$co{'tree'}) {3226return;3227};3228$co{'parents'} = \@parents;3229$co{'parent'} =$parents[0];32303231foreachmy$title(@commit_lines) {3232$title=~s/^ //;3233if($titlene"") {3234$co{'title'} = chop_str($title,80,5);3235# remove leading stuff of merges to make the interesting part visible3236if(length($title) >50) {3237$title=~s/^Automatic //;3238$title=~s/^merge (of|with) /Merge ... /i;3239if(length($title) >50) {3240$title=~s/(http|rsync):\/\///;3241}3242if(length($title) >50) {3243$title=~s/(master|www|rsync)\.//;3244}3245if(length($title) >50) {3246$title=~s/kernel.org:?//;3247}3248if(length($title) >50) {3249$title=~s/\/pub\/scm//;3250}3251}3252$co{'title_short'} = chop_str($title,50,5);3253last;3254}3255}3256if(!defined$co{'title'} ||$co{'title'}eq"") {3257$co{'title'} =$co{'title_short'} ='(no commit message)';3258}3259# remove added spaces3260foreachmy$line(@commit_lines) {3261$line=~s/^ //;3262}3263$co{'comment'} = \@commit_lines;32643265my$age=time-$co{'committer_epoch'};3266$co{'age'} =$age;3267$co{'age_string'} = age_string($age);3268my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3269if($age>60*60*24*7*2) {3270$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3271$co{'age_string_age'} =$co{'age_string'};3272}else{3273$co{'age_string_date'} =$co{'age_string'};3274$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3275}3276return%co;3277}32783279sub parse_commit {3280my($commit_id) =@_;3281my%co;32823283local$/="\0";32843285open my$fd,"-|", git_cmd(),"rev-list",3286"--parents",3287"--header",3288"--max-count=1",3289$commit_id,3290"--",3291or die_error(500,"Open git-rev-list failed");3292%co= parse_commit_text(<$fd>,1);3293close$fd;32943295return%co;3296}32973298sub parse_commits {3299my($commit_id,$maxcount,$skip,$filename,@args) =@_;3300my@cos;33013302$maxcount||=1;3303$skip||=0;33043305local$/="\0";33063307open my$fd,"-|", git_cmd(),"rev-list",3308"--header",3309@args,3310("--max-count=".$maxcount),3311("--skip=".$skip),3312@extra_options,3313$commit_id,3314"--",3315($filename? ($filename) : ())3316or die_error(500,"Open git-rev-list failed");3317while(my$line= <$fd>) {3318my%co= parse_commit_text($line);3319push@cos, \%co;3320}3321close$fd;33223323returnwantarray?@cos: \@cos;3324}33253326# parse line of git-diff-tree "raw" output3327sub parse_difftree_raw_line {3328my$line=shift;3329my%res;33303331# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3332# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3333if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3334$res{'from_mode'} =$1;3335$res{'to_mode'} =$2;3336$res{'from_id'} =$3;3337$res{'to_id'} =$4;3338$res{'status'} =$5;3339$res{'similarity'} =$6;3340if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3341($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3342}else{3343$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3344}3345}3346# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3347# combined diff (for merge commit)3348elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3349$res{'nparents'} =length($1);3350$res{'from_mode'} = [split(' ',$2) ];3351$res{'to_mode'} =pop@{$res{'from_mode'}};3352$res{'from_id'} = [split(' ',$3) ];3353$res{'to_id'} =pop@{$res{'from_id'}};3354$res{'status'} = [split('',$4) ];3355$res{'to_file'} = unquote($5);3356}3357# 'c512b523472485aef4fff9e57b229d9d243c967f'3358elsif($line=~m/^([0-9a-fA-F]{40})$/) {3359$res{'commit'} =$1;3360}33613362returnwantarray?%res: \%res;3363}33643365# wrapper: return parsed line of git-diff-tree "raw" output3366# (the argument might be raw line, or parsed info)3367sub parsed_difftree_line {3368my$line_or_ref=shift;33693370if(ref($line_or_ref)eq"HASH") {3371# pre-parsed (or generated by hand)3372return$line_or_ref;3373}else{3374return parse_difftree_raw_line($line_or_ref);3375}3376}33773378# parse line of git-ls-tree output3379sub parse_ls_tree_line {3380my$line=shift;3381my%opts=@_;3382my%res;33833384if($opts{'-l'}) {3385#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3386$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;33873388$res{'mode'} =$1;3389$res{'type'} =$2;3390$res{'hash'} =$3;3391$res{'size'} =$4;3392if($opts{'-z'}) {3393$res{'name'} =$5;3394}else{3395$res{'name'} = unquote($5);3396}3397}else{3398#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3399$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;34003401$res{'mode'} =$1;3402$res{'type'} =$2;3403$res{'hash'} =$3;3404if($opts{'-z'}) {3405$res{'name'} =$4;3406}else{3407$res{'name'} = unquote($4);3408}3409}34103411returnwantarray?%res: \%res;3412}34133414# generates _two_ hashes, references to which are passed as 2 and 3 argument3415sub parse_from_to_diffinfo {3416my($diffinfo,$from,$to,@parents) =@_;34173418if($diffinfo->{'nparents'}) {3419# combined diff3420$from->{'file'} = [];3421$from->{'href'} = [];3422 fill_from_file_info($diffinfo,@parents)3423unlessexists$diffinfo->{'from_file'};3424for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3425$from->{'file'}[$i] =3426defined$diffinfo->{'from_file'}[$i] ?3427$diffinfo->{'from_file'}[$i] :3428$diffinfo->{'to_file'};3429if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3430$from->{'href'}[$i] = href(action=>"blob",3431 hash_base=>$parents[$i],3432 hash=>$diffinfo->{'from_id'}[$i],3433 file_name=>$from->{'file'}[$i]);3434}else{3435$from->{'href'}[$i] =undef;3436}3437}3438}else{3439# ordinary (not combined) diff3440$from->{'file'} =$diffinfo->{'from_file'};3441if($diffinfo->{'status'}ne"A") {# not new (added) file3442$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3443 hash=>$diffinfo->{'from_id'},3444 file_name=>$from->{'file'});3445}else{3446delete$from->{'href'};3447}3448}34493450$to->{'file'} =$diffinfo->{'to_file'};3451if(!is_deleted($diffinfo)) {# file exists in result3452$to->{'href'} = href(action=>"blob", hash_base=>$hash,3453 hash=>$diffinfo->{'to_id'},3454 file_name=>$to->{'file'});3455}else{3456delete$to->{'href'};3457}3458}34593460## ......................................................................3461## parse to array of hashes functions34623463sub git_get_heads_list {3464my($limit,@classes) =@_;3465@classes= ('heads')unless@classes;3466my@patterns=map{"refs/$_"}@classes;3467my@headslist;34683469open my$fd,'-|', git_cmd(),'for-each-ref',3470($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3471'--format=%(objectname) %(refname) %(subject)%00%(committer)',3472@patterns3473orreturn;3474while(my$line= <$fd>) {3475my%ref_item;34763477chomp$line;3478my($refinfo,$committerinfo) =split(/\0/,$line);3479my($hash,$name,$title) =split(' ',$refinfo,3);3480my($committer,$epoch,$tz) =3481($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3482$ref_item{'fullname'} =$name;3483$name=~s!^refs/(?:head|remote)s/!!;34843485$ref_item{'name'} =$name;3486$ref_item{'id'} =$hash;3487$ref_item{'title'} =$title||'(no commit message)';3488$ref_item{'epoch'} =$epoch;3489if($epoch) {3490$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3491}else{3492$ref_item{'age'} ="unknown";3493}34943495push@headslist, \%ref_item;3496}3497close$fd;34983499returnwantarray?@headslist: \@headslist;3500}35013502sub git_get_tags_list {3503my$limit=shift;3504my@tagslist;35053506open my$fd,'-|', git_cmd(),'for-each-ref',3507($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3508'--format=%(objectname) %(objecttype) %(refname) '.3509'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3510'refs/tags'3511orreturn;3512while(my$line= <$fd>) {3513my%ref_item;35143515chomp$line;3516my($refinfo,$creatorinfo) =split(/\0/,$line);3517my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3518my($creator,$epoch,$tz) =3519($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3520$ref_item{'fullname'} =$name;3521$name=~s!^refs/tags/!!;35223523$ref_item{'type'} =$type;3524$ref_item{'id'} =$id;3525$ref_item{'name'} =$name;3526if($typeeq"tag") {3527$ref_item{'subject'} =$title;3528$ref_item{'reftype'} =$reftype;3529$ref_item{'refid'} =$refid;3530}else{3531$ref_item{'reftype'} =$type;3532$ref_item{'refid'} =$id;3533}35343535if($typeeq"tag"||$typeeq"commit") {3536$ref_item{'epoch'} =$epoch;3537if($epoch) {3538$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3539}else{3540$ref_item{'age'} ="unknown";3541}3542}35433544push@tagslist, \%ref_item;3545}3546close$fd;35473548returnwantarray?@tagslist: \@tagslist;3549}35503551## ----------------------------------------------------------------------3552## filesystem-related functions35533554sub get_file_owner {3555my$path=shift;35563557my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3558my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3559if(!defined$gcos) {3560returnundef;3561}3562my$owner=$gcos;3563$owner=~s/[,;].*$//;3564return to_utf8($owner);3565}35663567# assume that file exists3568sub insert_file {3569my$filename=shift;35703571open my$fd,'<',$filename;3572print map{ to_utf8($_) } <$fd>;3573close$fd;3574}35753576## ......................................................................3577## mimetype related functions35783579sub mimetype_guess_file {3580my$filename=shift;3581my$mimemap=shift;3582-r $mimemaporreturnundef;35833584my%mimemap;3585open(my$mh,'<',$mimemap)orreturnundef;3586while(<$mh>) {3587next ifm/^#/;# skip comments3588my($mimetype,@exts) =split(/\s+/);3589foreachmy$ext(@exts) {3590$mimemap{$ext} =$mimetype;3591}3592}3593close($mh);35943595$filename=~/\.([^.]*)$/;3596return$mimemap{$1};3597}35983599sub mimetype_guess {3600my$filename=shift;3601my$mime;3602$filename=~/\./orreturnundef;36033604if($mimetypes_file) {3605my$file=$mimetypes_file;3606if($file!~m!^/!) {# if it is relative path3607# it is relative to project3608$file="$projectroot/$project/$file";3609}3610$mime= mimetype_guess_file($filename,$file);3611}3612$mime||= mimetype_guess_file($filename,'/etc/mime.types');3613return$mime;3614}36153616sub blob_mimetype {3617my$fd=shift;3618my$filename=shift;36193620if($filename) {3621my$mime= mimetype_guess($filename);3622$mimeandreturn$mime;3623}36243625# just in case3626return$default_blob_plain_mimetypeunless$fd;36273628if(-T $fd) {3629return'text/plain';3630}elsif(!$filename) {3631return'application/octet-stream';3632}elsif($filename=~m/\.png$/i) {3633return'image/png';3634}elsif($filename=~m/\.gif$/i) {3635return'image/gif';3636}elsif($filename=~m/\.jpe?g$/i) {3637return'image/jpeg';3638}else{3639return'application/octet-stream';3640}3641}36423643sub blob_contenttype {3644my($fd,$file_name,$type) =@_;36453646$type||= blob_mimetype($fd,$file_name);3647if($typeeq'text/plain'&&defined$default_text_plain_charset) {3648$type.="; charset=$default_text_plain_charset";3649}36503651return$type;3652}36533654# guess file syntax for syntax highlighting; return undef if no highlighting3655# the name of syntax can (in the future) depend on syntax highlighter used3656sub guess_file_syntax {3657my($highlight,$mimetype,$file_name) =@_;3658returnundefunless($highlight&&defined$file_name);3659my$basename= basename($file_name,'.in');3660return$highlight_basename{$basename}3661ifexists$highlight_basename{$basename};36623663$basename=~/\.([^.]*)$/;3664my$ext=$1orreturnundef;3665return$highlight_ext{$ext}3666ifexists$highlight_ext{$ext};36673668returnundef;3669}36703671# run highlighter and return FD of its output,3672# or return original FD if no highlighting3673sub run_highlighter {3674my($fd,$highlight,$syntax) =@_;3675return$fdunless($highlight&&defined$syntax);36763677close$fd;3678open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3679 quote_command($highlight_bin).3680" --replace-tabs=8 --fragment --syntax$syntax|"3681or die_error(500,"Couldn't open file or run syntax highlighter");3682return$fd;3683}36843685## ======================================================================3686## functions printing HTML: header, footer, error page36873688sub get_page_title {3689my$title= to_utf8($site_name);36903691return$titleunless(defined$project);3692$title.=" - ". to_utf8($project);36933694return$titleunless(defined$action);3695$title.="/$action";# $action is US-ASCII (7bit ASCII)36963697return$titleunless(defined$file_name);3698$title.=" - ". esc_path($file_name);3699if($actioneq"tree"&&$file_name!~ m|/$|) {3700$title.="/";3701}37023703return$title;3704}37053706sub get_content_type_html {3707# require explicit support from the UA if we are to send the page as3708# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3709# we have to do this because MSIE sometimes globs '*/*', pretending to3710# support xhtml+xml but choking when it gets what it asked for.3711if(defined$cgi->http('HTTP_ACCEPT') &&3712$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3713$cgi->Accept('application/xhtml+xml') !=0) {3714return'application/xhtml+xml';3715}else{3716return'text/html';3717}3718}37193720sub print_feed_meta {3721if(defined$project) {3722my%href_params= get_feed_info();3723if(!exists$href_params{'-title'}) {3724$href_params{'-title'} ='log';3725}37263727foreachmy$format(qw(RSS Atom)) {3728my$type=lc($format);3729my%link_attr= (3730'-rel'=>'alternate',3731'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3732'-type'=>"application/$type+xml"3733);37343735$href_params{'action'} =$type;3736$link_attr{'-href'} = href(%href_params);3737print"<link ".3738"rel=\"$link_attr{'-rel'}\"".3739"title=\"$link_attr{'-title'}\"".3740"href=\"$link_attr{'-href'}\"".3741"type=\"$link_attr{'-type'}\"".3742"/>\n";37433744$href_params{'extra_options'} ='--no-merges';3745$link_attr{'-href'} = href(%href_params);3746$link_attr{'-title'} .=' (no merges)';3747print"<link ".3748"rel=\"$link_attr{'-rel'}\"".3749"title=\"$link_attr{'-title'}\"".3750"href=\"$link_attr{'-href'}\"".3751"type=\"$link_attr{'-type'}\"".3752"/>\n";3753}37543755}else{3756printf('<link rel="alternate" title="%sprojects list" '.3757'href="%s" type="text/plain; charset=utf-8" />'."\n",3758 esc_attr($site_name), href(project=>undef, action=>"project_index"));3759printf('<link rel="alternate" title="%sprojects feeds" '.3760'href="%s" type="text/x-opml" />'."\n",3761 esc_attr($site_name), href(project=>undef, action=>"opml"));3762}3763}37643765sub print_header_links {3766my$status=shift;37673768# print out each stylesheet that exist, providing backwards capability3769# for those people who defined $stylesheet in a config file3770if(defined$stylesheet) {3771print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3772}else{3773foreachmy$stylesheet(@stylesheets) {3774next unless$stylesheet;3775print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3776}3777}3778 print_feed_meta()3779if($statuseq'200 OK');3780if(defined$favicon) {3781printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);3782}3783}37843785sub print_nav_breadcrumbs {3786my%opts=@_;37873788print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3789if(defined$project) {3790print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3791if(defined$action) {3792my$action_print=$action;3793if(defined$opts{-action_extra}) {3794$action_print=$cgi->a({-href => href(action=>$action)},3795$action);3796}3797print" /$action_print";3798}3799if(defined$opts{-action_extra}) {3800print" /$opts{-action_extra}";3801}3802print"\n";3803}3804}38053806sub print_search_form {3807if(!defined$searchtext) {3808$searchtext="";3809}3810my$search_hash;3811if(defined$hash_base) {3812$search_hash=$hash_base;3813}elsif(defined$hash) {3814$search_hash=$hash;3815}else{3816$search_hash="HEAD";3817}3818my$action=$my_uri;3819my$use_pathinfo= gitweb_check_feature('pathinfo');3820if($use_pathinfo) {3821$action.="/".esc_url($project);3822}3823print$cgi->startform(-method=>"get", -action =>$action) .3824"<div class=\"search\">\n".3825(!$use_pathinfo&&3826$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3827$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3828$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3829$cgi->popup_menu(-name =>'st', -default=>'commit',3830-values=> ['commit','grep','author','committer','pickaxe']) .3831$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3832" search:\n",3833$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3834"<span title=\"Extended regular expression\">".3835$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3836-checked =>$search_use_regexp) .3837"</span>".3838"</div>".3839$cgi->end_form() ."\n";3840}38413842sub git_header_html {3843my$status=shift||"200 OK";3844my$expires=shift;3845my%opts=@_;38463847my$title= get_page_title();3848my$content_type= get_content_type_html();3849print$cgi->header(-type=>$content_type, -charset =>'utf-8',3850-status=>$status, -expires =>$expires)3851unless($opts{'-no_http_header'});3852my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3853print<<EOF;3854<?xml version="1.0" encoding="utf-8"?>3855<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3856<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3857<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3858<!-- git core binaries version$git_version-->3859<head>3860<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3861<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3862<meta name="robots" content="index, nofollow"/>3863<title>$title</title>3864EOF3865# the stylesheet, favicon etc urls won't work correctly with path_info3866# unless we set the appropriate base URL3867if($ENV{'PATH_INFO'}) {3868print"<base href=\"".esc_url($base_url)."\"/>\n";3869}3870 print_header_links($status);3871print"</head>\n".3872"<body>\n";38733874if(defined$site_header&& -f $site_header) {3875 insert_file($site_header);3876}38773878print"<div class=\"page_header\">\n";3879if(defined$logo) {3880print$cgi->a({-href => esc_url($logo_url),3881-title =>$logo_label},3882$cgi->img({-src => esc_url($logo),3883-width =>72, -height =>27,3884-alt =>"git",3885-class=>"logo"}));3886}3887 print_nav_breadcrumbs(%opts);3888print"</div>\n";38893890my$have_search= gitweb_check_feature('search');3891if(defined$project&&$have_search) {3892 print_search_form();3893}3894}38953896sub git_footer_html {3897my$feed_class='rss_logo';38983899print"<div class=\"page_footer\">\n";3900if(defined$project) {3901my$descr= git_get_project_description($project);3902if(defined$descr) {3903print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3904}39053906my%href_params= get_feed_info();3907if(!%href_params) {3908$feed_class.=' generic';3909}3910$href_params{'-title'} ||='log';39113912foreachmy$format(qw(RSS Atom)) {3913$href_params{'action'} =lc($format);3914print$cgi->a({-href => href(%href_params),3915-title =>"$href_params{'-title'}$formatfeed",3916-class=>$feed_class},$format)."\n";3917}39183919}else{3920print$cgi->a({-href => href(project=>undef, action=>"opml"),3921-class=>$feed_class},"OPML") ." ";3922print$cgi->a({-href => href(project=>undef, action=>"project_index"),3923-class=>$feed_class},"TXT") ."\n";3924}3925print"</div>\n";# class="page_footer"39263927if(defined$t0&& gitweb_check_feature('timed')) {3928print"<div id=\"generating_info\">\n";3929print'This page took '.3930'<span id="generating_time" class="time_span">'.3931 tv_interval($t0, [ gettimeofday() ]).3932' seconds </span>'.3933' and '.3934'<span id="generating_cmd">'.3935$number_of_git_cmds.3936'</span> git commands '.3937" to generate.\n";3938print"</div>\n";# class="page_footer"3939}39403941if(defined$site_footer&& -f $site_footer) {3942 insert_file($site_footer);3943}39443945print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;3946if(defined$action&&3947$actioneq'blame_incremental') {3948print qq!<script type="text/javascript">\n!.3949 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.3950 qq!"!. href() .qq!");\n!.3951 qq!</script>\n!;3952}else{3953my($jstimezone,$tz_cookie,$datetime_class) =3954 gitweb_get_feature('javascript-timezone');39553956print qq!<script type="text/javascript">\n!.3957 qq!window.onload = function () {\n!;3958if(gitweb_check_feature('javascript-actions')) {3959print qq! fixLinks();\n!;3960}3961if($jstimezone&&$tz_cookie&&$datetime_class) {3962print qq! var tz_cookie = { name:'$tz_cookie', expires:14, path:'/'};\n!.# in days3963 qq! onloadTZSetup('$jstimezone', tz_cookie,'$datetime_class');\n!;3964}3965print qq!};\n!.3966 qq!</script>\n!;3967}39683969print"</body>\n".3970"</html>";3971}39723973# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])3974# Example: die_error(404, 'Hash not found')3975# By convention, use the following status codes (as defined in RFC 2616):3976# 400: Invalid or missing CGI parameters, or3977# requested object exists but has wrong type.3978# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3979# this server or project.3980# 404: Requested object/revision/project doesn't exist.3981# 500: The server isn't configured properly, or3982# an internal error occurred (e.g. failed assertions caused by bugs), or3983# an unknown error occurred (e.g. the git binary died unexpectedly).3984# 503: The server is currently unavailable (because it is overloaded,3985# or down for maintenance). Generally, this is a temporary state.3986sub die_error {3987my$status=shift||500;3988my$error= esc_html(shift) ||"Internal Server Error";3989my$extra=shift;3990my%opts=@_;39913992my%http_responses= (3993400=>'400 Bad Request',3994403=>'403 Forbidden',3995404=>'404 Not Found',3996500=>'500 Internal Server Error',3997503=>'503 Service Unavailable',3998);3999 git_header_html($http_responses{$status},undef,%opts);4000print<<EOF;4001<div class="page_body">4002<br /><br />4003$status-$error4004<br />4005EOF4006if(defined$extra) {4007print"<hr />\n".4008"$extra\n";4009}4010print"</div>\n";40114012 git_footer_html();4013goto DONE_GITWEB4014unless($opts{'-error_handler'});4015}40164017## ----------------------------------------------------------------------4018## functions printing or outputting HTML: navigation40194020sub git_print_page_nav {4021my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;4022$extra=''if!defined$extra;# pager or formats40234024my@navs=qw(summary shortlog log commit commitdiff tree);4025if($suppress) {4026@navs=grep{$_ne$suppress}@navs;4027}40284029my%arg=map{$_=> {action=>$_} }@navs;4030if(defined$head) {4031for(qw(commit commitdiff)) {4032$arg{$_}{'hash'} =$head;4033}4034if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {4035for(qw(shortlog log)) {4036$arg{$_}{'hash'} =$head;4037}4038}4039}40404041$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;4042$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;40434044my@actions= gitweb_get_feature('actions');4045my%repl= (4046'%'=>'%',4047'n'=>$project,# project name4048'f'=>$git_dir,# project path within filesystem4049'h'=>$treehead||'',# current hash ('h' parameter)4050'b'=>$treebase||'',# hash base ('hb' parameter)4051);4052while(@actions) {4053my($label,$link,$pos) =splice(@actions,0,3);4054# insert4055@navs=map{$_eq$pos? ($_,$label) :$_}@navs;4056# munch munch4057$link=~s/%([%nfhb])/$repl{$1}/g;4058$arg{$label}{'_href'} =$link;4059}40604061print"<div class=\"page_nav\">\n".4062(join" | ",4063map{$_eq$current?4064$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4065}@navs);4066print"<br/>\n$extra<br/>\n".4067"</div>\n";4068}40694070# returns a submenu for the nagivation of the refs views (tags, heads,4071# remotes) with the current view disabled and the remotes view only4072# available if the feature is enabled4073sub format_ref_views {4074my($current) =@_;4075my@ref_views=qw{tags heads};4076push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4077returnjoin" | ",map{4078$_eq$current?$_:4079$cgi->a({-href => href(action=>$_)},$_)4080}@ref_views4081}40824083sub format_paging_nav {4084my($action,$page,$has_next_link) =@_;4085my$paging_nav;408640874088if($page>0) {4089$paging_nav.=4090$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4091" ⋅ ".4092$cgi->a({-href => href(-replay=>1, page=>$page-1),4093-accesskey =>"p", -title =>"Alt-p"},"prev");4094}else{4095$paging_nav.="first ⋅ prev";4096}40974098if($has_next_link) {4099$paging_nav.=" ⋅ ".4100$cgi->a({-href => href(-replay=>1, page=>$page+1),4101-accesskey =>"n", -title =>"Alt-n"},"next");4102}else{4103$paging_nav.=" ⋅ next";4104}41054106return$paging_nav;4107}41084109## ......................................................................4110## functions printing or outputting HTML: div41114112sub git_print_header_div {4113my($action,$title,$hash,$hash_base) =@_;4114my%args= ();41154116$args{'action'} =$action;4117$args{'hash'} =$hashif$hash;4118$args{'hash_base'} =$hash_baseif$hash_base;41194120print"<div class=\"header\">\n".4121$cgi->a({-href => href(%args), -class=>"title"},4122$title?$title:$action) .4123"\n</div>\n";4124}41254126sub format_repo_url {4127my($name,$url) =@_;4128return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4129}41304131# Group output by placing it in a DIV element and adding a header.4132# Options for start_div() can be provided by passing a hash reference as the4133# first parameter to the function.4134# Options to git_print_header_div() can be provided by passing an array4135# reference. This must follow the options to start_div if they are present.4136# The content can be a scalar, which is output as-is, a scalar reference, which4137# is output after html escaping, an IO handle passed either as *handle or4138# *handle{IO}, or a function reference. In the latter case all following4139# parameters will be taken as argument to the content function call.4140sub git_print_section {4141my($div_args,$header_args,$content);4142my$arg=shift;4143if(ref($arg)eq'HASH') {4144$div_args=$arg;4145$arg=shift;4146}4147if(ref($arg)eq'ARRAY') {4148$header_args=$arg;4149$arg=shift;4150}4151$content=$arg;41524153print$cgi->start_div($div_args);4154 git_print_header_div(@$header_args);41554156if(ref($content)eq'CODE') {4157$content->(@_);4158}elsif(ref($content)eq'SCALAR') {4159print esc_html($$content);4160}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4161print<$content>;4162}elsif(!ref($content) &&defined($content)) {4163print$content;4164}41654166print$cgi->end_div;4167}41684169sub format_timestamp_html {4170my$date=shift;4171my$strtime=$date->{'rfc2822'};41724173my(undef,undef,$datetime_class) =4174 gitweb_get_feature('javascript-timezone');4175if($datetime_class) {4176$strtime= qq!<span class="$datetime_class">$strtime</span>!;4177}41784179my$localtime_format='(%02d:%02d%s)';4180if($date->{'hour_local'} <6) {4181$localtime_format='(<span class="atnight">%02d:%02d</span>%s)';4182}4183$strtime.=' '.4184sprintf($localtime_format,4185$date->{'hour_local'},$date->{'minute_local'},$date->{'tz_local'});41864187return$strtime;4188}41894190# Outputs the author name and date in long form4191sub git_print_authorship {4192my$co=shift;4193my%opts=@_;4194my$tag=$opts{-tag} ||'div';4195my$author=$co->{'author_name'};41964197my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4198print"<$tagclass=\"author_date\">".4199 format_search_author($author,"author", esc_html($author)) .4200" [".format_timestamp_html(\%ad)."]".4201 git_get_avatar($co->{'author_email'}, -pad_before =>1) .4202"</$tag>\n";4203}42044205# Outputs table rows containing the full author or committer information,4206# in the format expected for 'commit' view (& similar).4207# Parameters are a commit hash reference, followed by the list of people4208# to output information for. If the list is empty it defaults to both4209# author and committer.4210sub git_print_authorship_rows {4211my$co=shift;4212# too bad we can't use @people = @_ || ('author', 'committer')4213my@people=@_;4214@people= ('author','committer')unless@people;4215foreachmy$who(@people) {4216my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4217print"<tr><td>$who</td><td>".4218 format_search_author($co->{"${who}_name"},$who,4219 esc_html($co->{"${who}_name"})) ." ".4220 format_search_author($co->{"${who}_email"},$who,4221 esc_html("<".$co->{"${who}_email"} .">")) .4222"</td><td rowspan=\"2\">".4223 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4224"</td></tr>\n".4225"<tr>".4226"<td></td><td>".4227 format_timestamp_html(\%wd) .4228"</td>".4229"</tr>\n";4230}4231}42324233sub git_print_page_path {4234my$name=shift;4235my$type=shift;4236my$hb=shift;423742384239print"<div class=\"page_path\">";4240print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4241-title =>'tree root'}, to_utf8("[$project]"));4242print" / ";4243if(defined$name) {4244my@dirname=split'/',$name;4245my$basename=pop@dirname;4246my$fullname='';42474248foreachmy$dir(@dirname) {4249$fullname.= ($fullname?'/':'') .$dir;4250print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4251 hash_base=>$hb),4252-title =>$fullname}, esc_path($dir));4253print" / ";4254}4255if(defined$type&&$typeeq'blob') {4256print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4257 hash_base=>$hb),4258-title =>$name}, esc_path($basename));4259}elsif(defined$type&&$typeeq'tree') {4260print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4261 hash_base=>$hb),4262-title =>$name}, esc_path($basename));4263print" / ";4264}else{4265print esc_path($basename);4266}4267}4268print"<br/></div>\n";4269}42704271sub git_print_log {4272my$log=shift;4273my%opts=@_;42744275if($opts{'-remove_title'}) {4276# remove title, i.e. first line of log4277shift@$log;4278}4279# remove leading empty lines4280while(defined$log->[0] &&$log->[0]eq"") {4281shift@$log;4282}42834284# print log4285my$signoff=0;4286my$empty=0;4287foreachmy$line(@$log) {4288if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {4289$signoff=1;4290$empty=0;4291if(!$opts{'-remove_signoff'}) {4292print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4293next;4294}else{4295# remove signoff lines4296next;4297}4298}else{4299$signoff=0;4300}43014302# print only one empty line4303# do not print empty line after signoff4304if($lineeq"") {4305next if($empty||$signoff);4306$empty=1;4307}else{4308$empty=0;4309}43104311print format_log_line_html($line) ."<br/>\n";4312}43134314if($opts{'-final_empty_line'}) {4315# end with single empty line4316print"<br/>\n"unless$empty;4317}4318}43194320# return link target (what link points to)4321sub git_get_link_target {4322my$hash=shift;4323my$link_target;43244325# read link4326open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4327orreturn;4328{4329local$/=undef;4330$link_target= <$fd>;4331}4332close$fd4333orreturn;43344335return$link_target;4336}43374338# given link target, and the directory (basedir) the link is in,4339# return target of link relative to top directory (top tree);4340# return undef if it is not possible (including absolute links).4341sub normalize_link_target {4342my($link_target,$basedir) =@_;43434344# absolute symlinks (beginning with '/') cannot be normalized4345return if(substr($link_target,0,1)eq'/');43464347# normalize link target to path from top (root) tree (dir)4348my$path;4349if($basedir) {4350$path=$basedir.'/'.$link_target;4351}else{4352# we are in top (root) tree (dir)4353$path=$link_target;4354}43554356# remove //, /./, and /../4357my@path_parts;4358foreachmy$part(split('/',$path)) {4359# discard '.' and ''4360next if(!$part||$parteq'.');4361# handle '..'4362if($parteq'..') {4363if(@path_parts) {4364pop@path_parts;4365}else{4366# link leads outside repository (outside top dir)4367return;4368}4369}else{4370push@path_parts,$part;4371}4372}4373$path=join('/',@path_parts);43744375return$path;4376}43774378# print tree entry (row of git_tree), but without encompassing <tr> element4379sub git_print_tree_entry {4380my($t,$basedir,$hash_base,$have_blame) =@_;43814382my%base_key= ();4383$base_key{'hash_base'} =$hash_baseifdefined$hash_base;43844385# The format of a table row is: mode list link. Where mode is4386# the mode of the entry, list is the name of the entry, an href,4387# and link is the action links of the entry.43884389print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4390if(exists$t->{'size'}) {4391print"<td class=\"size\">$t->{'size'}</td>\n";4392}4393if($t->{'type'}eq"blob") {4394print"<td class=\"list\">".4395$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4396 file_name=>"$basedir$t->{'name'}",%base_key),4397-class=>"list"}, esc_path($t->{'name'}));4398if(S_ISLNK(oct$t->{'mode'})) {4399my$link_target= git_get_link_target($t->{'hash'});4400if($link_target) {4401my$norm_target= normalize_link_target($link_target,$basedir);4402if(defined$norm_target) {4403print" -> ".4404$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4405 file_name=>$norm_target),4406-title =>$norm_target}, esc_path($link_target));4407}else{4408print" -> ". esc_path($link_target);4409}4410}4411}4412print"</td>\n";4413print"<td class=\"link\">";4414print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4415 file_name=>"$basedir$t->{'name'}",%base_key)},4416"blob");4417if($have_blame) {4418print" | ".4419$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4420 file_name=>"$basedir$t->{'name'}",%base_key)},4421"blame");4422}4423if(defined$hash_base) {4424print" | ".4425$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4426 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4427"history");4428}4429print" | ".4430$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4431 file_name=>"$basedir$t->{'name'}")},4432"raw");4433print"</td>\n";44344435}elsif($t->{'type'}eq"tree") {4436print"<td class=\"list\">";4437print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4438 file_name=>"$basedir$t->{'name'}",4439%base_key)},4440 esc_path($t->{'name'}));4441print"</td>\n";4442print"<td class=\"link\">";4443print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4444 file_name=>"$basedir$t->{'name'}",4445%base_key)},4446"tree");4447if(defined$hash_base) {4448print" | ".4449$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4450 file_name=>"$basedir$t->{'name'}")},4451"history");4452}4453print"</td>\n";4454}else{4455# unknown object: we can only present history for it4456# (this includes 'commit' object, i.e. submodule support)4457print"<td class=\"list\">".4458 esc_path($t->{'name'}) .4459"</td>\n";4460print"<td class=\"link\">";4461if(defined$hash_base) {4462print$cgi->a({-href => href(action=>"history",4463 hash_base=>$hash_base,4464 file_name=>"$basedir$t->{'name'}")},4465"history");4466}4467print"</td>\n";4468}4469}44704471## ......................................................................4472## functions printing large fragments of HTML44734474# get pre-image filenames for merge (combined) diff4475sub fill_from_file_info {4476my($diff,@parents) =@_;44774478$diff->{'from_file'} = [ ];4479$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4480for(my$i=0;$i<$diff->{'nparents'};$i++) {4481if($diff->{'status'}[$i]eq'R'||4482$diff->{'status'}[$i]eq'C') {4483$diff->{'from_file'}[$i] =4484 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4485}4486}44874488return$diff;4489}44904491# is current raw difftree line of file deletion4492sub is_deleted {4493my$diffinfo=shift;44944495return$diffinfo->{'to_id'}eq('0' x 40);4496}44974498# does patch correspond to [previous] difftree raw line4499# $diffinfo - hashref of parsed raw diff format4500# $patchinfo - hashref of parsed patch diff format4501# (the same keys as in $diffinfo)4502sub is_patch_split {4503my($diffinfo,$patchinfo) =@_;45044505returndefined$diffinfo&&defined$patchinfo4506&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4507}450845094510sub git_difftree_body {4511my($difftree,$hash,@parents) =@_;4512my($parent) =$parents[0];4513my$have_blame= gitweb_check_feature('blame');4514print"<div class=\"list_head\">\n";4515if($#{$difftree} >10) {4516print(($#{$difftree} +1) ." files changed:\n");4517}4518print"</div>\n";45194520print"<table class=\"".4521(@parents>1?"combined ":"") .4522"diff_tree\">\n";45234524# header only for combined diff in 'commitdiff' view4525my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4526if($has_header) {4527# table header4528print"<thead><tr>\n".4529"<th></th><th></th>\n";# filename, patchN link4530for(my$i=0;$i<@parents;$i++) {4531my$par=$parents[$i];4532print"<th>".4533$cgi->a({-href => href(action=>"commitdiff",4534 hash=>$hash, hash_parent=>$par),4535-title =>'commitdiff to parent number '.4536($i+1) .': '.substr($par,0,7)},4537$i+1) .4538" </th>\n";4539}4540print"</tr></thead>\n<tbody>\n";4541}45424543my$alternate=1;4544my$patchno=0;4545foreachmy$line(@{$difftree}) {4546my$diff= parsed_difftree_line($line);45474548if($alternate) {4549print"<tr class=\"dark\">\n";4550}else{4551print"<tr class=\"light\">\n";4552}4553$alternate^=1;45544555if(exists$diff->{'nparents'}) {# combined diff45564557 fill_from_file_info($diff,@parents)4558unlessexists$diff->{'from_file'};45594560if(!is_deleted($diff)) {4561# file exists in the result (child) commit4562print"<td>".4563$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4564 file_name=>$diff->{'to_file'},4565 hash_base=>$hash),4566-class=>"list"}, esc_path($diff->{'to_file'})) .4567"</td>\n";4568}else{4569print"<td>".4570 esc_path($diff->{'to_file'}) .4571"</td>\n";4572}45734574if($actioneq'commitdiff') {4575# link to patch4576$patchno++;4577print"<td class=\"link\">".4578$cgi->a({-href => href(-anchor=>"patch$patchno")},4579"patch") .4580" | ".4581"</td>\n";4582}45834584my$has_history=0;4585my$not_deleted=0;4586for(my$i=0;$i<$diff->{'nparents'};$i++) {4587my$hash_parent=$parents[$i];4588my$from_hash=$diff->{'from_id'}[$i];4589my$from_path=$diff->{'from_file'}[$i];4590my$status=$diff->{'status'}[$i];45914592$has_history||= ($statusne'A');4593$not_deleted||= ($statusne'D');45944595if($statuseq'A') {4596print"<td class=\"link\"align=\"right\"> | </td>\n";4597}elsif($statuseq'D') {4598print"<td class=\"link\">".4599$cgi->a({-href => href(action=>"blob",4600 hash_base=>$hash,4601 hash=>$from_hash,4602 file_name=>$from_path)},4603"blob". ($i+1)) .4604" | </td>\n";4605}else{4606if($diff->{'to_id'}eq$from_hash) {4607print"<td class=\"link nochange\">";4608}else{4609print"<td class=\"link\">";4610}4611print$cgi->a({-href => href(action=>"blobdiff",4612 hash=>$diff->{'to_id'},4613 hash_parent=>$from_hash,4614 hash_base=>$hash,4615 hash_parent_base=>$hash_parent,4616 file_name=>$diff->{'to_file'},4617 file_parent=>$from_path)},4618"diff". ($i+1)) .4619" | </td>\n";4620}4621}46224623print"<td class=\"link\">";4624if($not_deleted) {4625print$cgi->a({-href => href(action=>"blob",4626 hash=>$diff->{'to_id'},4627 file_name=>$diff->{'to_file'},4628 hash_base=>$hash)},4629"blob");4630print" | "if($has_history);4631}4632if($has_history) {4633print$cgi->a({-href => href(action=>"history",4634 file_name=>$diff->{'to_file'},4635 hash_base=>$hash)},4636"history");4637}4638print"</td>\n";46394640print"</tr>\n";4641next;# instead of 'else' clause, to avoid extra indent4642}4643# else ordinary diff46444645my($to_mode_oct,$to_mode_str,$to_file_type);4646my($from_mode_oct,$from_mode_str,$from_file_type);4647if($diff->{'to_mode'}ne('0' x 6)) {4648$to_mode_oct=oct$diff->{'to_mode'};4649if(S_ISREG($to_mode_oct)) {# only for regular file4650$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4651}4652$to_file_type= file_type($diff->{'to_mode'});4653}4654if($diff->{'from_mode'}ne('0' x 6)) {4655$from_mode_oct=oct$diff->{'from_mode'};4656if(S_ISREG($from_mode_oct)) {# only for regular file4657$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4658}4659$from_file_type= file_type($diff->{'from_mode'});4660}46614662if($diff->{'status'}eq"A") {# created4663my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4664$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4665$mode_chng.="]</span>";4666print"<td>";4667print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4668 hash_base=>$hash, file_name=>$diff->{'file'}),4669-class=>"list"}, esc_path($diff->{'file'}));4670print"</td>\n";4671print"<td>$mode_chng</td>\n";4672print"<td class=\"link\">";4673if($actioneq'commitdiff') {4674# link to patch4675$patchno++;4676print$cgi->a({-href => href(-anchor=>"patch$patchno")},4677"patch") .4678" | ";4679}4680print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4681 hash_base=>$hash, file_name=>$diff->{'file'})},4682"blob");4683print"</td>\n";46844685}elsif($diff->{'status'}eq"D") {# deleted4686my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4687print"<td>";4688print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4689 hash_base=>$parent, file_name=>$diff->{'file'}),4690-class=>"list"}, esc_path($diff->{'file'}));4691print"</td>\n";4692print"<td>$mode_chng</td>\n";4693print"<td class=\"link\">";4694if($actioneq'commitdiff') {4695# link to patch4696$patchno++;4697print$cgi->a({-href => href(-anchor=>"patch$patchno")},4698"patch") .4699" | ";4700}4701print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4702 hash_base=>$parent, file_name=>$diff->{'file'})},4703"blob") ." | ";4704if($have_blame) {4705print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4706 file_name=>$diff->{'file'})},4707"blame") ." | ";4708}4709print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4710 file_name=>$diff->{'file'})},4711"history");4712print"</td>\n";47134714}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4715my$mode_chnge="";4716if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4717$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4718if($from_file_typene$to_file_type) {4719$mode_chnge.=" from$from_file_typeto$to_file_type";4720}4721if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4722if($from_mode_str&&$to_mode_str) {4723$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4724}elsif($to_mode_str) {4725$mode_chnge.=" mode:$to_mode_str";4726}4727}4728$mode_chnge.="]</span>\n";4729}4730print"<td>";4731print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4732 hash_base=>$hash, file_name=>$diff->{'file'}),4733-class=>"list"}, esc_path($diff->{'file'}));4734print"</td>\n";4735print"<td>$mode_chnge</td>\n";4736print"<td class=\"link\">";4737if($actioneq'commitdiff') {4738# link to patch4739$patchno++;4740print$cgi->a({-href => href(-anchor=>"patch$patchno")},4741"patch") .4742" | ";4743}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4744# "commit" view and modified file (not onlu mode changed)4745print$cgi->a({-href => href(action=>"blobdiff",4746 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4747 hash_base=>$hash, hash_parent_base=>$parent,4748 file_name=>$diff->{'file'})},4749"diff") .4750" | ";4751}4752print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4753 hash_base=>$hash, file_name=>$diff->{'file'})},4754"blob") ." | ";4755if($have_blame) {4756print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4757 file_name=>$diff->{'file'})},4758"blame") ." | ";4759}4760print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4761 file_name=>$diff->{'file'})},4762"history");4763print"</td>\n";47644765}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4766my%status_name= ('R'=>'moved','C'=>'copied');4767my$nstatus=$status_name{$diff->{'status'}};4768my$mode_chng="";4769if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4770# mode also for directories, so we cannot use $to_mode_str4771$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4772}4773print"<td>".4774$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4775 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4776-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4777"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4778$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4779 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4780-class=>"list"}, esc_path($diff->{'from_file'})) .4781" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4782"<td class=\"link\">";4783if($actioneq'commitdiff') {4784# link to patch4785$patchno++;4786print$cgi->a({-href => href(-anchor=>"patch$patchno")},4787"patch") .4788" | ";4789}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4790# "commit" view and modified file (not only pure rename or copy)4791print$cgi->a({-href => href(action=>"blobdiff",4792 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4793 hash_base=>$hash, hash_parent_base=>$parent,4794 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4795"diff") .4796" | ";4797}4798print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4799 hash_base=>$parent, file_name=>$diff->{'to_file'})},4800"blob") ." | ";4801if($have_blame) {4802print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4803 file_name=>$diff->{'to_file'})},4804"blame") ." | ";4805}4806print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4807 file_name=>$diff->{'to_file'})},4808"history");4809print"</td>\n";48104811}# we should not encounter Unmerged (U) or Unknown (X) status4812print"</tr>\n";4813}4814print"</tbody>"if$has_header;4815print"</table>\n";4816}48174818sub git_patchset_body {4819my($fd,$difftree,$hash,@hash_parents) =@_;4820my($hash_parent) =$hash_parents[0];48214822my$is_combined= (@hash_parents>1);4823my$patch_idx=0;4824my$patch_number=0;4825my$patch_line;4826my$diffinfo;4827my$to_name;4828my(%from,%to);48294830print"<div class=\"patchset\">\n";48314832# skip to first patch4833while($patch_line= <$fd>) {4834chomp$patch_line;48354836last if($patch_line=~m/^diff /);4837}48384839 PATCH:4840while($patch_line) {48414842# parse "git diff" header line4843if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4844# $1 is from_name, which we do not use4845$to_name= unquote($2);4846$to_name=~s!^b/!!;4847}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4848# $1 is 'cc' or 'combined', which we do not use4849$to_name= unquote($2);4850}else{4851$to_name=undef;4852}48534854# check if current patch belong to current raw line4855# and parse raw git-diff line if needed4856if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4857# this is continuation of a split patch4858print"<div class=\"patch cont\">\n";4859}else{4860# advance raw git-diff output if needed4861$patch_idx++ifdefined$diffinfo;48624863# read and prepare patch information4864$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);48654866# compact combined diff output can have some patches skipped4867# find which patch (using pathname of result) we are at now;4868if($is_combined) {4869while($to_namene$diffinfo->{'to_file'}) {4870print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4871 format_diff_cc_simplified($diffinfo,@hash_parents) .4872"</div>\n";# class="patch"48734874$patch_idx++;4875$patch_number++;48764877last if$patch_idx>$#$difftree;4878$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4879}4880}48814882# modifies %from, %to hashes4883 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);48844885# this is first patch for raw difftree line with $patch_idx index4886# we index @$difftree array from 0, but number patches from 14887print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4888}48894890# git diff header4891#assert($patch_line =~ m/^diff /) if DEBUG;4892#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4893$patch_number++;4894# print "git diff" header4895print format_git_diff_header_line($patch_line,$diffinfo,4896 \%from, \%to);48974898# print extended diff header4899print"<div class=\"diff extended_header\">\n";4900 EXTENDED_HEADER:4901while($patch_line= <$fd>) {4902chomp$patch_line;49034904last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);49054906print format_extended_diff_header_line($patch_line,$diffinfo,4907 \%from, \%to);4908}4909print"</div>\n";# class="diff extended_header"49104911# from-file/to-file diff header4912if(!$patch_line) {4913print"</div>\n";# class="patch"4914last PATCH;4915}4916next PATCH if($patch_line=~m/^diff /);4917#assert($patch_line =~ m/^---/) if DEBUG;49184919my$last_patch_line=$patch_line;4920$patch_line= <$fd>;4921chomp$patch_line;4922#assert($patch_line =~ m/^\+\+\+/) if DEBUG;49234924print format_diff_from_to_header($last_patch_line,$patch_line,4925$diffinfo, \%from, \%to,4926@hash_parents);49274928# the patch itself4929 LINE:4930while($patch_line= <$fd>) {4931chomp$patch_line;49324933next PATCH if($patch_line=~m/^diff /);49344935print format_diff_line($patch_line, \%from, \%to);4936}49374938}continue{4939print"</div>\n";# class="patch"4940}49414942# for compact combined (--cc) format, with chunk and patch simplification4943# the patchset might be empty, but there might be unprocessed raw lines4944for(++$patch_idxif$patch_number>0;4945$patch_idx<@$difftree;4946++$patch_idx) {4947# read and prepare patch information4948$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);49494950# generate anchor for "patch" links in difftree / whatchanged part4951print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4952 format_diff_cc_simplified($diffinfo,@hash_parents) .4953"</div>\n";# class="patch"49544955$patch_number++;4956}49574958if($patch_number==0) {4959if(@hash_parents>1) {4960print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4961}else{4962print"<div class=\"diff nodifferences\">No differences found</div>\n";4963}4964}49654966print"</div>\n";# class="patchset"4967}49684969# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49704971# fills project list info (age, description, owner, category, forks)4972# for each project in the list, removing invalid projects from4973# returned list4974# NOTE: modifies $projlist, but does not remove entries from it4975sub fill_project_list_info {4976my$projlist=shift;4977my@projects;49784979my$show_ctags= gitweb_check_feature('ctags');4980 PROJECT:4981foreachmy$pr(@$projlist) {4982my(@activity) = git_get_last_activity($pr->{'path'});4983unless(@activity) {4984next PROJECT;4985}4986($pr->{'age'},$pr->{'age_string'}) =@activity;4987if(!defined$pr->{'descr'}) {4988my$descr= git_get_project_description($pr->{'path'}) ||"";4989$descr= to_utf8($descr);4990$pr->{'descr_long'} =$descr;4991$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);4992}4993if(!defined$pr->{'owner'}) {4994$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";4995}4996if($show_ctags) {4997$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});4998}4999if($projects_list_group_categories&& !defined$pr->{'category'}) {5000my$cat= git_get_project_category($pr->{'path'}) ||5001$project_list_default_category;5002$pr->{'category'} = to_utf8($cat);5003}50045005push@projects,$pr;5006}50075008return@projects;5009}50105011sub sort_projects_list {5012my($projlist,$order) =@_;5013my@projects;50145015my%order_info= (5016 project => { key =>'path', type =>'str'},5017 descr => { key =>'descr_long', type =>'str'},5018 owner => { key =>'owner', type =>'str'},5019 age => { key =>'age', type =>'num'}5020);5021my$oi=$order_info{$order};5022return@$projlistunlessdefined$oi;5023if($oi->{'type'}eq'str') {5024@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@$projlist;5025}else{5026@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@$projlist;5027}50285029return@projects;5030}50315032# returns a hash of categories, containing the list of project5033# belonging to each category5034sub build_projlist_by_category {5035my($projlist,$from,$to) =@_;5036my%categories;50375038$from=0unlessdefined$from;5039$to=$#$projlistif(!defined$to||$#$projlist<$to);50405041for(my$i=$from;$i<=$to;$i++) {5042my$pr=$projlist->[$i];5043push@{$categories{$pr->{'category'} }},$pr;5044}50455046returnwantarray?%categories: \%categories;5047}50485049# print 'sort by' <th> element, generating 'sort by $name' replay link5050# if that order is not selected5051sub print_sort_th {5052print format_sort_th(@_);5053}50545055sub format_sort_th {5056my($name,$order,$header) =@_;5057my$sort_th="";5058$header||=ucfirst($name);50595060if($ordereq$name) {5061$sort_th.="<th>$header</th>\n";5062}else{5063$sort_th.="<th>".5064$cgi->a({-href => href(-replay=>1, order=>$name),5065-class=>"header"},$header) .5066"</th>\n";5067}50685069return$sort_th;5070}50715072sub git_project_list_rows {5073my($projlist,$from,$to,$check_forks) =@_;50745075$from=0unlessdefined$from;5076$to=$#$projlistif(!defined$to||$#$projlist<$to);50775078my$alternate=1;5079for(my$i=$from;$i<=$to;$i++) {5080my$pr=$projlist->[$i];50815082if($alternate) {5083print"<tr class=\"dark\">\n";5084}else{5085print"<tr class=\"light\">\n";5086}5087$alternate^=1;50885089if($check_forks) {5090print"<td>";5091if($pr->{'forks'}) {5092my$nforks=scalar@{$pr->{'forks'}};5093if($nforks>0) {5094print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5095-title =>"$nforksforks"},"+");5096}else{5097print$cgi->span({-title =>"$nforksforks"},"+");5098}5099}5100print"</td>\n";5101}5102print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5103-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".5104"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5105-class=>"list", -title =>$pr->{'descr_long'}},5106 esc_html($pr->{'descr'})) ."</td>\n".5107"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5108print"<td class=\"". age_class($pr->{'age'}) ."\">".5109(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".5110"<td class=\"link\">".5111$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5112$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5113$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5114$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5115($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5116"</td>\n".5117"</tr>\n";5118}5119}51205121sub git_project_list_body {5122# actually uses global variable $project5123my($projlist,$order,$from,$to,$extra,$no_header) =@_;5124my@projects=@$projlist;51255126my$check_forks= gitweb_check_feature('forks');5127my$show_ctags= gitweb_check_feature('ctags');5128my$tagfilter=$show_ctags?$cgi->param('by_tag') :undef;5129$check_forks=undef5130if($tagfilter||$searchtext);51315132# filtering out forks before filling info allows to do less work5133@projects= filter_forks_from_projects_list(\@projects)5134if($check_forks);5135@projects= fill_project_list_info(\@projects);5136# searching projects require filling to be run before it5137@projects= search_projects_list(\@projects,5138'searchtext'=>$searchtext,5139'tagfilter'=>$tagfilter)5140if($tagfilter||$searchtext);51415142$order||=$default_projects_order;5143$from=0unlessdefined$from;5144$to=$#projectsif(!defined$to||$#projects<$to);51455146# short circuit5147if($from>$to) {5148print"<center>\n".5149"<b>No such projects found</b><br />\n".5150"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5151"</center>\n<br />\n";5152return;5153}51545155@projects= sort_projects_list(\@projects,$order);51565157if($show_ctags) {5158my$ctags= git_gather_all_ctags(\@projects);5159my$cloud= git_populate_project_tagcloud($ctags);5160print git_show_project_tagcloud($cloud,64);5161}51625163print"<table class=\"project_list\">\n";5164unless($no_header) {5165print"<tr>\n";5166if($check_forks) {5167print"<th></th>\n";5168}5169 print_sort_th('project',$order,'Project');5170 print_sort_th('descr',$order,'Description');5171 print_sort_th('owner',$order,'Owner');5172 print_sort_th('age',$order,'Last Change');5173print"<th></th>\n".# for links5174"</tr>\n";5175}51765177if($projects_list_group_categories) {5178# only display categories with projects in the $from-$to window5179@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5180my%categories= build_projlist_by_category(\@projects,$from,$to);5181foreachmy$cat(sort keys%categories) {5182unless($cateq"") {5183print"<tr>\n";5184if($check_forks) {5185print"<td></td>\n";5186}5187print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5188print"</tr>\n";5189}51905191 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5192}5193}else{5194 git_project_list_rows(\@projects,$from,$to,$check_forks);5195}51965197if(defined$extra) {5198print"<tr>\n";5199if($check_forks) {5200print"<td></td>\n";5201}5202print"<td colspan=\"5\">$extra</td>\n".5203"</tr>\n";5204}5205print"</table>\n";5206}52075208sub git_log_body {5209# uses global variable $project5210my($commitlist,$from,$to,$refs,$extra) =@_;52115212$from=0unlessdefined$from;5213$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);52145215for(my$i=0;$i<=$to;$i++) {5216my%co= %{$commitlist->[$i]};5217next if!%co;5218my$commit=$co{'id'};5219my$ref= format_ref_marker($refs,$commit);5220 git_print_header_div('commit',5221"<span class=\"age\">$co{'age_string'}</span>".5222 esc_html($co{'title'}) .$ref,5223$commit);5224print"<div class=\"title_text\">\n".5225"<div class=\"log_link\">\n".5226$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5227" | ".5228$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5229" | ".5230$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5231"<br/>\n".5232"</div>\n";5233 git_print_authorship(\%co, -tag =>'span');5234print"<br/>\n</div>\n";52355236print"<div class=\"log_body\">\n";5237 git_print_log($co{'comment'}, -final_empty_line=>1);5238print"</div>\n";5239}5240if($extra) {5241print"<div class=\"page_nav\">\n";5242print"$extra\n";5243print"</div>\n";5244}5245}52465247sub git_shortlog_body {5248# uses global variable $project5249my($commitlist,$from,$to,$refs,$extra) =@_;52505251$from=0unlessdefined$from;5252$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);52535254print"<table class=\"shortlog\">\n";5255my$alternate=1;5256for(my$i=$from;$i<=$to;$i++) {5257my%co= %{$commitlist->[$i]};5258my$commit=$co{'id'};5259my$ref= format_ref_marker($refs,$commit);5260if($alternate) {5261print"<tr class=\"dark\">\n";5262}else{5263print"<tr class=\"light\">\n";5264}5265$alternate^=1;5266# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5267print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5268 format_author_html('td', \%co,10) ."<td>";5269print format_subject_html($co{'title'},$co{'title_short'},5270 href(action=>"commit", hash=>$commit),$ref);5271print"</td>\n".5272"<td class=\"link\">".5273$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5274$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5275$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5276my$snapshot_links= format_snapshot_links($commit);5277if(defined$snapshot_links) {5278print" | ".$snapshot_links;5279}5280print"</td>\n".5281"</tr>\n";5282}5283if(defined$extra) {5284print"<tr>\n".5285"<td colspan=\"4\">$extra</td>\n".5286"</tr>\n";5287}5288print"</table>\n";5289}52905291sub git_history_body {5292# Warning: assumes constant type (blob or tree) during history5293my($commitlist,$from,$to,$refs,$extra,5294$file_name,$file_hash,$ftype) =@_;52955296$from=0unlessdefined$from;5297$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});52985299print"<table class=\"history\">\n";5300my$alternate=1;5301for(my$i=$from;$i<=$to;$i++) {5302my%co= %{$commitlist->[$i]};5303if(!%co) {5304next;5305}5306my$commit=$co{'id'};53075308my$ref= format_ref_marker($refs,$commit);53095310if($alternate) {5311print"<tr class=\"dark\">\n";5312}else{5313print"<tr class=\"light\">\n";5314}5315$alternate^=1;5316print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5317# shortlog: format_author_html('td', \%co, 10)5318 format_author_html('td', \%co,15,3) ."<td>";5319# originally git_history used chop_str($co{'title'}, 50)5320print format_subject_html($co{'title'},$co{'title_short'},5321 href(action=>"commit", hash=>$commit),$ref);5322print"</td>\n".5323"<td class=\"link\">".5324$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5325$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");53265327if($ftypeeq'blob') {5328my$blob_current=$file_hash;5329my$blob_parent= git_get_hash_by_path($commit,$file_name);5330if(defined$blob_current&&defined$blob_parent&&5331$blob_currentne$blob_parent) {5332print" | ".5333$cgi->a({-href => href(action=>"blobdiff",5334 hash=>$blob_current, hash_parent=>$blob_parent,5335 hash_base=>$hash_base, hash_parent_base=>$commit,5336 file_name=>$file_name)},5337"diff to current");5338}5339}5340print"</td>\n".5341"</tr>\n";5342}5343if(defined$extra) {5344print"<tr>\n".5345"<td colspan=\"4\">$extra</td>\n".5346"</tr>\n";5347}5348print"</table>\n";5349}53505351sub git_tags_body {5352# uses global variable $project5353my($taglist,$from,$to,$extra) =@_;5354$from=0unlessdefined$from;5355$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);53565357print"<table class=\"tags\">\n";5358my$alternate=1;5359for(my$i=$from;$i<=$to;$i++) {5360my$entry=$taglist->[$i];5361my%tag=%$entry;5362my$comment=$tag{'subject'};5363my$comment_short;5364if(defined$comment) {5365$comment_short= chop_str($comment,30,5);5366}5367if($alternate) {5368print"<tr class=\"dark\">\n";5369}else{5370print"<tr class=\"light\">\n";5371}5372$alternate^=1;5373if(defined$tag{'age'}) {5374print"<td><i>$tag{'age'}</i></td>\n";5375}else{5376print"<td></td>\n";5377}5378print"<td>".5379$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5380-class=>"list name"}, esc_html($tag{'name'})) .5381"</td>\n".5382"<td>";5383if(defined$comment) {5384print format_subject_html($comment,$comment_short,5385 href(action=>"tag", hash=>$tag{'id'}));5386}5387print"</td>\n".5388"<td class=\"selflink\">";5389if($tag{'type'}eq"tag") {5390print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");5391}else{5392print" ";5393}5394print"</td>\n".5395"<td class=\"link\">"." | ".5396$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});5397if($tag{'reftype'}eq"commit") {5398print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .5399" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");5400}elsif($tag{'reftype'}eq"blob") {5401print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");5402}5403print"</td>\n".5404"</tr>";5405}5406if(defined$extra) {5407print"<tr>\n".5408"<td colspan=\"5\">$extra</td>\n".5409"</tr>\n";5410}5411print"</table>\n";5412}54135414sub git_heads_body {5415# uses global variable $project5416my($headlist,$head,$from,$to,$extra) =@_;5417$from=0unlessdefined$from;5418$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);54195420print"<table class=\"heads\">\n";5421my$alternate=1;5422for(my$i=$from;$i<=$to;$i++) {5423my$entry=$headlist->[$i];5424my%ref=%$entry;5425my$curr=$ref{'id'}eq$head;5426if($alternate) {5427print"<tr class=\"dark\">\n";5428}else{5429print"<tr class=\"light\">\n";5430}5431$alternate^=1;5432print"<td><i>$ref{'age'}</i></td>\n".5433($curr?"<td class=\"current_head\">":"<td>") .5434$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),5435-class=>"list name"},esc_html($ref{'name'})) .5436"</td>\n".5437"<td class=\"link\">".5438$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".5439$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".5440$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .5441"</td>\n".5442"</tr>";5443}5444if(defined$extra) {5445print"<tr>\n".5446"<td colspan=\"3\">$extra</td>\n".5447"</tr>\n";5448}5449print"</table>\n";5450}54515452# Display a single remote block5453sub git_remote_block {5454my($remote,$rdata,$limit,$head) =@_;54555456my$heads=$rdata->{'heads'};5457my$fetch=$rdata->{'fetch'};5458my$push=$rdata->{'push'};54595460my$urls_table="<table class=\"projects_list\">\n";54615462if(defined$fetch) {5463if($fetcheq$push) {5464$urls_table.= format_repo_url("URL",$fetch);5465}else{5466$urls_table.= format_repo_url("Fetch URL",$fetch);5467$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;5468}5469}elsif(defined$push) {5470$urls_table.= format_repo_url("Push URL",$push);5471}else{5472$urls_table.= format_repo_url("","No remote URL");5473}54745475$urls_table.="</table>\n";54765477my$dots;5478if(defined$limit&&$limit<@$heads) {5479$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");5480}54815482print$urls_table;5483 git_heads_body($heads,$head,0,$limit,$dots);5484}54855486# Display a list of remote names with the respective fetch and push URLs5487sub git_remotes_list {5488my($remotedata,$limit) =@_;5489print"<table class=\"heads\">\n";5490my$alternate=1;5491my@remotes=sort keys%$remotedata;54925493my$limited=$limit&&$limit<@remotes;54945495$#remotes=$limit-1if$limited;54965497while(my$remote=shift@remotes) {5498my$rdata=$remotedata->{$remote};5499my$fetch=$rdata->{'fetch'};5500my$push=$rdata->{'push'};5501if($alternate) {5502print"<tr class=\"dark\">\n";5503}else{5504print"<tr class=\"light\">\n";5505}5506$alternate^=1;5507print"<td>".5508$cgi->a({-href=> href(action=>'remotes', hash=>$remote),5509-class=>"list name"},esc_html($remote)) .5510"</td>";5511print"<td class=\"link\">".5512(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .5513" | ".5514(defined$push?$cgi->a({-href=>$push},"push") :"push") .5515"</td>";55165517print"</tr>\n";5518}55195520if($limited) {5521print"<tr>\n".5522"<td colspan=\"3\">".5523$cgi->a({-href => href(action=>"remotes")},"...") .5524"</td>\n"."</tr>\n";5525}55265527print"</table>";5528}55295530# Display remote heads grouped by remote, unless there are too many5531# remotes, in which case we only display the remote names5532sub git_remotes_body {5533my($remotedata,$limit,$head) =@_;5534if($limitand$limit<keys%$remotedata) {5535 git_remotes_list($remotedata,$limit);5536}else{5537 fill_remote_heads($remotedata);5538while(my($remote,$rdata) =each%$remotedata) {5539 git_print_section({-class=>"remote", -id=>$remote},5540["remotes",$remote,$remote],sub{5541 git_remote_block($remote,$rdata,$limit,$head);5542});5543}5544}5545}55465547sub git_search_message {5548my%co=@_;55495550my$greptype;5551if($searchtypeeq'commit') {5552$greptype="--grep=";5553}elsif($searchtypeeq'author') {5554$greptype="--author=";5555}elsif($searchtypeeq'committer') {5556$greptype="--committer=";5557}5558$greptype.=$searchtext;5559my@commitlist= parse_commits($hash,101, (100*$page),undef,5560$greptype,'--regexp-ignore-case',5561$search_use_regexp?'--extended-regexp':'--fixed-strings');55625563my$paging_nav='';5564if($page>0) {5565$paging_nav.=5566$cgi->a({-href => href(-replay=>1, page=>undef)},5567"first") .5568" ⋅ ".5569$cgi->a({-href => href(-replay=>1, page=>$page-1),5570-accesskey =>"p", -title =>"Alt-p"},"prev");5571}else{5572$paging_nav.="first ⋅ prev";5573}5574my$next_link='';5575if($#commitlist>=100) {5576$next_link=5577$cgi->a({-href => href(-replay=>1, page=>$page+1),5578-accesskey =>"n", -title =>"Alt-n"},"next");5579$paging_nav.=" ⋅$next_link";5580}else{5581$paging_nav.=" ⋅ next";5582}55835584 git_header_html();55855586 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);5587 git_print_header_div('commit', esc_html($co{'title'}),$hash);5588if($page==0&& !@commitlist) {5589print"<p>No match.</p>\n";5590}else{5591 git_search_grep_body(\@commitlist,0,99,$next_link);5592}55935594 git_footer_html();5595}55965597sub git_search_changes {5598my%co=@_;55995600local$/="\n";5601open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,5602'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",5603($search_use_regexp?'--pickaxe-regex': ())5604or die_error(500,"Open git-log failed");56055606 git_header_html();56075608 git_print_page_nav('','',$hash,$co{'tree'},$hash);5609 git_print_header_div('commit', esc_html($co{'title'}),$hash);56105611print"<table class=\"pickaxe search\">\n";5612my$alternate=1;5613undef%co;5614my@files;5615while(my$line= <$fd>) {5616chomp$line;5617next unless$line;56185619my%set= parse_difftree_raw_line($line);5620if(defined$set{'commit'}) {5621# finish previous commit5622if(%co) {5623print"</td>\n".5624"<td class=\"link\">".5625$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},5626"commit") .5627" | ".5628$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},5629 hash_base=>$co{'id'})},5630"tree") .5631"</td>\n".5632"</tr>\n";5633}56345635if($alternate) {5636print"<tr class=\"dark\">\n";5637}else{5638print"<tr class=\"light\">\n";5639}5640$alternate^=1;5641%co= parse_commit($set{'commit'});5642my$author= chop_and_escape_str($co{'author_name'},15,5);5643print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5644"<td><i>$author</i></td>\n".5645"<td>".5646$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5647-class=>"list subject"},5648 chop_and_escape_str($co{'title'},50) ."<br/>");5649}elsif(defined$set{'to_id'}) {5650next if($set{'to_id'} =~m/^0{40}$/);56515652print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},5653 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),5654-class=>"list"},5655"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .5656"<br/>\n";5657}5658}5659close$fd;56605661# finish last commit (warning: repetition!)5662if(%co) {5663print"</td>\n".5664"<td class=\"link\">".5665$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},5666"commit") .5667" | ".5668$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},5669 hash_base=>$co{'id'})},5670"tree") .5671"</td>\n".5672"</tr>\n";5673}56745675print"</table>\n";56765677 git_footer_html();5678}56795680sub git_search_files {5681my%co=@_;56825683local$/="\n";5684open my$fd,"-|", git_cmd(),'grep','-n',5685$search_use_regexp? ('-E','-i') :'-F',5686$searchtext,$co{'tree'}5687or die_error(500,"Open git-grep failed");56885689 git_header_html();56905691 git_print_page_nav('','',$hash,$co{'tree'},$hash);5692 git_print_header_div('commit', esc_html($co{'title'}),$hash);56935694print"<table class=\"grep_search\">\n";5695my$alternate=1;5696my$matches=0;5697my$lastfile='';5698while(my$line= <$fd>) {5699chomp$line;5700my($file,$lno,$ltext,$binary);5701last if($matches++>1000);5702if($line=~/^Binary file (.+) matches$/) {5703$file=$1;5704$binary=1;5705}else{5706(undef,$file,$lno,$ltext) =split(/:/,$line,4);5707}5708if($filene$lastfile) {5709$lastfileand print"</td></tr>\n";5710if($alternate++) {5711print"<tr class=\"dark\">\n";5712}else{5713print"<tr class=\"light\">\n";5714}5715print"<td class=\"list\">".5716$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},5717 file_name=>"$file"),5718-class=>"list"}, esc_path($file));5719print"</td><td>\n";5720$lastfile=$file;5721}5722if($binary) {5723print"<div class=\"binary\">Binary file</div>\n";5724}else{5725$ltext= untabify($ltext);5726if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {5727$ltext= esc_html($1, -nbsp=>1);5728$ltext.='<span class="match">';5729$ltext.= esc_html($2, -nbsp=>1);5730$ltext.='</span>';5731$ltext.= esc_html($3, -nbsp=>1);5732}else{5733$ltext= esc_html($ltext, -nbsp=>1);5734}5735print"<div class=\"pre\">".5736$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},5737 file_name=>"$file").'#l'.$lno,5738-class=>"linenr"},sprintf('%4i',$lno))5739.' '.$ltext."</div>\n";5740}5741}5742if($lastfile) {5743print"</td></tr>\n";5744if($matches>1000) {5745print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";5746}5747}else{5748print"<div class=\"diff nodifferences\">No matches found</div>\n";5749}5750close$fd;57515752print"</table>\n";57535754 git_footer_html();5755}57565757sub git_search_grep_body {5758my($commitlist,$from,$to,$extra) =@_;5759$from=0unlessdefined$from;5760$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);57615762print"<table class=\"commit_search\">\n";5763my$alternate=1;5764for(my$i=$from;$i<=$to;$i++) {5765my%co= %{$commitlist->[$i]};5766if(!%co) {5767next;5768}5769my$commit=$co{'id'};5770if($alternate) {5771print"<tr class=\"dark\">\n";5772}else{5773print"<tr class=\"light\">\n";5774}5775$alternate^=1;5776print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5777 format_author_html('td', \%co,15,5) .5778"<td>".5779$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5780-class=>"list subject"},5781 chop_and_escape_str($co{'title'},50) ."<br/>");5782my$comment=$co{'comment'};5783foreachmy$line(@$comment) {5784if($line=~m/^(.*?)($search_regexp)(.*)$/i) {5785my($lead,$match,$trail) = ($1,$2,$3);5786$match= chop_str($match,70,5,'center');5787my$contextlen=int((80-length($match))/2);5788$contextlen=30if($contextlen>30);5789$lead= chop_str($lead,$contextlen,10,'left');5790$trail= chop_str($trail,$contextlen,10,'right');57915792$lead= esc_html($lead);5793$match= esc_html($match);5794$trail= esc_html($trail);57955796print"$lead<span class=\"match\">$match</span>$trail<br />";5797}5798}5799print"</td>\n".5800"<td class=\"link\">".5801$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .5802" | ".5803$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .5804" | ".5805$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");5806print"</td>\n".5807"</tr>\n";5808}5809if(defined$extra) {5810print"<tr>\n".5811"<td colspan=\"3\">$extra</td>\n".5812"</tr>\n";5813}5814print"</table>\n";5815}58165817## ======================================================================5818## ======================================================================5819## actions58205821sub git_project_list {5822my$order=$input_params{'order'};5823if(defined$order&&$order!~m/none|project|descr|owner|age/) {5824 die_error(400,"Unknown order parameter");5825}58265827my@list= git_get_projects_list();5828if(!@list) {5829 die_error(404,"No projects found");5830}58315832 git_header_html();5833if(defined$home_text&& -f $home_text) {5834print"<div class=\"index_include\">\n";5835 insert_file($home_text);5836print"</div>\n";5837}5838print$cgi->startform(-method=>"get") .5839"<p class=\"projsearch\">Search:\n".5840$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".5841"</p>".5842$cgi->end_form() ."\n";5843 git_project_list_body(\@list,$order);5844 git_footer_html();5845}58465847sub git_forks {5848my$order=$input_params{'order'};5849if(defined$order&&$order!~m/none|project|descr|owner|age/) {5850 die_error(400,"Unknown order parameter");5851}58525853my@list= git_get_projects_list($project);5854if(!@list) {5855 die_error(404,"No forks found");5856}58575858 git_header_html();5859 git_print_page_nav('','');5860 git_print_header_div('summary',"$projectforks");5861 git_project_list_body(\@list,$order);5862 git_footer_html();5863}58645865sub git_project_index {5866my@projects= git_get_projects_list();5867if(!@projects) {5868 die_error(404,"No projects found");5869}58705871print$cgi->header(5872-type =>'text/plain',5873-charset =>'utf-8',5874-content_disposition =>'inline; filename="index.aux"');58755876foreachmy$pr(@projects) {5877if(!exists$pr->{'owner'}) {5878$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");5879}58805881my($path,$owner) = ($pr->{'path'},$pr->{'owner'});5882# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '5883$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5884$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5885$path=~s/ /\+/g;5886$owner=~s/ /\+/g;58875888print"$path$owner\n";5889}5890}58915892sub git_summary {5893my$descr= git_get_project_description($project) ||"none";5894my%co= parse_commit("HEAD");5895my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();5896my$head=$co{'id'};5897my$remote_heads= gitweb_check_feature('remote_heads');58985899my$owner= git_get_project_owner($project);59005901my$refs= git_get_references();5902# These get_*_list functions return one more to allow us to see if5903# there are more ...5904my@taglist= git_get_tags_list(16);5905my@headlist= git_get_heads_list(16);5906my%remotedata=$remote_heads? git_get_remotes_list() : ();5907my@forklist;5908my$check_forks= gitweb_check_feature('forks');59095910if($check_forks) {5911# find forks of a project5912@forklist= git_get_projects_list($project);5913# filter out forks of forks5914@forklist= filter_forks_from_projects_list(\@forklist)5915if(@forklist);5916}59175918 git_header_html();5919 git_print_page_nav('summary','',$head);59205921print"<div class=\"title\"> </div>\n";5922print"<table class=\"projects_list\">\n".5923"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".5924"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";5925if(defined$cd{'rfc2822'}) {5926print"<tr id=\"metadata_lchange\"><td>last change</td>".5927"<td>".format_timestamp_html(\%cd)."</td></tr>\n";5928}59295930# use per project git URL list in $projectroot/$project/cloneurl5931# or make project git URL from git base URL and project name5932my$url_tag="URL";5933my@url_list= git_get_project_url_list($project);5934@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;5935foreachmy$git_url(@url_list) {5936next unless$git_url;5937print format_repo_url($url_tag,$git_url);5938$url_tag="";5939}59405941# Tag cloud5942my$show_ctags= gitweb_check_feature('ctags');5943if($show_ctags) {5944my$ctags= git_get_project_ctags($project);5945if(%$ctags) {5946# without ability to add tags, don't show if there are none5947my$cloud= git_populate_project_tagcloud($ctags);5948print"<tr id=\"metadata_ctags\">".5949"<td>content tags</td>".5950"<td>".git_show_project_tagcloud($cloud,48)."</td>".5951"</tr>\n";5952}5953}59545955print"</table>\n";59565957# If XSS prevention is on, we don't include README.html.5958# TODO: Allow a readme in some safe format.5959if(!$prevent_xss&& -s "$projectroot/$project/README.html") {5960print"<div class=\"title\">readme</div>\n".5961"<div class=\"readme\">\n";5962 insert_file("$projectroot/$project/README.html");5963print"\n</div>\n";# class="readme"5964}59655966# we need to request one more than 16 (0..15) to check if5967# those 16 are all5968my@commitlist=$head? parse_commits($head,17) : ();5969if(@commitlist) {5970 git_print_header_div('shortlog');5971 git_shortlog_body(\@commitlist,0,15,$refs,5972$#commitlist<=15?undef:5973$cgi->a({-href => href(action=>"shortlog")},"..."));5974}59755976if(@taglist) {5977 git_print_header_div('tags');5978 git_tags_body(\@taglist,0,15,5979$#taglist<=15?undef:5980$cgi->a({-href => href(action=>"tags")},"..."));5981}59825983if(@headlist) {5984 git_print_header_div('heads');5985 git_heads_body(\@headlist,$head,0,15,5986$#headlist<=15?undef:5987$cgi->a({-href => href(action=>"heads")},"..."));5988}59895990if(%remotedata) {5991 git_print_header_div('remotes');5992 git_remotes_body(\%remotedata,15,$head);5993}59945995if(@forklist) {5996 git_print_header_div('forks');5997 git_project_list_body(\@forklist,'age',0,15,5998$#forklist<=15?undef:5999$cgi->a({-href => href(action=>"forks")},"..."),6000'no_header');6001}60026003 git_footer_html();6004}60056006sub git_tag {6007my%tag= parse_tag($hash);60086009if(!%tag) {6010 die_error(404,"Unknown tag object");6011}60126013my$head= git_get_head_hash($project);6014 git_header_html();6015 git_print_page_nav('','',$head,undef,$head);6016 git_print_header_div('commit', esc_html($tag{'name'}),$hash);6017print"<div class=\"title_text\">\n".6018"<table class=\"object_header\">\n".6019"<tr>\n".6020"<td>object</td>\n".6021"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6022$tag{'object'}) ."</td>\n".6023"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6024$tag{'type'}) ."</td>\n".6025"</tr>\n";6026if(defined($tag{'author'})) {6027 git_print_authorship_rows(\%tag,'author');6028}6029print"</table>\n\n".6030"</div>\n";6031print"<div class=\"page_body\">";6032my$comment=$tag{'comment'};6033foreachmy$line(@$comment) {6034chomp$line;6035print esc_html($line, -nbsp=>1) ."<br/>\n";6036}6037print"</div>\n";6038 git_footer_html();6039}60406041sub git_blame_common {6042my$format=shift||'porcelain';6043if($formateq'porcelain'&&$cgi->param('js')) {6044$format='incremental';6045$action='blame_incremental';# for page title etc6046}60476048# permissions6049 gitweb_check_feature('blame')6050or die_error(403,"Blame view not allowed");60516052# error checking6053 die_error(400,"No file name given")unless$file_name;6054$hash_base||= git_get_head_hash($project);6055 die_error(404,"Couldn't find base commit")unless$hash_base;6056my%co= parse_commit($hash_base)6057or die_error(404,"Commit not found");6058my$ftype="blob";6059if(!defined$hash) {6060$hash= git_get_hash_by_path($hash_base,$file_name,"blob")6061or die_error(404,"Error looking up file");6062}else{6063$ftype= git_get_type($hash);6064if($ftype!~"blob") {6065 die_error(400,"Object is not a blob");6066}6067}60686069my$fd;6070if($formateq'incremental') {6071# get file contents (as base)6072open$fd,"-|", git_cmd(),'cat-file','blob',$hash6073or die_error(500,"Open git-cat-file failed");6074}elsif($formateq'data') {6075# run git-blame --incremental6076open$fd,"-|", git_cmd(),"blame","--incremental",6077$hash_base,"--",$file_name6078or die_error(500,"Open git-blame --incremental failed");6079}else{6080# run git-blame --porcelain6081open$fd,"-|", git_cmd(),"blame",'-p',6082$hash_base,'--',$file_name6083or die_error(500,"Open git-blame --porcelain failed");6084}60856086# incremental blame data returns early6087if($formateq'data') {6088print$cgi->header(6089-type=>"text/plain", -charset =>"utf-8",6090-status=>"200 OK");6091local$| =1;# output autoflush6092printwhile<$fd>;6093close$fd6094or print"ERROR$!\n";60956096print'END';6097if(defined$t0&& gitweb_check_feature('timed')) {6098print' '.6099 tv_interval($t0, [ gettimeofday() ]).6100' '.$number_of_git_cmds;6101}6102print"\n";61036104return;6105}61066107# page header6108 git_header_html();6109my$formats_nav=6110$cgi->a({-href => href(action=>"blob", -replay=>1)},6111"blob") .6112" | ";6113if($formateq'incremental') {6114$formats_nav.=6115$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},6116"blame") ." (non-incremental)";6117}else{6118$formats_nav.=6119$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},6120"blame") ." (incremental)";6121}6122$formats_nav.=6123" | ".6124$cgi->a({-href => href(action=>"history", -replay=>1)},6125"history") .6126" | ".6127$cgi->a({-href => href(action=>$action, file_name=>$file_name)},6128"HEAD");6129 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6130 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6131 git_print_page_path($file_name,$ftype,$hash_base);61326133# page body6134if($formateq'incremental') {6135print"<noscript>\n<div class=\"error\"><center><b>\n".6136"This page requires JavaScript to run.\nUse ".6137$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},6138'this page').6139" instead.\n".6140"</b></center></div>\n</noscript>\n";61416142print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;6143}61446145print qq!<div class="page_body">\n!;6146print qq!<div id="progress_info">.../ ...</div>\n!6147if($formateq'incremental');6148print qq!<table id="blame_table"class="blame" width="100%">\n!.6149#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.6150 qq!<thead>\n!.6151 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.6152 qq!</thead>\n!.6153 qq!<tbody>\n!;61546155my@rev_color=qw(light dark);6156my$num_colors=scalar(@rev_color);6157my$current_color=0;61586159if($formateq'incremental') {6160my$color_class=$rev_color[$current_color];61616162#contents of a file6163my$linenr=0;6164 LINE:6165while(my$line= <$fd>) {6166chomp$line;6167$linenr++;61686169print qq!<tr id="l$linenr"class="$color_class">!.6170 qq!<td class="sha1"><a href=""> </a></td>!.6171 qq!<td class="linenr">!.6172 qq!<a class="linenr" href="">$linenr</a></td>!;6173print qq!<td class="pre">! . esc_html($line) ."</td>\n";6174print qq!</tr>\n!;6175}61766177}else{# porcelain, i.e. ordinary blame6178my%metainfo= ();# saves information about commits61796180# blame data6181 LINE:6182while(my$line= <$fd>) {6183chomp$line;6184# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]6185# no <lines in group> for subsequent lines in group of lines6186my($full_rev,$orig_lineno,$lineno,$group_size) =6187($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);6188if(!exists$metainfo{$full_rev}) {6189$metainfo{$full_rev} = {'nprevious'=>0};6190}6191my$meta=$metainfo{$full_rev};6192my$data;6193while($data= <$fd>) {6194chomp$data;6195last if($data=~s/^\t//);# contents of line6196if($data=~/^(\S+)(?: (.*))?$/) {6197$meta->{$1} =$2unlessexists$meta->{$1};6198}6199if($data=~/^previous /) {6200$meta->{'nprevious'}++;6201}6202}6203my$short_rev=substr($full_rev,0,8);6204my$author=$meta->{'author'};6205my%date=6206 parse_date($meta->{'author-time'},$meta->{'author-tz'});6207my$date=$date{'iso-tz'};6208if($group_size) {6209$current_color= ($current_color+1) %$num_colors;6210}6211my$tr_class=$rev_color[$current_color];6212$tr_class.=' boundary'if(exists$meta->{'boundary'});6213$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);6214$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);6215print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";6216if($group_size) {6217print"<td class=\"sha1\"";6218print" title=\"". esc_html($author) .",$date\"";6219print" rowspan=\"$group_size\""if($group_size>1);6220print">";6221print$cgi->a({-href => href(action=>"commit",6222 hash=>$full_rev,6223 file_name=>$file_name)},6224 esc_html($short_rev));6225if($group_size>=2) {6226my@author_initials= ($author=~/\b([[:upper:]])\B/g);6227if(@author_initials) {6228print"<br />".6229 esc_html(join('',@author_initials));6230# or join('.', ...)6231}6232}6233print"</td>\n";6234}6235# 'previous' <sha1 of parent commit> <filename at commit>6236if(exists$meta->{'previous'} &&6237$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {6238$meta->{'parent'} =$1;6239$meta->{'file_parent'} = unquote($2);6240}6241my$linenr_commit=6242exists($meta->{'parent'}) ?6243$meta->{'parent'} :$full_rev;6244my$linenr_filename=6245exists($meta->{'file_parent'}) ?6246$meta->{'file_parent'} : unquote($meta->{'filename'});6247my$blamed= href(action =>'blame',6248 file_name =>$linenr_filename,6249 hash_base =>$linenr_commit);6250print"<td class=\"linenr\">";6251print$cgi->a({ -href =>"$blamed#l$orig_lineno",6252-class=>"linenr"},6253 esc_html($lineno));6254print"</td>";6255print"<td class=\"pre\">". esc_html($data) ."</td>\n";6256print"</tr>\n";6257}# end while62586259}62606261# footer6262print"</tbody>\n".6263"</table>\n";# class="blame"6264print"</div>\n";# class="blame_body"6265close$fd6266or print"Reading blob failed\n";62676268 git_footer_html();6269}62706271sub git_blame {6272 git_blame_common();6273}62746275sub git_blame_incremental {6276 git_blame_common('incremental');6277}62786279sub git_blame_data {6280 git_blame_common('data');6281}62826283sub git_tags {6284my$head= git_get_head_hash($project);6285 git_header_html();6286 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6287 git_print_header_div('summary',$project);62886289my@tagslist= git_get_tags_list();6290if(@tagslist) {6291 git_tags_body(\@tagslist);6292}6293 git_footer_html();6294}62956296sub git_heads {6297my$head= git_get_head_hash($project);6298 git_header_html();6299 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6300 git_print_header_div('summary',$project);63016302my@headslist= git_get_heads_list();6303if(@headslist) {6304 git_heads_body(\@headslist,$head);6305}6306 git_footer_html();6307}63086309# used both for single remote view and for list of all the remotes6310sub git_remotes {6311 gitweb_check_feature('remote_heads')6312or die_error(403,"Remote heads view is disabled");63136314my$head= git_get_head_hash($project);6315my$remote=$input_params{'hash'};63166317my$remotedata= git_get_remotes_list($remote);6318 die_error(500,"Unable to get remote information")unlessdefined$remotedata;63196320unless(%$remotedata) {6321 die_error(404,defined$remote?6322"Remote$remotenot found":6323"No remotes found");6324}63256326 git_header_html(undef,undef, -action_extra =>$remote);6327 git_print_page_nav('','',$head,undef,$head,6328 format_ref_views($remote?'':'remotes'));63296330 fill_remote_heads($remotedata);6331if(defined$remote) {6332 git_print_header_div('remotes',"$remoteremote for$project");6333 git_remote_block($remote,$remotedata->{$remote},undef,$head);6334}else{6335 git_print_header_div('summary',"$projectremotes");6336 git_remotes_body($remotedata,undef,$head);6337}63386339 git_footer_html();6340}63416342sub git_blob_plain {6343my$type=shift;6344my$expires;63456346if(!defined$hash) {6347if(defined$file_name) {6348my$base=$hash_base|| git_get_head_hash($project);6349$hash= git_get_hash_by_path($base,$file_name,"blob")6350or die_error(404,"Cannot find file");6351}else{6352 die_error(400,"No file name defined");6353}6354}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6355# blobs defined by non-textual hash id's can be cached6356$expires="+1d";6357}63586359open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6360or die_error(500,"Open git-cat-file blob '$hash' failed");63616362# content-type (can include charset)6363$type= blob_contenttype($fd,$file_name,$type);63646365# "save as" filename, even when no $file_name is given6366my$save_as="$hash";6367if(defined$file_name) {6368$save_as=$file_name;6369}elsif($type=~m/^text\//) {6370$save_as.='.txt';6371}63726373# With XSS prevention on, blobs of all types except a few known safe6374# ones are served with "Content-Disposition: attachment" to make sure6375# they don't run in our security domain. For certain image types,6376# blob view writes an <img> tag referring to blob_plain view, and we6377# want to be sure not to break that by serving the image as an6378# attachment (though Firefox 3 doesn't seem to care).6379my$sandbox=$prevent_xss&&6380$type!~m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;63816382# serve text/* as text/plain6383if($prevent_xss&&6384($type=~m!^text/[a-z]+\b(.*)$!||6385($type=~m!^[a-z]+/[a-z]\+xml\b(.*)$!&& -T $fd))) {6386my$rest=$1;6387$rest=defined$rest?$rest:'';6388$type="text/plain$rest";6389}63906391print$cgi->header(6392-type =>$type,6393-expires =>$expires,6394-content_disposition =>6395($sandbox?'attachment':'inline')6396.'; filename="'.$save_as.'"');6397local$/=undef;6398binmode STDOUT,':raw';6399print<$fd>;6400binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6401close$fd;6402}64036404sub git_blob {6405my$expires;64066407if(!defined$hash) {6408if(defined$file_name) {6409my$base=$hash_base|| git_get_head_hash($project);6410$hash= git_get_hash_by_path($base,$file_name,"blob")6411or die_error(404,"Cannot find file");6412}else{6413 die_error(400,"No file name defined");6414}6415}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6416# blobs defined by non-textual hash id's can be cached6417$expires="+1d";6418}64196420my$have_blame= gitweb_check_feature('blame');6421open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6422or die_error(500,"Couldn't cat$file_name,$hash");6423my$mimetype= blob_mimetype($fd,$file_name);6424# use 'blob_plain' (aka 'raw') view for files that cannot be displayed6425if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {6426close$fd;6427return git_blob_plain($mimetype);6428}6429# we can have blame only for text/* mimetype6430$have_blame&&= ($mimetype=~m!^text/!);64316432my$highlight= gitweb_check_feature('highlight');6433my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);6434$fd= run_highlighter($fd,$highlight,$syntax)6435if$syntax;64366437 git_header_html(undef,$expires);6438my$formats_nav='';6439if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6440if(defined$file_name) {6441if($have_blame) {6442$formats_nav.=6443$cgi->a({-href => href(action=>"blame", -replay=>1)},6444"blame") .6445" | ";6446}6447$formats_nav.=6448$cgi->a({-href => href(action=>"history", -replay=>1)},6449"history") .6450" | ".6451$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6452"raw") .6453" | ".6454$cgi->a({-href => href(action=>"blob",6455 hash_base=>"HEAD", file_name=>$file_name)},6456"HEAD");6457}else{6458$formats_nav.=6459$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6460"raw");6461}6462 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6463 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6464}else{6465print"<div class=\"page_nav\">\n".6466"<br/><br/></div>\n".6467"<div class=\"title\">".esc_html($hash)."</div>\n";6468}6469 git_print_page_path($file_name,"blob",$hash_base);6470print"<div class=\"page_body\">\n";6471if($mimetype=~m!^image/!) {6472print qq!<img type="!.esc_attr($mimetype).qq!"!;6473if($file_name) {6474print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;6475}6476print qq! src="! .6477 href(action=>"blob_plain", hash=>$hash,6478 hash_base=>$hash_base, file_name=>$file_name) .6479 qq!"/>\n!;6480}else{6481my$nr;6482while(my$line= <$fd>) {6483chomp$line;6484$nr++;6485$line= untabify($line);6486printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,6487$nr, esc_attr(href(-replay =>1)),$nr,$nr,$syntax? to_utf8($line) : esc_html($line, -nbsp=>1);6488}6489}6490close$fd6491or print"Reading blob failed.\n";6492print"</div>";6493 git_footer_html();6494}64956496sub git_tree {6497if(!defined$hash_base) {6498$hash_base="HEAD";6499}6500if(!defined$hash) {6501if(defined$file_name) {6502$hash= git_get_hash_by_path($hash_base,$file_name,"tree");6503}else{6504$hash=$hash_base;6505}6506}6507 die_error(404,"No such tree")unlessdefined($hash);65086509my$show_sizes= gitweb_check_feature('show-sizes');6510my$have_blame= gitweb_check_feature('blame');65116512my@entries= ();6513{6514local$/="\0";6515open my$fd,"-|", git_cmd(),"ls-tree",'-z',6516($show_sizes?'-l': ()),@extra_options,$hash6517or die_error(500,"Open git-ls-tree failed");6518@entries=map{chomp;$_} <$fd>;6519close$fd6520or die_error(404,"Reading tree failed");6521}65226523my$refs= git_get_references();6524my$ref= format_ref_marker($refs,$hash_base);6525 git_header_html();6526my$basedir='';6527if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6528my@views_nav= ();6529if(defined$file_name) {6530push@views_nav,6531$cgi->a({-href => href(action=>"history", -replay=>1)},6532"history"),6533$cgi->a({-href => href(action=>"tree",6534 hash_base=>"HEAD", file_name=>$file_name)},6535"HEAD"),6536}6537my$snapshot_links= format_snapshot_links($hash);6538if(defined$snapshot_links) {6539# FIXME: Should be available when we have no hash base as well.6540push@views_nav,$snapshot_links;6541}6542 git_print_page_nav('tree','',$hash_base,undef,undef,6543join(' | ',@views_nav));6544 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);6545}else{6546undef$hash_base;6547print"<div class=\"page_nav\">\n";6548print"<br/><br/></div>\n";6549print"<div class=\"title\">".esc_html($hash)."</div>\n";6550}6551if(defined$file_name) {6552$basedir=$file_name;6553if($basedirne''&&substr($basedir, -1)ne'/') {6554$basedir.='/';6555}6556 git_print_page_path($file_name,'tree',$hash_base);6557}6558print"<div class=\"page_body\">\n";6559print"<table class=\"tree\">\n";6560my$alternate=1;6561# '..' (top directory) link if possible6562if(defined$hash_base&&6563defined$file_name&&$file_name=~m![^/]+$!) {6564if($alternate) {6565print"<tr class=\"dark\">\n";6566}else{6567print"<tr class=\"light\">\n";6568}6569$alternate^=1;65706571my$up=$file_name;6572$up=~s!/?[^/]+$!!;6573undef$upunless$up;6574# based on git_print_tree_entry6575print'<td class="mode">'. mode_str('040000') ."</td>\n";6576print'<td class="size"> </td>'."\n"if$show_sizes;6577print'<td class="list">';6578print$cgi->a({-href => href(action=>"tree",6579 hash_base=>$hash_base,6580 file_name=>$up)},6581"..");6582print"</td>\n";6583print"<td class=\"link\"></td>\n";65846585print"</tr>\n";6586}6587foreachmy$line(@entries) {6588my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);65896590if($alternate) {6591print"<tr class=\"dark\">\n";6592}else{6593print"<tr class=\"light\">\n";6594}6595$alternate^=1;65966597 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);65986599print"</tr>\n";6600}6601print"</table>\n".6602"</div>";6603 git_footer_html();6604}66056606sub snapshot_name {6607my($project,$hash) =@_;66086609# path/to/project.git -> project6610# path/to/project/.git -> project6611my$name= to_utf8($project);6612$name=~ s,([^/])/*\.git$,$1,;6613$name= basename($name);6614# sanitize name6615$name=~s/[[:cntrl:]]/?/g;66166617my$ver=$hash;6618if($hash=~/^[0-9a-fA-F]+$/) {6619# shorten SHA-1 hash6620my$full_hash= git_get_full_hash($project,$hash);6621if($full_hash=~/^$hash/&&length($hash) >7) {6622$ver= git_get_short_hash($project,$hash);6623}6624}elsif($hash=~m!^refs/tags/(.*)$!) {6625# tags don't need shortened SHA-1 hash6626$ver=$1;6627}else{6628# branches and other need shortened SHA-1 hash6629if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {6630$ver=$1;6631}6632$ver.='-'. git_get_short_hash($project,$hash);6633}6634# in case of hierarchical branch names6635$ver=~s!/!.!g;66366637# name = project-version_string6638$name="$name-$ver";66396640returnwantarray? ($name,$name) :$name;6641}66426643sub git_snapshot {6644my$format=$input_params{'snapshot_format'};6645if(!@snapshot_fmts) {6646 die_error(403,"Snapshots not allowed");6647}6648# default to first supported snapshot format6649$format||=$snapshot_fmts[0];6650if($format!~m/^[a-z0-9]+$/) {6651 die_error(400,"Invalid snapshot format parameter");6652}elsif(!exists($known_snapshot_formats{$format})) {6653 die_error(400,"Unknown snapshot format");6654}elsif($known_snapshot_formats{$format}{'disabled'}) {6655 die_error(403,"Snapshot format not allowed");6656}elsif(!grep($_eq$format,@snapshot_fmts)) {6657 die_error(403,"Unsupported snapshot format");6658}66596660my$type= git_get_type("$hash^{}");6661if(!$type) {6662 die_error(404,'Object does not exist');6663}elsif($typeeq'blob') {6664 die_error(400,'Object is not a tree-ish');6665}66666667my($name,$prefix) = snapshot_name($project,$hash);6668my$filename="$name$known_snapshot_formats{$format}{'suffix'}";6669my$cmd= quote_command(6670 git_cmd(),'archive',6671"--format=$known_snapshot_formats{$format}{'format'}",6672"--prefix=$prefix/",$hash);6673if(exists$known_snapshot_formats{$format}{'compressor'}) {6674$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});6675}66766677$filename=~s/(["\\])/\\$1/g;6678print$cgi->header(6679-type =>$known_snapshot_formats{$format}{'type'},6680-content_disposition =>'inline; filename="'.$filename.'"',6681-status =>'200 OK');66826683open my$fd,"-|",$cmd6684or die_error(500,"Execute git-archive failed");6685binmode STDOUT,':raw';6686print<$fd>;6687binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6688close$fd;6689}66906691sub git_log_generic {6692my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;66936694my$head= git_get_head_hash($project);6695if(!defined$base) {6696$base=$head;6697}6698if(!defined$page) {6699$page=0;6700}6701my$refs= git_get_references();67026703my$commit_hash=$base;6704if(defined$parent) {6705$commit_hash="$parent..$base";6706}6707my@commitlist=6708 parse_commits($commit_hash,101, (100*$page),6709defined$file_name? ($file_name,"--full-history") : ());67106711my$ftype;6712if(!defined$file_hash&&defined$file_name) {6713# some commits could have deleted file in question,6714# and not have it in tree, but one of them has to have it6715for(my$i=0;$i<@commitlist;$i++) {6716$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);6717last ifdefined$file_hash;6718}6719}6720if(defined$file_hash) {6721$ftype= git_get_type($file_hash);6722}6723if(defined$file_name&& !defined$ftype) {6724 die_error(500,"Unknown type of object");6725}6726my%co;6727if(defined$file_name) {6728%co= parse_commit($base)6729or die_error(404,"Unknown commit object");6730}673167326733my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);6734my$next_link='';6735if($#commitlist>=100) {6736$next_link=6737$cgi->a({-href => href(-replay=>1, page=>$page+1),6738-accesskey =>"n", -title =>"Alt-n"},"next");6739}6740my$patch_max= gitweb_get_feature('patches');6741if($patch_max&& !defined$file_name) {6742if($patch_max<0||@commitlist<=$patch_max) {6743$paging_nav.=" ⋅ ".6744$cgi->a({-href => href(action=>"patches", -replay=>1)},6745"patches");6746}6747}67486749 git_header_html();6750 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);6751if(defined$file_name) {6752 git_print_header_div('commit', esc_html($co{'title'}),$base);6753}else{6754 git_print_header_div('summary',$project)6755}6756 git_print_page_path($file_name,$ftype,$hash_base)6757if(defined$file_name);67586759$body_subr->(\@commitlist,0,99,$refs,$next_link,6760$file_name,$file_hash,$ftype);67616762 git_footer_html();6763}67646765sub git_log {6766 git_log_generic('log', \&git_log_body,6767$hash,$hash_parent);6768}67696770sub git_commit {6771$hash||=$hash_base||"HEAD";6772my%co= parse_commit($hash)6773or die_error(404,"Unknown commit object");67746775my$parent=$co{'parent'};6776my$parents=$co{'parents'};# listref67776778# we need to prepare $formats_nav before any parameter munging6779my$formats_nav;6780if(!defined$parent) {6781# --root commitdiff6782$formats_nav.='(initial)';6783}elsif(@$parents==1) {6784# single parent commit6785$formats_nav.=6786'(parent: '.6787$cgi->a({-href => href(action=>"commit",6788 hash=>$parent)},6789 esc_html(substr($parent,0,7))) .6790')';6791}else{6792# merge commit6793$formats_nav.=6794'(merge: '.6795join(' ',map{6796$cgi->a({-href => href(action=>"commit",6797 hash=>$_)},6798 esc_html(substr($_,0,7)));6799}@$parents) .6800')';6801}6802if(gitweb_check_feature('patches') &&@$parents<=1) {6803$formats_nav.=" | ".6804$cgi->a({-href => href(action=>"patch", -replay=>1)},6805"patch");6806}68076808if(!defined$parent) {6809$parent="--root";6810}6811my@difftree;6812open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",6813@diff_opts,6814(@$parents<=1?$parent:'-c'),6815$hash,"--"6816or die_error(500,"Open git-diff-tree failed");6817@difftree=map{chomp;$_} <$fd>;6818close$fdor die_error(404,"Reading git-diff-tree failed");68196820# non-textual hash id's can be cached6821my$expires;6822if($hash=~m/^[0-9a-fA-F]{40}$/) {6823$expires="+1d";6824}6825my$refs= git_get_references();6826my$ref= format_ref_marker($refs,$co{'id'});68276828 git_header_html(undef,$expires);6829 git_print_page_nav('commit','',6830$hash,$co{'tree'},$hash,6831$formats_nav);68326833if(defined$co{'parent'}) {6834 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);6835}else{6836 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);6837}6838print"<div class=\"title_text\">\n".6839"<table class=\"object_header\">\n";6840 git_print_authorship_rows(\%co);6841print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";6842print"<tr>".6843"<td>tree</td>".6844"<td class=\"sha1\">".6845$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),6846class=>"list"},$co{'tree'}) .6847"</td>".6848"<td class=\"link\">".6849$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},6850"tree");6851my$snapshot_links= format_snapshot_links($hash);6852if(defined$snapshot_links) {6853print" | ".$snapshot_links;6854}6855print"</td>".6856"</tr>\n";68576858foreachmy$par(@$parents) {6859print"<tr>".6860"<td>parent</td>".6861"<td class=\"sha1\">".6862$cgi->a({-href => href(action=>"commit", hash=>$par),6863class=>"list"},$par) .6864"</td>".6865"<td class=\"link\">".6866$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .6867" | ".6868$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .6869"</td>".6870"</tr>\n";6871}6872print"</table>".6873"</div>\n";68746875print"<div class=\"page_body\">\n";6876 git_print_log($co{'comment'});6877print"</div>\n";68786879 git_difftree_body(\@difftree,$hash,@$parents);68806881 git_footer_html();6882}68836884sub git_object {6885# object is defined by:6886# - hash or hash_base alone6887# - hash_base and file_name6888my$type;68896890# - hash or hash_base alone6891if($hash|| ($hash_base&& !defined$file_name)) {6892my$object_id=$hash||$hash_base;68936894open my$fd,"-|", quote_command(6895 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'6896or die_error(404,"Object does not exist");6897$type= <$fd>;6898chomp$type;6899close$fd6900or die_error(404,"Object does not exist");69016902# - hash_base and file_name6903}elsif($hash_base&&defined$file_name) {6904$file_name=~ s,/+$,,;69056906system(git_cmd(),"cat-file",'-e',$hash_base) ==06907or die_error(404,"Base object does not exist");69086909# here errors should not hapen6910open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name6911or die_error(500,"Open git-ls-tree failed");6912my$line= <$fd>;6913close$fd;69146915#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'6916unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {6917 die_error(404,"File or directory for given base does not exist");6918}6919$type=$2;6920$hash=$3;6921}else{6922 die_error(400,"Not enough information to find object");6923}69246925print$cgi->redirect(-uri => href(action=>$type, -full=>1,6926 hash=>$hash, hash_base=>$hash_base,6927 file_name=>$file_name),6928-status =>'302 Found');6929}69306931sub git_blobdiff {6932my$format=shift||'html';69336934my$fd;6935my@difftree;6936my%diffinfo;6937my$expires;69386939# preparing $fd and %diffinfo for git_patchset_body6940# new style URI6941if(defined$hash_base&&defined$hash_parent_base) {6942if(defined$file_name) {6943# read raw output6944open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6945$hash_parent_base,$hash_base,6946"--", (defined$file_parent?$file_parent: ()),$file_name6947or die_error(500,"Open git-diff-tree failed");6948@difftree=map{chomp;$_} <$fd>;6949close$fd6950or die_error(404,"Reading git-diff-tree failed");6951@difftree6952or die_error(404,"Blob diff not found");69536954}elsif(defined$hash&&6955$hash=~/[0-9a-fA-F]{40}/) {6956# try to find filename from $hash69576958# read filtered raw output6959open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6960$hash_parent_base,$hash_base,"--"6961or die_error(500,"Open git-diff-tree failed");6962@difftree=6963# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'6964# $hash == to_id6965grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}6966map{chomp;$_} <$fd>;6967close$fd6968or die_error(404,"Reading git-diff-tree failed");6969@difftree6970or die_error(404,"Blob diff not found");69716972}else{6973 die_error(400,"Missing one of the blob diff parameters");6974}69756976if(@difftree>1) {6977 die_error(400,"Ambiguous blob diff specification");6978}69796980%diffinfo= parse_difftree_raw_line($difftree[0]);6981$file_parent||=$diffinfo{'from_file'} ||$file_name;6982$file_name||=$diffinfo{'to_file'};69836984$hash_parent||=$diffinfo{'from_id'};6985$hash||=$diffinfo{'to_id'};69866987# non-textual hash id's can be cached6988if($hash_base=~m/^[0-9a-fA-F]{40}$/&&6989$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {6990$expires='+1d';6991}69926993# open patch output6994open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6995'-p', ($formateq'html'?"--full-index": ()),6996$hash_parent_base,$hash_base,6997"--", (defined$file_parent?$file_parent: ()),$file_name6998or die_error(500,"Open git-diff-tree failed");6999}70007001# old/legacy style URI -- not generated anymore since 1.4.3.7002if(!%diffinfo) {7003 die_error('404 Not Found',"Missing one of the blob diff parameters")7004}70057006# header7007if($formateq'html') {7008my$formats_nav=7009$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},7010"raw");7011 git_header_html(undef,$expires);7012if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7013 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7014 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7015}else{7016print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";7017print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";7018}7019if(defined$file_name) {7020 git_print_page_path($file_name,"blob",$hash_base);7021}else{7022print"<div class=\"page_path\"></div>\n";7023}70247025}elsif($formateq'plain') {7026print$cgi->header(7027-type =>'text/plain',7028-charset =>'utf-8',7029-expires =>$expires,7030-content_disposition =>'inline; filename="'."$file_name".'.patch"');70317032print"X-Git-Url: ".$cgi->self_url() ."\n\n";70337034}else{7035 die_error(400,"Unknown blobdiff format");7036}70377038# patch7039if($formateq'html') {7040print"<div class=\"page_body\">\n";70417042 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);7043close$fd;70447045print"</div>\n";# class="page_body"7046 git_footer_html();70477048}else{7049while(my$line= <$fd>) {7050$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;7051$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;70527053print$line;70547055last if$line=~m!^\+\+\+!;7056}7057local$/=undef;7058print<$fd>;7059close$fd;7060}7061}70627063sub git_blobdiff_plain {7064 git_blobdiff('plain');7065}70667067sub git_commitdiff {7068my%params=@_;7069my$format=$params{-format} ||'html';70707071my($patch_max) = gitweb_get_feature('patches');7072if($formateq'patch') {7073 die_error(403,"Patch view not allowed")unless$patch_max;7074}70757076$hash||=$hash_base||"HEAD";7077my%co= parse_commit($hash)7078or die_error(404,"Unknown commit object");70797080# choose format for commitdiff for merge7081if(!defined$hash_parent&& @{$co{'parents'}} >1) {7082$hash_parent='--cc';7083}7084# we need to prepare $formats_nav before almost any parameter munging7085my$formats_nav;7086if($formateq'html') {7087$formats_nav=7088$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},7089"raw");7090if($patch_max&& @{$co{'parents'}} <=1) {7091$formats_nav.=" | ".7092$cgi->a({-href => href(action=>"patch", -replay=>1)},7093"patch");7094}70957096if(defined$hash_parent&&7097$hash_parentne'-c'&&$hash_parentne'--cc') {7098# commitdiff with two commits given7099my$hash_parent_short=$hash_parent;7100if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {7101$hash_parent_short=substr($hash_parent,0,7);7102}7103$formats_nav.=7104' (from';7105for(my$i=0;$i< @{$co{'parents'}};$i++) {7106if($co{'parents'}[$i]eq$hash_parent) {7107$formats_nav.=' parent '. ($i+1);7108last;7109}7110}7111$formats_nav.=': '.7112$cgi->a({-href => href(action=>"commitdiff",7113 hash=>$hash_parent)},7114 esc_html($hash_parent_short)) .7115')';7116}elsif(!$co{'parent'}) {7117# --root commitdiff7118$formats_nav.=' (initial)';7119}elsif(scalar@{$co{'parents'}} ==1) {7120# single parent commit7121$formats_nav.=7122' (parent: '.7123$cgi->a({-href => href(action=>"commitdiff",7124 hash=>$co{'parent'})},7125 esc_html(substr($co{'parent'},0,7))) .7126')';7127}else{7128# merge commit7129if($hash_parenteq'--cc') {7130$formats_nav.=' | '.7131$cgi->a({-href => href(action=>"commitdiff",7132 hash=>$hash, hash_parent=>'-c')},7133'combined');7134}else{# $hash_parent eq '-c'7135$formats_nav.=' | '.7136$cgi->a({-href => href(action=>"commitdiff",7137 hash=>$hash, hash_parent=>'--cc')},7138'compact');7139}7140$formats_nav.=7141' (merge: '.7142join(' ',map{7143$cgi->a({-href => href(action=>"commitdiff",7144 hash=>$_)},7145 esc_html(substr($_,0,7)));7146} @{$co{'parents'}} ) .7147')';7148}7149}71507151my$hash_parent_param=$hash_parent;7152if(!defined$hash_parent_param) {7153# --cc for multiple parents, --root for parentless7154$hash_parent_param=7155@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';7156}71577158# read commitdiff7159my$fd;7160my@difftree;7161if($formateq'html') {7162open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7163"--no-commit-id","--patch-with-raw","--full-index",7164$hash_parent_param,$hash,"--"7165or die_error(500,"Open git-diff-tree failed");71667167while(my$line= <$fd>) {7168chomp$line;7169# empty line ends raw part of diff-tree output7170last unless$line;7171push@difftree,scalar parse_difftree_raw_line($line);7172}71737174}elsif($formateq'plain') {7175open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7176'-p',$hash_parent_param,$hash,"--"7177or die_error(500,"Open git-diff-tree failed");7178}elsif($formateq'patch') {7179# For commit ranges, we limit the output to the number of7180# patches specified in the 'patches' feature.7181# For single commits, we limit the output to a single patch,7182# diverging from the git-format-patch default.7183my@commit_spec= ();7184if($hash_parent) {7185if($patch_max>0) {7186push@commit_spec,"-$patch_max";7187}7188push@commit_spec,'-n',"$hash_parent..$hash";7189}else{7190if($params{-single}) {7191push@commit_spec,'-1';7192}else{7193if($patch_max>0) {7194push@commit_spec,"-$patch_max";7195}7196push@commit_spec,"-n";7197}7198push@commit_spec,'--root',$hash;7199}7200open$fd,"-|", git_cmd(),"format-patch",@diff_opts,7201'--encoding=utf8','--stdout',@commit_spec7202or die_error(500,"Open git-format-patch failed");7203}else{7204 die_error(400,"Unknown commitdiff format");7205}72067207# non-textual hash id's can be cached7208my$expires;7209if($hash=~m/^[0-9a-fA-F]{40}$/) {7210$expires="+1d";7211}72127213# write commit message7214if($formateq'html') {7215my$refs= git_get_references();7216my$ref= format_ref_marker($refs,$co{'id'});72177218 git_header_html(undef,$expires);7219 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);7220 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);7221print"<div class=\"title_text\">\n".7222"<table class=\"object_header\">\n";7223 git_print_authorship_rows(\%co);7224print"</table>".7225"</div>\n";7226print"<div class=\"page_body\">\n";7227if(@{$co{'comment'}} >1) {7228print"<div class=\"log\">\n";7229 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);7230print"</div>\n";# class="log"7231}72327233}elsif($formateq'plain') {7234my$refs= git_get_references("tags");7235my$tagname= git_get_rev_name_tags($hash);7236my$filename= basename($project) ."-$hash.patch";72377238print$cgi->header(7239-type =>'text/plain',7240-charset =>'utf-8',7241-expires =>$expires,7242-content_disposition =>'inline; filename="'."$filename".'"');7243my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});7244print"From: ". to_utf8($co{'author'}) ."\n";7245print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";7246print"Subject: ". to_utf8($co{'title'}) ."\n";72477248print"X-Git-Tag:$tagname\n"if$tagname;7249print"X-Git-Url: ".$cgi->self_url() ."\n\n";72507251foreachmy$line(@{$co{'comment'}}) {7252print to_utf8($line) ."\n";7253}7254print"---\n\n";7255}elsif($formateq'patch') {7256my$filename= basename($project) ."-$hash.patch";72577258print$cgi->header(7259-type =>'text/plain',7260-charset =>'utf-8',7261-expires =>$expires,7262-content_disposition =>'inline; filename="'."$filename".'"');7263}72647265# write patch7266if($formateq'html') {7267my$use_parents= !defined$hash_parent||7268$hash_parenteq'-c'||$hash_parenteq'--cc';7269 git_difftree_body(\@difftree,$hash,7270$use_parents? @{$co{'parents'}} :$hash_parent);7271print"<br/>\n";72727273 git_patchset_body($fd, \@difftree,$hash,7274$use_parents? @{$co{'parents'}} :$hash_parent);7275close$fd;7276print"</div>\n";# class="page_body"7277 git_footer_html();72787279}elsif($formateq'plain') {7280local$/=undef;7281print<$fd>;7282close$fd7283or print"Reading git-diff-tree failed\n";7284}elsif($formateq'patch') {7285local$/=undef;7286print<$fd>;7287close$fd7288or print"Reading git-format-patch failed\n";7289}7290}72917292sub git_commitdiff_plain {7293 git_commitdiff(-format =>'plain');7294}72957296# format-patch-style patches7297sub git_patch {7298 git_commitdiff(-format =>'patch', -single =>1);7299}73007301sub git_patches {7302 git_commitdiff(-format =>'patch');7303}73047305sub git_history {7306 git_log_generic('history', \&git_history_body,7307$hash_base,$hash_parent_base,7308$file_name,$hash);7309}73107311sub git_search {7312$searchtype||='commit';73137314# check if appropriate features are enabled7315 gitweb_check_feature('search')7316or die_error(403,"Search is disabled");7317if($searchtypeeq'pickaxe') {7318# pickaxe may take all resources of your box and run for several minutes7319# with every query - so decide by yourself how public you make this feature7320 gitweb_check_feature('pickaxe')7321or die_error(403,"Pickaxe search is disabled");7322}7323if($searchtypeeq'grep') {7324# grep search might be potentially CPU-intensive, too7325 gitweb_check_feature('grep')7326or die_error(403,"Grep search is disabled");7327}73287329if(!defined$searchtext) {7330 die_error(400,"Text field is empty");7331}7332if(!defined$hash) {7333$hash= git_get_head_hash($project);7334}7335my%co= parse_commit($hash);7336if(!%co) {7337 die_error(404,"Unknown commit object");7338}7339if(!defined$page) {7340$page=0;7341}73427343if($searchtypeeq'commit'||7344$searchtypeeq'author'||7345$searchtypeeq'committer') {7346 git_search_message(%co);7347}elsif($searchtypeeq'pickaxe') {7348 git_search_changes(%co);7349}elsif($searchtypeeq'grep') {7350 git_search_files(%co);7351}else{7352 die_error(400,"Unknown search type");7353}7354}73557356sub git_search_help {7357 git_header_html();7358 git_print_page_nav('','',$hash,$hash,$hash);7359print<<EOT;7360<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without7361regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,7362the pattern entered is recognized as the POSIX extended7363<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case7364insensitive).</p>7365<dl>7366<dt><b>commit</b></dt>7367<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>7368EOT7369my$have_grep= gitweb_check_feature('grep');7370if($have_grep) {7371print<<EOT;7372<dt><b>grep</b></dt>7373<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing7374 a different one) are searched for the given pattern. On large trees, this search can take7375a while and put some strain on the server, so please use it with some consideration. Note that7376due to git-grep peculiarity, currently if regexp mode is turned off, the matches are7377case-sensitive.</dd>7378EOT7379}7380print<<EOT;7381<dt><b>author</b></dt>7382<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>7383<dt><b>committer</b></dt>7384<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>7385EOT7386my$have_pickaxe= gitweb_check_feature('pickaxe');7387if($have_pickaxe) {7388print<<EOT;7389<dt><b>pickaxe</b></dt>7390<dd>All commits that caused the string to appear or disappear from any file (changes that7391added, removed or "modified" the string) will be listed. This search can take a while and7392takes a lot of strain on the server, so please use it wisely. Note that since you may be7393interested even in changes just changing the case as well, this search is case sensitive.</dd>7394EOT7395}7396print"</dl>\n";7397 git_footer_html();7398}73997400sub git_shortlog {7401 git_log_generic('shortlog', \&git_shortlog_body,7402$hash,$hash_parent);7403}74047405## ......................................................................7406## feeds (RSS, Atom; OPML)74077408sub git_feed {7409my$format=shift||'atom';7410my$have_blame= gitweb_check_feature('blame');74117412# Atom: http://www.atomenabled.org/developers/syndication/7413# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ7414if($formatne'rss'&&$formatne'atom') {7415 die_error(400,"Unknown web feed format");7416}74177418# log/feed of current (HEAD) branch, log of given branch, history of file/directory7419my$head=$hash||'HEAD';7420my@commitlist= parse_commits($head,150,0,$file_name);74217422my%latest_commit;7423my%latest_date;7424my$content_type="application/$format+xml";7425if(defined$cgi->http('HTTP_ACCEPT') &&7426$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {7427# browser (feed reader) prefers text/xml7428$content_type='text/xml';7429}7430if(defined($commitlist[0])) {7431%latest_commit= %{$commitlist[0]};7432my$latest_epoch=$latest_commit{'committer_epoch'};7433%latest_date= parse_date($latest_epoch,$latest_commit{'comitter_tz'});7434my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7435if(defined$if_modified) {7436my$since;7437if(eval{require HTTP::Date;1; }) {7438$since= HTTP::Date::str2time($if_modified);7439}elsif(eval{require Time::ParseDate;1; }) {7440$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7441}7442if(defined$since&&$latest_epoch<=$since) {7443print$cgi->header(7444-type =>$content_type,7445-charset =>'utf-8',7446-last_modified =>$latest_date{'rfc2822'},7447-status =>'304 Not Modified');7448return;7449}7450}7451print$cgi->header(7452-type =>$content_type,7453-charset =>'utf-8',7454-last_modified =>$latest_date{'rfc2822'});7455}else{7456print$cgi->header(7457-type =>$content_type,7458-charset =>'utf-8');7459}74607461# Optimization: skip generating the body if client asks only7462# for Last-Modified date.7463return if($cgi->request_method()eq'HEAD');74647465# header variables7466my$title="$site_name-$project/$action";7467my$feed_type='log';7468if(defined$hash) {7469$title.=" - '$hash'";7470$feed_type='branch log';7471if(defined$file_name) {7472$title.=" ::$file_name";7473$feed_type='history';7474}7475}elsif(defined$file_name) {7476$title.=" -$file_name";7477$feed_type='history';7478}7479$title.="$feed_type";7480my$descr= git_get_project_description($project);7481if(defined$descr) {7482$descr= esc_html($descr);7483}else{7484$descr="$project".7485($formateq'rss'?'RSS':'Atom') .7486" feed";7487}7488my$owner= git_get_project_owner($project);7489$owner= esc_html($owner);74907491#header7492my$alt_url;7493if(defined$file_name) {7494$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);7495}elsif(defined$hash) {7496$alt_url= href(-full=>1, action=>"log", hash=>$hash);7497}else{7498$alt_url= href(-full=>1, action=>"summary");7499}7500print qq!<?xml version="1.0" encoding="utf-8"?>\n!;7501if($formateq'rss') {7502print<<XML;7503<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">7504<channel>7505XML7506print"<title>$title</title>\n".7507"<link>$alt_url</link>\n".7508"<description>$descr</description>\n".7509"<language>en</language>\n".7510# project owner is responsible for 'editorial' content7511"<managingEditor>$owner</managingEditor>\n";7512if(defined$logo||defined$favicon) {7513# prefer the logo to the favicon, since RSS7514# doesn't allow both7515my$img= esc_url($logo||$favicon);7516print"<image>\n".7517"<url>$img</url>\n".7518"<title>$title</title>\n".7519"<link>$alt_url</link>\n".7520"</image>\n";7521}7522if(%latest_date) {7523print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";7524print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";7525}7526print"<generator>gitweb v.$version/$git_version</generator>\n";7527}elsif($formateq'atom') {7528print<<XML;7529<feed xmlns="http://www.w3.org/2005/Atom">7530XML7531print"<title>$title</title>\n".7532"<subtitle>$descr</subtitle>\n".7533'<link rel="alternate" type="text/html" href="'.7534$alt_url.'" />'."\n".7535'<link rel="self" type="'.$content_type.'" href="'.7536$cgi->self_url() .'" />'."\n".7537"<id>". href(-full=>1) ."</id>\n".7538# use project owner for feed author7539"<author><name>$owner</name></author>\n";7540if(defined$favicon) {7541print"<icon>". esc_url($favicon) ."</icon>\n";7542}7543if(defined$logo) {7544# not twice as wide as tall: 72 x 27 pixels7545print"<logo>". esc_url($logo) ."</logo>\n";7546}7547if(!%latest_date) {7548# dummy date to keep the feed valid until commits trickle in:7549print"<updated>1970-01-01T00:00:00Z</updated>\n";7550}else{7551print"<updated>$latest_date{'iso-8601'}</updated>\n";7552}7553print"<generator version='$version/$git_version'>gitweb</generator>\n";7554}75557556# contents7557for(my$i=0;$i<=$#commitlist;$i++) {7558my%co= %{$commitlist[$i]};7559my$commit=$co{'id'};7560# we read 150, we always show 30 and the ones more recent than 48 hours7561if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {7562last;7563}7564my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});75657566# get list of changed files7567open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7568$co{'parent'} ||"--root",7569$co{'id'},"--", (defined$file_name?$file_name: ())7570ornext;7571my@difftree=map{chomp;$_} <$fd>;7572close$fd7573ornext;75747575# print element (entry, item)7576my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);7577if($formateq'rss') {7578print"<item>\n".7579"<title>". esc_html($co{'title'}) ."</title>\n".7580"<author>". esc_html($co{'author'}) ."</author>\n".7581"<pubDate>$cd{'rfc2822'}</pubDate>\n".7582"<guid isPermaLink=\"true\">$co_url</guid>\n".7583"<link>$co_url</link>\n".7584"<description>". esc_html($co{'title'}) ."</description>\n".7585"<content:encoded>".7586"<![CDATA[\n";7587}elsif($formateq'atom') {7588print"<entry>\n".7589"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".7590"<updated>$cd{'iso-8601'}</updated>\n".7591"<author>\n".7592" <name>". esc_html($co{'author_name'}) ."</name>\n";7593if($co{'author_email'}) {7594print" <email>". esc_html($co{'author_email'}) ."</email>\n";7595}7596print"</author>\n".7597# use committer for contributor7598"<contributor>\n".7599" <name>". esc_html($co{'committer_name'}) ."</name>\n";7600if($co{'committer_email'}) {7601print" <email>". esc_html($co{'committer_email'}) ."</email>\n";7602}7603print"</contributor>\n".7604"<published>$cd{'iso-8601'}</published>\n".7605"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".7606"<id>$co_url</id>\n".7607"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".7608"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";7609}7610my$comment=$co{'comment'};7611print"<pre>\n";7612foreachmy$line(@$comment) {7613$line= esc_html($line);7614print"$line\n";7615}7616print"</pre><ul>\n";7617foreachmy$difftree_line(@difftree) {7618my%difftree= parse_difftree_raw_line($difftree_line);7619next if!$difftree{'from_id'};76207621my$file=$difftree{'file'} ||$difftree{'to_file'};76227623print"<li>".7624"[".7625$cgi->a({-href => href(-full=>1, action=>"blobdiff",7626 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},7627 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},7628 file_name=>$file, file_parent=>$difftree{'from_file'}),7629-title =>"diff"},'D');7630if($have_blame) {7631print$cgi->a({-href => href(-full=>1, action=>"blame",7632 file_name=>$file, hash_base=>$commit),7633-title =>"blame"},'B');7634}7635# if this is not a feed of a file history7636if(!defined$file_name||$file_namene$file) {7637print$cgi->a({-href => href(-full=>1, action=>"history",7638 file_name=>$file, hash=>$commit),7639-title =>"history"},'H');7640}7641$file= esc_path($file);7642print"] ".7643"$file</li>\n";7644}7645if($formateq'rss') {7646print"</ul>]]>\n".7647"</content:encoded>\n".7648"</item>\n";7649}elsif($formateq'atom') {7650print"</ul>\n</div>\n".7651"</content>\n".7652"</entry>\n";7653}7654}76557656# end of feed7657if($formateq'rss') {7658print"</channel>\n</rss>\n";7659}elsif($formateq'atom') {7660print"</feed>\n";7661}7662}76637664sub git_rss {7665 git_feed('rss');7666}76677668sub git_atom {7669 git_feed('atom');7670}76717672sub git_opml {7673my@list= git_get_projects_list();7674if(!@list) {7675 die_error(404,"No projects found");7676}76777678print$cgi->header(7679-type =>'text/xml',7680-charset =>'utf-8',7681-content_disposition =>'inline; filename="opml.xml"');76827683print<<XML;7684<?xml version="1.0" encoding="utf-8"?>7685<opml version="1.0">7686<head>7687 <title>$site_nameOPML Export</title>7688</head>7689<body>7690<outline text="git RSS feeds">7691XML76927693foreachmy$pr(@list) {7694my%proj=%$pr;7695my$head= git_get_head_hash($proj{'path'});7696if(!defined$head) {7697next;7698}7699$git_dir="$projectroot/$proj{'path'}";7700my%co= parse_commit($head);7701if(!%co) {7702next;7703}77047705my$path= esc_html(chop_str($proj{'path'},25,5));7706my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);7707my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);7708print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";7709}7710print<<XML;7711</outline>7712</body>7713</opml>7714XML7715}