1#!/usr/bin/perl 2 3# gitweb - simple web interface to track changes in git repositories 4# 5# (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org> 6# (C) 2005, Christian Gierke 7# 8# This program is licensed under the GPLv2 9 10use5.008; 11use strict; 12use warnings; 13use CGI qw(:standard :escapeHTML -nosticky); 14use CGI::Util qw(unescape); 15use CGI::Carp qw(fatalsToBrowser set_message); 16use Encode; 17use Fcntl ':mode'; 18use File::Find qw(); 19use File::Basename qw(basename); 20use Time::HiRes qw(gettimeofday tv_interval); 21binmode STDOUT,':utf8'; 22 23our$t0= [ gettimeofday() ]; 24our$number_of_git_cmds=0; 25 26BEGIN{ 27 CGI->compile()if$ENV{'MOD_PERL'}; 28} 29 30our$version="++GIT_VERSION++"; 31 32our($my_url,$my_uri,$base_url,$path_info,$home_link); 33sub evaluate_uri { 34our$cgi; 35 36our$my_url=$cgi->url(); 37our$my_uri=$cgi->url(-absolute =>1); 38 39# Base URL for relative URLs in gitweb ($logo, $favicon, ...), 40# needed and used only for URLs with nonempty PATH_INFO 41our$base_url=$my_url; 42 43# When the script is used as DirectoryIndex, the URL does not contain the name 44# of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we 45# have to do it ourselves. We make $path_info global because it's also used 46# later on. 47# 48# Another issue with the script being the DirectoryIndex is that the resulting 49# $my_url data is not the full script URL: this is good, because we want 50# generated links to keep implying the script name if it wasn't explicitly 51# indicated in the URL we're handling, but it means that $my_url cannot be used 52# as base URL. 53# Therefore, if we needed to strip PATH_INFO, then we know that we have 54# to build the base URL ourselves: 55our$path_info=$ENV{"PATH_INFO"}; 56if($path_info) { 57if($my_url=~ s,\Q$path_info\E$,, && 58$my_uri=~ s,\Q$path_info\E$,, && 59defined$ENV{'SCRIPT_NAME'}) { 60$base_url=$cgi->url(-base =>1) .$ENV{'SCRIPT_NAME'}; 61} 62} 63 64# target of the home link on top of all pages 65our$home_link=$my_uri||"/"; 66} 67 68# core git executable to use 69# this can just be "git" if your webserver has a sensible PATH 70our$GIT="++GIT_BINDIR++/git"; 71 72# absolute fs-path which will be prepended to the project path 73#our $projectroot = "/pub/scm"; 74our$projectroot="++GITWEB_PROJECTROOT++"; 75 76# fs traversing limit for getting project list 77# the number is relative to the projectroot 78our$project_maxdepth="++GITWEB_PROJECT_MAXDEPTH++"; 79 80# string of the home link on top of all pages 81our$home_link_str="++GITWEB_HOME_LINK_STR++"; 82 83# name of your site or organization to appear in page titles 84# replace this with something more descriptive for clearer bookmarks 85our$site_name="++GITWEB_SITENAME++" 86|| ($ENV{'SERVER_NAME'} ||"Untitled") ." Git"; 87 88# filename of html text to include at top of each page 89our$site_header="++GITWEB_SITE_HEADER++"; 90# html text to include at home page 91our$home_text="++GITWEB_HOMETEXT++"; 92# filename of html text to include at bottom of each page 93our$site_footer="++GITWEB_SITE_FOOTER++"; 94 95# URI of stylesheets 96our@stylesheets= ("++GITWEB_CSS++"); 97# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG. 98our$stylesheet=undef; 99# URI of GIT logo (72x27 size) 100our$logo="++GITWEB_LOGO++"; 101# URI of GIT favicon, assumed to be image/png type 102our$favicon="++GITWEB_FAVICON++"; 103# URI of gitweb.js (JavaScript code for gitweb) 104our$javascript="++GITWEB_JS++"; 105 106# URI and label (title) of GIT logo link 107#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/"; 108#our $logo_label = "git documentation"; 109our$logo_url="http://git-scm.com/"; 110our$logo_label="git homepage"; 111 112# source of projects list 113our$projects_list="++GITWEB_LIST++"; 114 115# the width (in characters) of the projects list "Description" column 116our$projects_list_description_width=25; 117 118# group projects by category on the projects list 119# (enabled if this variable evaluates to true) 120our$projects_list_group_categories=0; 121 122# default category if none specified 123# (leave the empty string for no category) 124our$project_list_default_category=""; 125 126# default order of projects list 127# valid values are none, project, descr, owner, and age 128our$default_projects_order="project"; 129 130# show repository only if this file exists 131# (only effective if this variable evaluates to true) 132our$export_ok="++GITWEB_EXPORT_OK++"; 133 134# show repository only if this subroutine returns true 135# when given the path to the project, for example: 136# sub { return -e "$_[0]/git-daemon-export-ok"; } 137our$export_auth_hook=undef; 138 139# only allow viewing of repositories also shown on the overview page 140our$strict_export="++GITWEB_STRICT_EXPORT++"; 141 142# list of git base URLs used for URL to where fetch project from, 143# i.e. full URL is "$git_base_url/$project" 144our@git_base_url_list=grep{$_ne''} ("++GITWEB_BASE_URL++"); 145 146# default blob_plain mimetype and default charset for text/plain blob 147our$default_blob_plain_mimetype='text/plain'; 148our$default_text_plain_charset=undef; 149 150# file to use for guessing MIME types before trying /etc/mime.types 151# (relative to the current git repository) 152our$mimetypes_file=undef; 153 154# assume this charset if line contains non-UTF-8 characters; 155# it should be valid encoding (see Encoding::Supported(3pm) for list), 156# for which encoding all byte sequences are valid, for example 157# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it 158# could be even 'utf-8' for the old behavior) 159our$fallback_encoding='latin1'; 160 161# rename detection options for git-diff and git-diff-tree 162# - default is '-M', with the cost proportional to 163# (number of removed files) * (number of new files). 164# - more costly is '-C' (which implies '-M'), with the cost proportional to 165# (number of changed files + number of removed files) * (number of new files) 166# - even more costly is '-C', '--find-copies-harder' with cost 167# (number of files in the original tree) * (number of new files) 168# - one might want to include '-B' option, e.g. '-B', '-M' 169our@diff_opts= ('-M');# taken from git_commit 170 171# Disables features that would allow repository owners to inject script into 172# the gitweb domain. 173our$prevent_xss=0; 174 175# Path to the highlight executable to use (must be the one from 176# http://www.andre-simon.de due to assumptions about parameters and output). 177# Useful if highlight is not installed on your webserver's PATH. 178# [Default: highlight] 179our$highlight_bin="++HIGHLIGHT_BIN++"; 180 181# information about snapshot formats that gitweb is capable of serving 182our%known_snapshot_formats= ( 183# name => { 184# 'display' => display name, 185# 'type' => mime type, 186# 'suffix' => filename suffix, 187# 'format' => --format for git-archive, 188# 'compressor' => [compressor command and arguments] 189# (array reference, optional) 190# 'disabled' => boolean (optional)} 191# 192'tgz'=> { 193'display'=>'tar.gz', 194'type'=>'application/x-gzip', 195'suffix'=>'.tar.gz', 196'format'=>'tar', 197'compressor'=> ['gzip','-n']}, 198 199'tbz2'=> { 200'display'=>'tar.bz2', 201'type'=>'application/x-bzip2', 202'suffix'=>'.tar.bz2', 203'format'=>'tar', 204'compressor'=> ['bzip2']}, 205 206'txz'=> { 207'display'=>'tar.xz', 208'type'=>'application/x-xz', 209'suffix'=>'.tar.xz', 210'format'=>'tar', 211'compressor'=> ['xz'], 212'disabled'=>1}, 213 214'zip'=> { 215'display'=>'zip', 216'type'=>'application/x-zip', 217'suffix'=>'.zip', 218'format'=>'zip'}, 219); 220 221# Aliases so we understand old gitweb.snapshot values in repository 222# configuration. 223our%known_snapshot_format_aliases= ( 224'gzip'=>'tgz', 225'bzip2'=>'tbz2', 226'xz'=>'txz', 227 228# backward compatibility: legacy gitweb config support 229'x-gzip'=>undef,'gz'=>undef, 230'x-bzip2'=>undef,'bz2'=>undef, 231'x-zip'=>undef,''=>undef, 232); 233 234# Pixel sizes for icons and avatars. If the default font sizes or lineheights 235# are changed, it may be appropriate to change these values too via 236# $GITWEB_CONFIG. 237our%avatar_size= ( 238'default'=>16, 239'double'=>32 240); 241 242# Used to set the maximum load that we will still respond to gitweb queries. 243# If server load exceed this value then return "503 server busy" error. 244# If gitweb cannot determined server load, it is taken to be 0. 245# Leave it undefined (or set to 'undef') to turn off load checking. 246our$maxload=300; 247 248# configuration for 'highlight' (http://www.andre-simon.de/) 249# match by basename 250our%highlight_basename= ( 251#'Program' => 'py', 252#'Library' => 'py', 253'SConstruct'=>'py',# SCons equivalent of Makefile 254'Makefile'=>'make', 255); 256# match by extension 257our%highlight_ext= ( 258# main extensions, defining name of syntax; 259# see files in /usr/share/highlight/langDefs/ directory 260map{$_=>$_} 261qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl sql make), 262# alternate extensions, see /etc/highlight/filetypes.conf 263'h'=>'c', 264map{$_=>'sh'}qw(bash zsh ksh), 265map{$_=>'cpp'}qw(cxx c++ cc), 266map{$_=>'php'}qw(php3 php4 php5 phps), 267map{$_=>'pl'}qw(perl pm),# perhaps also 'cgi' 268map{$_=>'make'}qw(mak mk), 269map{$_=>'xml'}qw(xhtml html htm), 270); 271 272# You define site-wide feature defaults here; override them with 273# $GITWEB_CONFIG as necessary. 274our%feature= ( 275# feature => { 276# 'sub' => feature-sub (subroutine), 277# 'override' => allow-override (boolean), 278# 'default' => [ default options...] (array reference)} 279# 280# if feature is overridable (it means that allow-override has true value), 281# then feature-sub will be called with default options as parameters; 282# return value of feature-sub indicates if to enable specified feature 283# 284# if there is no 'sub' key (no feature-sub), then feature cannot be 285# overridden 286# 287# use gitweb_get_feature(<feature>) to retrieve the <feature> value 288# (an array) or gitweb_check_feature(<feature>) to check if <feature> 289# is enabled 290 291# Enable the 'blame' blob view, showing the last commit that modified 292# each line in the file. This can be very CPU-intensive. 293 294# To enable system wide have in $GITWEB_CONFIG 295# $feature{'blame'}{'default'} = [1]; 296# To have project specific config enable override in $GITWEB_CONFIG 297# $feature{'blame'}{'override'} = 1; 298# and in project config gitweb.blame = 0|1; 299'blame'=> { 300'sub'=>sub{ feature_bool('blame',@_) }, 301'override'=>0, 302'default'=> [0]}, 303 304# Enable the 'snapshot' link, providing a compressed archive of any 305# tree. This can potentially generate high traffic if you have large 306# project. 307 308# Value is a list of formats defined in %known_snapshot_formats that 309# you wish to offer. 310# To disable system wide have in $GITWEB_CONFIG 311# $feature{'snapshot'}{'default'} = []; 312# To have project specific config enable override in $GITWEB_CONFIG 313# $feature{'snapshot'}{'override'} = 1; 314# and in project config, a comma-separated list of formats or "none" 315# to disable. Example: gitweb.snapshot = tbz2,zip; 316'snapshot'=> { 317'sub'=> \&feature_snapshot, 318'override'=>0, 319'default'=> ['tgz']}, 320 321# Enable text search, which will list the commits which match author, 322# committer or commit text to a given string. Enabled by default. 323# Project specific override is not supported. 324'search'=> { 325'override'=>0, 326'default'=> [1]}, 327 328# Enable grep search, which will list the files in currently selected 329# tree containing the given string. Enabled by default. This can be 330# potentially CPU-intensive, of course. 331 332# To enable system wide have in $GITWEB_CONFIG 333# $feature{'grep'}{'default'} = [1]; 334# To have project specific config enable override in $GITWEB_CONFIG 335# $feature{'grep'}{'override'} = 1; 336# and in project config gitweb.grep = 0|1; 337'grep'=> { 338'sub'=>sub{ feature_bool('grep',@_) }, 339'override'=>0, 340'default'=> [1]}, 341 342# Enable the pickaxe search, which will list the commits that modified 343# a given string in a file. This can be practical and quite faster 344# alternative to 'blame', but still potentially CPU-intensive. 345 346# To enable system wide have in $GITWEB_CONFIG 347# $feature{'pickaxe'}{'default'} = [1]; 348# To have project specific config enable override in $GITWEB_CONFIG 349# $feature{'pickaxe'}{'override'} = 1; 350# and in project config gitweb.pickaxe = 0|1; 351'pickaxe'=> { 352'sub'=>sub{ feature_bool('pickaxe',@_) }, 353'override'=>0, 354'default'=> [1]}, 355 356# Enable showing size of blobs in a 'tree' view, in a separate 357# column, similar to what 'ls -l' does. This cost a bit of IO. 358 359# To disable system wide have in $GITWEB_CONFIG 360# $feature{'show-sizes'}{'default'} = [0]; 361# To have project specific config enable override in $GITWEB_CONFIG 362# $feature{'show-sizes'}{'override'} = 1; 363# and in project config gitweb.showsizes = 0|1; 364'show-sizes'=> { 365'sub'=>sub{ feature_bool('showsizes',@_) }, 366'override'=>0, 367'default'=> [1]}, 368 369# Make gitweb use an alternative format of the URLs which can be 370# more readable and natural-looking: project name is embedded 371# directly in the path and the query string contains other 372# auxiliary information. All gitweb installations recognize 373# URL in either format; this configures in which formats gitweb 374# generates links. 375 376# To enable system wide have in $GITWEB_CONFIG 377# $feature{'pathinfo'}{'default'} = [1]; 378# Project specific override is not supported. 379 380# Note that you will need to change the default location of CSS, 381# favicon, logo and possibly other files to an absolute URL. Also, 382# if gitweb.cgi serves as your indexfile, you will need to force 383# $my_uri to contain the script name in your $GITWEB_CONFIG. 384'pathinfo'=> { 385'override'=>0, 386'default'=> [0]}, 387 388# Make gitweb consider projects in project root subdirectories 389# to be forks of existing projects. Given project $projname.git, 390# projects matching $projname/*.git will not be shown in the main 391# projects list, instead a '+' mark will be added to $projname 392# there and a 'forks' view will be enabled for the project, listing 393# all the forks. If project list is taken from a file, forks have 394# to be listed after the main project. 395 396# To enable system wide have in $GITWEB_CONFIG 397# $feature{'forks'}{'default'} = [1]; 398# Project specific override is not supported. 399'forks'=> { 400'override'=>0, 401'default'=> [0]}, 402 403# Insert custom links to the action bar of all project pages. 404# This enables you mainly to link to third-party scripts integrating 405# into gitweb; e.g. git-browser for graphical history representation 406# or custom web-based repository administration interface. 407 408# The 'default' value consists of a list of triplets in the form 409# (label, link, position) where position is the label after which 410# to insert the link and link is a format string where %n expands 411# to the project name, %f to the project path within the filesystem, 412# %h to the current hash (h gitweb parameter) and %b to the current 413# hash base (hb gitweb parameter); %% expands to %. 414 415# To enable system wide have in $GITWEB_CONFIG e.g. 416# $feature{'actions'}{'default'} = [('graphiclog', 417# '/git-browser/by-commit.html?r=%n', 'summary')]; 418# Project specific override is not supported. 419'actions'=> { 420'override'=>0, 421'default'=> []}, 422 423# Allow gitweb scan project content tags of project repository, 424# and display the popular Web 2.0-ish "tag cloud" near the projects 425# list. Note that this is something COMPLETELY different from the 426# normal Git tags. 427 428# gitweb by itself can show existing tags, but it does not handle 429# tagging itself; you need to do it externally, outside gitweb. 430# The format is described in git_get_project_ctags() subroutine. 431# You may want to install the HTML::TagCloud Perl module to get 432# a pretty tag cloud instead of just a list of tags. 433 434# To enable system wide have in $GITWEB_CONFIG 435# $feature{'ctags'}{'default'} = [1]; 436# Project specific override is not supported. 437 438# In the future whether ctags editing is enabled might depend 439# on the value, but using 1 should always mean no editing of ctags. 440'ctags'=> { 441'override'=>0, 442'default'=> [0]}, 443 444# The maximum number of patches in a patchset generated in patch 445# view. Set this to 0 or undef to disable patch view, or to a 446# negative number to remove any limit. 447 448# To disable system wide have in $GITWEB_CONFIG 449# $feature{'patches'}{'default'} = [0]; 450# To have project specific config enable override in $GITWEB_CONFIG 451# $feature{'patches'}{'override'} = 1; 452# and in project config gitweb.patches = 0|n; 453# where n is the maximum number of patches allowed in a patchset. 454'patches'=> { 455'sub'=> \&feature_patches, 456'override'=>0, 457'default'=> [16]}, 458 459# Avatar support. When this feature is enabled, views such as 460# shortlog or commit will display an avatar associated with 461# the email of the committer(s) and/or author(s). 462 463# Currently available providers are gravatar and picon. 464# If an unknown provider is specified, the feature is disabled. 465 466# Gravatar depends on Digest::MD5. 467# Picon currently relies on the indiana.edu database. 468 469# To enable system wide have in $GITWEB_CONFIG 470# $feature{'avatar'}{'default'} = ['<provider>']; 471# where <provider> is either gravatar or picon. 472# To have project specific config enable override in $GITWEB_CONFIG 473# $feature{'avatar'}{'override'} = 1; 474# and in project config gitweb.avatar = <provider>; 475'avatar'=> { 476'sub'=> \&feature_avatar, 477'override'=>0, 478'default'=> ['']}, 479 480# Enable displaying how much time and how many git commands 481# it took to generate and display page. Disabled by default. 482# Project specific override is not supported. 483'timed'=> { 484'override'=>0, 485'default'=> [0]}, 486 487# Enable turning some links into links to actions which require 488# JavaScript to run (like 'blame_incremental'). Not enabled by 489# default. Project specific override is currently not supported. 490'javascript-actions'=> { 491'override'=>0, 492'default'=> [0]}, 493 494# Syntax highlighting support. This is based on Daniel Svensson's 495# and Sham Chukoury's work in gitweb-xmms2.git. 496# It requires the 'highlight' program present in $PATH, 497# and therefore is disabled by default. 498 499# To enable system wide have in $GITWEB_CONFIG 500# $feature{'highlight'}{'default'} = [1]; 501 502'highlight'=> { 503'sub'=>sub{ feature_bool('highlight',@_) }, 504'override'=>0, 505'default'=> [0]}, 506 507# Enable displaying of remote heads in the heads list 508 509# To enable system wide have in $GITWEB_CONFIG 510# $feature{'remote_heads'}{'default'} = [1]; 511# To have project specific config enable override in $GITWEB_CONFIG 512# $feature{'remote_heads'}{'override'} = 1; 513# and in project config gitweb.remote_heads = 0|1; 514'remote_heads'=> { 515'sub'=>sub{ feature_bool('remote_heads',@_) }, 516'override'=>0, 517'default'=> [0]}, 518); 519 520sub gitweb_get_feature { 521my($name) =@_; 522return unlessexists$feature{$name}; 523my($sub,$override,@defaults) = ( 524$feature{$name}{'sub'}, 525$feature{$name}{'override'}, 526@{$feature{$name}{'default'}}); 527# project specific override is possible only if we have project 528our$git_dir;# global variable, declared later 529if(!$override|| !defined$git_dir) { 530return@defaults; 531} 532if(!defined$sub) { 533warn"feature$nameis not overridable"; 534return@defaults; 535} 536return$sub->(@defaults); 537} 538 539# A wrapper to check if a given feature is enabled. 540# With this, you can say 541# 542# my $bool_feat = gitweb_check_feature('bool_feat'); 543# gitweb_check_feature('bool_feat') or somecode; 544# 545# instead of 546# 547# my ($bool_feat) = gitweb_get_feature('bool_feat'); 548# (gitweb_get_feature('bool_feat'))[0] or somecode; 549# 550sub gitweb_check_feature { 551return(gitweb_get_feature(@_))[0]; 552} 553 554 555sub feature_bool { 556my$key=shift; 557my($val) = git_get_project_config($key,'--bool'); 558 559if(!defined$val) { 560return($_[0]); 561}elsif($valeq'true') { 562return(1); 563}elsif($valeq'false') { 564return(0); 565} 566} 567 568sub feature_snapshot { 569my(@fmts) =@_; 570 571my($val) = git_get_project_config('snapshot'); 572 573if($val) { 574@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 575} 576 577return@fmts; 578} 579 580sub feature_patches { 581my@val= (git_get_project_config('patches','--int')); 582 583if(@val) { 584return@val; 585} 586 587return($_[0]); 588} 589 590sub feature_avatar { 591my@val= (git_get_project_config('avatar')); 592 593return@val?@val:@_; 594} 595 596# checking HEAD file with -e is fragile if the repository was 597# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 598# and then pruned. 599sub check_head_link { 600my($dir) =@_; 601my$headfile="$dir/HEAD"; 602return((-e $headfile) || 603(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 604} 605 606sub check_export_ok { 607my($dir) =@_; 608return(check_head_link($dir) && 609(!$export_ok|| -e "$dir/$export_ok") && 610(!$export_auth_hook||$export_auth_hook->($dir))); 611} 612 613# process alternate names for backward compatibility 614# filter out unsupported (unknown) snapshot formats 615sub filter_snapshot_fmts { 616my@fmts=@_; 617 618@fmts=map{ 619exists$known_snapshot_format_aliases{$_} ? 620$known_snapshot_format_aliases{$_} :$_}@fmts; 621@fmts=grep{ 622exists$known_snapshot_formats{$_} && 623!$known_snapshot_formats{$_}{'disabled'}}@fmts; 624} 625 626# If it is set to code reference, it is code that it is to be run once per 627# request, allowing updating configurations that change with each request, 628# while running other code in config file only once. 629# 630# Otherwise, if it is false then gitweb would process config file only once; 631# if it is true then gitweb config would be run for each request. 632our$per_request_config=1; 633 634# read and parse gitweb config file given by its parameter. 635# returns true on success, false on recoverable error, allowing 636# to chain this subroutine, using first file that exists. 637# dies on errors during parsing config file, as it is unrecoverable. 638sub read_config_file { 639my$filename=shift; 640return unlessdefined$filename; 641# die if there are errors parsing config file 642if(-e $filename) { 643do$filename; 644die$@if$@; 645return1; 646} 647return; 648} 649 650our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM); 651sub evaluate_gitweb_config { 652our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 653our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 654 655# use first config file that exists 656 read_config_file($GITWEB_CONFIG)or 657 read_config_file($GITWEB_CONFIG_SYSTEM); 658} 659 660# Get loadavg of system, to compare against $maxload. 661# Currently it requires '/proc/loadavg' present to get loadavg; 662# if it is not present it returns 0, which means no load checking. 663sub get_loadavg { 664if( -e '/proc/loadavg'){ 665open my$fd,'<','/proc/loadavg' 666orreturn0; 667my@load=split(/\s+/,scalar<$fd>); 668close$fd; 669 670# The first three columns measure CPU and IO utilization of the last one, 671# five, and 10 minute periods. The fourth column shows the number of 672# currently running processes and the total number of processes in the m/n 673# format. The last column displays the last process ID used. 674return$load[0] ||0; 675} 676# additional checks for load average should go here for things that don't export 677# /proc/loadavg 678 679return0; 680} 681 682# version of the core git binary 683our$git_version; 684sub evaluate_git_version { 685our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 686$number_of_git_cmds++; 687} 688 689sub check_loadavg { 690if(defined$maxload&& get_loadavg() >$maxload) { 691 die_error(503,"The load average on the server is too high"); 692} 693} 694 695# ====================================================================== 696# input validation and dispatch 697 698# input parameters can be collected from a variety of sources (presently, CGI 699# and PATH_INFO), so we define an %input_params hash that collects them all 700# together during validation: this allows subsequent uses (e.g. href()) to be 701# agnostic of the parameter origin 702 703our%input_params= (); 704 705# input parameters are stored with the long parameter name as key. This will 706# also be used in the href subroutine to convert parameters to their CGI 707# equivalent, and since the href() usage is the most frequent one, we store 708# the name -> CGI key mapping here, instead of the reverse. 709# 710# XXX: Warning: If you touch this, check the search form for updating, 711# too. 712 713our@cgi_param_mapping= ( 714 project =>"p", 715 action =>"a", 716 file_name =>"f", 717 file_parent =>"fp", 718 hash =>"h", 719 hash_parent =>"hp", 720 hash_base =>"hb", 721 hash_parent_base =>"hpb", 722 page =>"pg", 723 order =>"o", 724 searchtext =>"s", 725 searchtype =>"st", 726 snapshot_format =>"sf", 727 extra_options =>"opt", 728 search_use_regexp =>"sr", 729 ctag =>"by_tag", 730# this must be last entry (for manipulation from JavaScript) 731 javascript =>"js" 732); 733our%cgi_param_mapping=@cgi_param_mapping; 734 735# we will also need to know the possible actions, for validation 736our%actions= ( 737"blame"=> \&git_blame, 738"blame_incremental"=> \&git_blame_incremental, 739"blame_data"=> \&git_blame_data, 740"blobdiff"=> \&git_blobdiff, 741"blobdiff_plain"=> \&git_blobdiff_plain, 742"blob"=> \&git_blob, 743"blob_plain"=> \&git_blob_plain, 744"commitdiff"=> \&git_commitdiff, 745"commitdiff_plain"=> \&git_commitdiff_plain, 746"commit"=> \&git_commit, 747"forks"=> \&git_forks, 748"heads"=> \&git_heads, 749"history"=> \&git_history, 750"log"=> \&git_log, 751"patch"=> \&git_patch, 752"patches"=> \&git_patches, 753"remotes"=> \&git_remotes, 754"rss"=> \&git_rss, 755"atom"=> \&git_atom, 756"search"=> \&git_search, 757"search_help"=> \&git_search_help, 758"shortlog"=> \&git_shortlog, 759"summary"=> \&git_summary, 760"tag"=> \&git_tag, 761"tags"=> \&git_tags, 762"tree"=> \&git_tree, 763"snapshot"=> \&git_snapshot, 764"object"=> \&git_object, 765# those below don't need $project 766"opml"=> \&git_opml, 767"project_list"=> \&git_project_list, 768"project_index"=> \&git_project_index, 769); 770 771# finally, we have the hash of allowed extra_options for the commands that 772# allow them 773our%allowed_options= ( 774"--no-merges"=> [qw(rss atom log shortlog history)], 775); 776 777# fill %input_params with the CGI parameters. All values except for 'opt' 778# should be single values, but opt can be an array. We should probably 779# build an array of parameters that can be multi-valued, but since for the time 780# being it's only this one, we just single it out 781sub evaluate_query_params { 782our$cgi; 783 784while(my($name,$symbol) =each%cgi_param_mapping) { 785if($symboleq'opt') { 786$input_params{$name} = [$cgi->param($symbol) ]; 787}else{ 788$input_params{$name} =$cgi->param($symbol); 789} 790} 791} 792 793# now read PATH_INFO and update the parameter list for missing parameters 794sub evaluate_path_info { 795return ifdefined$input_params{'project'}; 796return if!$path_info; 797$path_info=~ s,^/+,,; 798return if!$path_info; 799 800# find which part of PATH_INFO is project 801my$project=$path_info; 802$project=~ s,/+$,,; 803while($project&& !check_head_link("$projectroot/$project")) { 804$project=~ s,/*[^/]*$,,; 805} 806return unless$project; 807$input_params{'project'} =$project; 808 809# do not change any parameters if an action is given using the query string 810return if$input_params{'action'}; 811$path_info=~ s,^\Q$project\E/*,,; 812 813# next, check if we have an action 814my$action=$path_info; 815$action=~ s,/.*$,,; 816if(exists$actions{$action}) { 817$path_info=~ s,^$action/*,,; 818$input_params{'action'} =$action; 819} 820 821# list of actions that want hash_base instead of hash, but can have no 822# pathname (f) parameter 823my@wants_base= ( 824'tree', 825'history', 826); 827 828# we want to catch, among others 829# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 830my($parentrefname,$parentpathname,$refname,$pathname) = 831($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/); 832 833# first, analyze the 'current' part 834if(defined$pathname) { 835# we got "branch:filename" or "branch:dir/" 836# we could use git_get_type(branch:pathname), but: 837# - it needs $git_dir 838# - it does a git() call 839# - the convention of terminating directories with a slash 840# makes it superfluous 841# - embedding the action in the PATH_INFO would make it even 842# more superfluous 843$pathname=~ s,^/+,,; 844if(!$pathname||substr($pathname, -1)eq"/") { 845$input_params{'action'} ||="tree"; 846$pathname=~ s,/$,,; 847}else{ 848# the default action depends on whether we had parent info 849# or not 850if($parentrefname) { 851$input_params{'action'} ||="blobdiff_plain"; 852}else{ 853$input_params{'action'} ||="blob_plain"; 854} 855} 856$input_params{'hash_base'} ||=$refname; 857$input_params{'file_name'} ||=$pathname; 858}elsif(defined$refname) { 859# we got "branch". In this case we have to choose if we have to 860# set hash or hash_base. 861# 862# Most of the actions without a pathname only want hash to be 863# set, except for the ones specified in @wants_base that want 864# hash_base instead. It should also be noted that hand-crafted 865# links having 'history' as an action and no pathname or hash 866# set will fail, but that happens regardless of PATH_INFO. 867if(defined$parentrefname) { 868# if there is parent let the default be 'shortlog' action 869# (for http://git.example.com/repo.git/A..B links); if there 870# is no parent, dispatch will detect type of object and set 871# action appropriately if required (if action is not set) 872$input_params{'action'} ||="shortlog"; 873} 874if($input_params{'action'} && 875grep{$_eq$input_params{'action'} }@wants_base) { 876$input_params{'hash_base'} ||=$refname; 877}else{ 878$input_params{'hash'} ||=$refname; 879} 880} 881 882# next, handle the 'parent' part, if present 883if(defined$parentrefname) { 884# a missing pathspec defaults to the 'current' filename, allowing e.g. 885# someproject/blobdiff/oldrev..newrev:/filename 886if($parentpathname) { 887$parentpathname=~ s,^/+,,; 888$parentpathname=~ s,/$,,; 889$input_params{'file_parent'} ||=$parentpathname; 890}else{ 891$input_params{'file_parent'} ||=$input_params{'file_name'}; 892} 893# we assume that hash_parent_base is wanted if a path was specified, 894# or if the action wants hash_base instead of hash 895if(defined$input_params{'file_parent'} || 896grep{$_eq$input_params{'action'} }@wants_base) { 897$input_params{'hash_parent_base'} ||=$parentrefname; 898}else{ 899$input_params{'hash_parent'} ||=$parentrefname; 900} 901} 902 903# for the snapshot action, we allow URLs in the form 904# $project/snapshot/$hash.ext 905# where .ext determines the snapshot and gets removed from the 906# passed $refname to provide the $hash. 907# 908# To be able to tell that $refname includes the format extension, we 909# require the following two conditions to be satisfied: 910# - the hash input parameter MUST have been set from the $refname part 911# of the URL (i.e. they must be equal) 912# - the snapshot format MUST NOT have been defined already (e.g. from 913# CGI parameter sf) 914# It's also useless to try any matching unless $refname has a dot, 915# so we check for that too 916if(defined$input_params{'action'} && 917$input_params{'action'}eq'snapshot'&& 918defined$refname&&index($refname,'.') != -1&& 919$refnameeq$input_params{'hash'} && 920!defined$input_params{'snapshot_format'}) { 921# We loop over the known snapshot formats, checking for 922# extensions. Allowed extensions are both the defined suffix 923# (which includes the initial dot already) and the snapshot 924# format key itself, with a prepended dot 925while(my($fmt,$opt) =each%known_snapshot_formats) { 926my$hash=$refname; 927unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 928next; 929} 930my$sfx=$1; 931# a valid suffix was found, so set the snapshot format 932# and reset the hash parameter 933$input_params{'snapshot_format'} =$fmt; 934$input_params{'hash'} =$hash; 935# we also set the format suffix to the one requested 936# in the URL: this way a request for e.g. .tgz returns 937# a .tgz instead of a .tar.gz 938$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 939last; 940} 941} 942} 943 944our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 945$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 946$searchtext,$search_regexp); 947sub evaluate_and_validate_params { 948our$action=$input_params{'action'}; 949if(defined$action) { 950if(!validate_action($action)) { 951 die_error(400,"Invalid action parameter"); 952} 953} 954 955# parameters which are pathnames 956our$project=$input_params{'project'}; 957if(defined$project) { 958if(!validate_project($project)) { 959undef$project; 960 die_error(404,"No such project"); 961} 962} 963 964our$file_name=$input_params{'file_name'}; 965if(defined$file_name) { 966if(!validate_pathname($file_name)) { 967 die_error(400,"Invalid file parameter"); 968} 969} 970 971our$file_parent=$input_params{'file_parent'}; 972if(defined$file_parent) { 973if(!validate_pathname($file_parent)) { 974 die_error(400,"Invalid file parent parameter"); 975} 976} 977 978# parameters which are refnames 979our$hash=$input_params{'hash'}; 980if(defined$hash) { 981if(!validate_refname($hash)) { 982 die_error(400,"Invalid hash parameter"); 983} 984} 985 986our$hash_parent=$input_params{'hash_parent'}; 987if(defined$hash_parent) { 988if(!validate_refname($hash_parent)) { 989 die_error(400,"Invalid hash parent parameter"); 990} 991} 992 993our$hash_base=$input_params{'hash_base'}; 994if(defined$hash_base) { 995if(!validate_refname($hash_base)) { 996 die_error(400,"Invalid hash base parameter"); 997} 998} 9991000our@extra_options= @{$input_params{'extra_options'}};1001# @extra_options is always defined, since it can only be (currently) set from1002# CGI, and $cgi->param() returns the empty array in array context if the param1003# is not set1004foreachmy$opt(@extra_options) {1005if(not exists$allowed_options{$opt}) {1006 die_error(400,"Invalid option parameter");1007}1008if(not grep(/^$action$/, @{$allowed_options{$opt}})) {1009 die_error(400,"Invalid option parameter for this action");1010}1011}10121013our$hash_parent_base=$input_params{'hash_parent_base'};1014if(defined$hash_parent_base) {1015if(!validate_refname($hash_parent_base)) {1016 die_error(400,"Invalid hash parent base parameter");1017}1018}10191020# other parameters1021our$page=$input_params{'page'};1022if(defined$page) {1023if($page=~m/[^0-9]/) {1024 die_error(400,"Invalid page parameter");1025}1026}10271028our$searchtype=$input_params{'searchtype'};1029if(defined$searchtype) {1030if($searchtype=~m/[^a-z]/) {1031 die_error(400,"Invalid searchtype parameter");1032}1033}10341035our$search_use_regexp=$input_params{'search_use_regexp'};10361037our$searchtext=$input_params{'searchtext'};1038our$search_regexp;1039if(defined$searchtext) {1040if(length($searchtext) <2) {1041 die_error(403,"At least two characters are required for search parameter");1042}1043$search_regexp=$search_use_regexp?$searchtext:quotemeta$searchtext;1044}1045}10461047# path to the current git repository1048our$git_dir;1049sub evaluate_git_dir {1050our$git_dir="$projectroot/$project"if$project;1051}10521053our(@snapshot_fmts,$git_avatar);1054sub configure_gitweb_features {1055# list of supported snapshot formats1056our@snapshot_fmts= gitweb_get_feature('snapshot');1057@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);10581059# check that the avatar feature is set to a known provider name,1060# and for each provider check if the dependencies are satisfied.1061# if the provider name is invalid or the dependencies are not met,1062# reset $git_avatar to the empty string.1063our($git_avatar) = gitweb_get_feature('avatar');1064if($git_avatareq'gravatar') {1065$git_avatar=''unless(eval{require Digest::MD5;1; });1066}elsif($git_avatareq'picon') {1067# no dependencies1068}else{1069$git_avatar='';1070}1071}10721073# custom error handler: 'die <message>' is Internal Server Error1074sub handle_errors_html {1075my$msg=shift;# it is already HTML escaped10761077# to avoid infinite loop where error occurs in die_error,1078# change handler to default handler, disabling handle_errors_html1079 set_message("Error occured when inside die_error:\n$msg");10801081# you cannot jump out of die_error when called as error handler;1082# the subroutine set via CGI::Carp::set_message is called _after_1083# HTTP headers are already written, so it cannot write them itself1084 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1085}1086set_message(\&handle_errors_html);10871088# dispatch1089sub dispatch {1090if(!defined$action) {1091if(defined$hash) {1092$action= git_get_type($hash);1093}elsif(defined$hash_base&&defined$file_name) {1094$action= git_get_type("$hash_base:$file_name");1095}elsif(defined$project) {1096$action='summary';1097}else{1098$action='project_list';1099}1100}1101if(!defined($actions{$action})) {1102 die_error(400,"Unknown action");1103}1104if($action!~m/^(?:opml|project_list|project_index)$/&&1105!$project) {1106 die_error(400,"Project needed");1107}1108$actions{$action}->();1109}11101111sub reset_timer {1112our$t0= [ gettimeofday() ]1113ifdefined$t0;1114our$number_of_git_cmds=0;1115}11161117our$first_request=1;1118sub run_request {1119 reset_timer();11201121 evaluate_uri();1122if($first_request) {1123 evaluate_gitweb_config();1124 evaluate_git_version();1125}1126if($per_request_config) {1127if(ref($per_request_config)eq'CODE') {1128$per_request_config->();1129}elsif(!$first_request) {1130 evaluate_gitweb_config();1131}1132}1133 check_loadavg();11341135# $projectroot and $projects_list might be set in gitweb config file1136$projects_list||=$projectroot;11371138 evaluate_query_params();1139 evaluate_path_info();1140 evaluate_and_validate_params();1141 evaluate_git_dir();11421143 configure_gitweb_features();11441145 dispatch();1146}11471148our$is_last_request=sub{1};1149our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1150our$CGI='CGI';1151our$cgi;1152sub configure_as_fcgi {1153require CGI::Fast;1154our$CGI='CGI::Fast';11551156my$request_number=0;1157# let each child service 100 requests1158our$is_last_request=sub{ ++$request_number>100};1159}1160sub evaluate_argv {1161my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1162 configure_as_fcgi()1163if$script_name=~/\.fcgi$/;11641165return unless(@ARGV);11661167require Getopt::Long;1168 Getopt::Long::GetOptions(1169'fastcgi|fcgi|f'=> \&configure_as_fcgi,1170'nproc|n=i'=>sub{1171my($arg,$val) =@_;1172return unlesseval{require FCGI::ProcManager;1; };1173my$proc_manager= FCGI::ProcManager->new({1174 n_processes =>$val,1175});1176our$pre_listen_hook=sub{$proc_manager->pm_manage() };1177our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1178our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1179},1180);1181}11821183sub run {1184 evaluate_argv();11851186$first_request=1;1187$pre_listen_hook->()1188if$pre_listen_hook;11891190 REQUEST:1191while($cgi=$CGI->new()) {1192$pre_dispatch_hook->()1193if$pre_dispatch_hook;11941195 run_request();11961197$post_dispatch_hook->()1198if$post_dispatch_hook;1199$first_request=0;12001201last REQUEST if($is_last_request->());1202}12031204 DONE_GITWEB:12051;1206}12071208run();12091210if(defined caller) {1211# wrapped in a subroutine processing requests,1212# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1213return;1214}else{1215# pure CGI script, serving single request1216exit;1217}12181219## ======================================================================1220## action links12211222# possible values of extra options1223# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1224# -replay => 1 - start from a current view (replay with modifications)1225# -path_info => 0|1 - don't use/use path_info URL (if possible)1226# -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone1227sub href {1228my%params=@_;1229# default is to use -absolute url() i.e. $my_uri1230my$href=$params{-full} ?$my_url:$my_uri;12311232# implicit -replay, must be first of implicit params1233$params{-replay} =1if(keys%params==1&&$params{-anchor});12341235$params{'project'} =$projectunlessexists$params{'project'};12361237if($params{-replay}) {1238while(my($name,$symbol) =each%cgi_param_mapping) {1239if(!exists$params{$name}) {1240$params{$name} =$input_params{$name};1241}1242}1243}12441245my$use_pathinfo= gitweb_check_feature('pathinfo');1246if(defined$params{'project'} &&1247(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1248# try to put as many parameters as possible in PATH_INFO:1249# - project name1250# - action1251# - hash_parent or hash_parent_base:/file_parent1252# - hash or hash_base:/filename1253# - the snapshot_format as an appropriate suffix12541255# When the script is the root DirectoryIndex for the domain,1256# $href here would be something like http://gitweb.example.com/1257# Thus, we strip any trailing / from $href, to spare us double1258# slashes in the final URL1259$href=~ s,/$,,;12601261# Then add the project name, if present1262$href.="/".esc_path_info($params{'project'});1263delete$params{'project'};12641265# since we destructively absorb parameters, we keep this1266# boolean that remembers if we're handling a snapshot1267my$is_snapshot=$params{'action'}eq'snapshot';12681269# Summary just uses the project path URL, any other action is1270# added to the URL1271if(defined$params{'action'}) {1272$href.="/".esc_path_info($params{'action'})1273unless$params{'action'}eq'summary';1274delete$params{'action'};1275}12761277# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1278# stripping nonexistent or useless pieces1279$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1280||$params{'hash_parent'} ||$params{'hash'});1281if(defined$params{'hash_base'}) {1282if(defined$params{'hash_parent_base'}) {1283$href.= esc_path_info($params{'hash_parent_base'});1284# skip the file_parent if it's the same as the file_name1285if(defined$params{'file_parent'}) {1286if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1287delete$params{'file_parent'};1288}elsif($params{'file_parent'} !~/\.\./) {1289$href.=":/".esc_path_info($params{'file_parent'});1290delete$params{'file_parent'};1291}1292}1293$href.="..";1294delete$params{'hash_parent'};1295delete$params{'hash_parent_base'};1296}elsif(defined$params{'hash_parent'}) {1297$href.= esc_path_info($params{'hash_parent'})."..";1298delete$params{'hash_parent'};1299}13001301$href.= esc_path_info($params{'hash_base'});1302if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1303$href.=":/".esc_path_info($params{'file_name'});1304delete$params{'file_name'};1305}1306delete$params{'hash'};1307delete$params{'hash_base'};1308}elsif(defined$params{'hash'}) {1309$href.= esc_path_info($params{'hash'});1310delete$params{'hash'};1311}13121313# If the action was a snapshot, we can absorb the1314# snapshot_format parameter too1315if($is_snapshot) {1316my$fmt=$params{'snapshot_format'};1317# snapshot_format should always be defined when href()1318# is called, but just in case some code forgets, we1319# fall back to the default1320$fmt||=$snapshot_fmts[0];1321$href.=$known_snapshot_formats{$fmt}{'suffix'};1322delete$params{'snapshot_format'};1323}1324}13251326# now encode the parameters explicitly1327my@result= ();1328for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1329my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1330if(defined$params{$name}) {1331if(ref($params{$name})eq"ARRAY") {1332foreachmy$par(@{$params{$name}}) {1333push@result,$symbol."=". esc_param($par);1334}1335}else{1336push@result,$symbol."=". esc_param($params{$name});1337}1338}1339}1340$href.="?".join(';',@result)ifscalar@result;13411342# final transformation: trailing spaces must be escaped (URI-encoded)1343$href=~s/(\s+)$/CGI::escape($1)/e;13441345if($params{-anchor}) {1346$href.="#".esc_param($params{-anchor});1347}13481349return$href;1350}135113521353## ======================================================================1354## validation, quoting/unquoting and escaping13551356sub validate_action {1357my$input=shift||returnundef;1358returnundefunlessexists$actions{$input};1359return$input;1360}13611362sub validate_project {1363my$input=shift||returnundef;1364if(!validate_pathname($input) ||1365!(-d "$projectroot/$input") ||1366!check_export_ok("$projectroot/$input") ||1367($strict_export&& !project_in_list($input))) {1368returnundef;1369}else{1370return$input;1371}1372}13731374sub validate_pathname {1375my$input=shift||returnundef;13761377# no '.' or '..' as elements of path, i.e. no '.' nor '..'1378# at the beginning, at the end, and between slashes.1379# also this catches doubled slashes1380if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1381returnundef;1382}1383# no null characters1384if($input=~m!\0!) {1385returnundef;1386}1387return$input;1388}13891390sub validate_refname {1391my$input=shift||returnundef;13921393# textual hashes are O.K.1394if($input=~m/^[0-9a-fA-F]{40}$/) {1395return$input;1396}1397# it must be correct pathname1398$input= validate_pathname($input)1399orreturnundef;1400# restrictions on ref name according to git-check-ref-format1401if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1402returnundef;1403}1404return$input;1405}14061407# decode sequences of octets in utf8 into Perl's internal form,1408# which is utf-8 with utf8 flag set if needed. gitweb writes out1409# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1410sub to_utf8 {1411my$str=shift;1412returnundefunlessdefined$str;1413if(utf8::valid($str)) {1414 utf8::decode($str);1415return$str;1416}else{1417return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1418}1419}14201421# quote unsafe chars, but keep the slash, even when it's not1422# correct, but quoted slashes look too horrible in bookmarks1423sub esc_param {1424my$str=shift;1425returnundefunlessdefined$str;1426$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1427$str=~s/ /\+/g;1428return$str;1429}14301431# the quoting rules for path_info fragment are slightly different1432sub esc_path_info {1433my$str=shift;1434returnundefunlessdefined$str;14351436# path_info doesn't treat '+' as space (specially), but '?' must be escaped1437$str=~s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;14381439return$str;1440}14411442# quote unsafe chars in whole URL, so some characters cannot be quoted1443sub esc_url {1444my$str=shift;1445returnundefunlessdefined$str;1446$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1447$str=~s/ /\+/g;1448return$str;1449}14501451# quote unsafe characters in HTML attributes1452sub esc_attr {14531454# for XHTML conformance escaping '"' to '"' is not enough1455return esc_html(@_);1456}14571458# replace invalid utf8 character with SUBSTITUTION sequence1459sub esc_html {1460my$str=shift;1461my%opts=@_;14621463returnundefunlessdefined$str;14641465$str= to_utf8($str);1466$str=$cgi->escapeHTML($str);1467if($opts{'-nbsp'}) {1468$str=~s/ / /g;1469}1470$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1471return$str;1472}14731474# quote control characters and escape filename to HTML1475sub esc_path {1476my$str=shift;1477my%opts=@_;14781479returnundefunlessdefined$str;14801481$str= to_utf8($str);1482$str=$cgi->escapeHTML($str);1483if($opts{'-nbsp'}) {1484$str=~s/ / /g;1485}1486$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1487return$str;1488}14891490# Make control characters "printable", using character escape codes (CEC)1491sub quot_cec {1492my$cntrl=shift;1493my%opts=@_;1494my%es= (# character escape codes, aka escape sequences1495"\t"=>'\t',# tab (HT)1496"\n"=>'\n',# line feed (LF)1497"\r"=>'\r',# carrige return (CR)1498"\f"=>'\f',# form feed (FF)1499"\b"=>'\b',# backspace (BS)1500"\a"=>'\a',# alarm (bell) (BEL)1501"\e"=>'\e',# escape (ESC)1502"\013"=>'\v',# vertical tab (VT)1503"\000"=>'\0',# nul character (NUL)1504);1505my$chr= ( (exists$es{$cntrl})1506?$es{$cntrl}1507:sprintf('\%2x',ord($cntrl)) );1508if($opts{-nohtml}) {1509return$chr;1510}else{1511return"<span class=\"cntrl\">$chr</span>";1512}1513}15141515# Alternatively use unicode control pictures codepoints,1516# Unicode "printable representation" (PR)1517sub quot_upr {1518my$cntrl=shift;1519my%opts=@_;15201521my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1522if($opts{-nohtml}) {1523return$chr;1524}else{1525return"<span class=\"cntrl\">$chr</span>";1526}1527}15281529# git may return quoted and escaped filenames1530sub unquote {1531my$str=shift;15321533sub unq {1534my$seq=shift;1535my%es= (# character escape codes, aka escape sequences1536't'=>"\t",# tab (HT, TAB)1537'n'=>"\n",# newline (NL)1538'r'=>"\r",# return (CR)1539'f'=>"\f",# form feed (FF)1540'b'=>"\b",# backspace (BS)1541'a'=>"\a",# alarm (bell) (BEL)1542'e'=>"\e",# escape (ESC)1543'v'=>"\013",# vertical tab (VT)1544);15451546if($seq=~m/^[0-7]{1,3}$/) {1547# octal char sequence1548returnchr(oct($seq));1549}elsif(exists$es{$seq}) {1550# C escape sequence, aka character escape code1551return$es{$seq};1552}1553# quoted ordinary character1554return$seq;1555}15561557if($str=~m/^"(.*)"$/) {1558# needs unquoting1559$str=$1;1560$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1561}1562return$str;1563}15641565# escape tabs (convert tabs to spaces)1566sub untabify {1567my$line=shift;15681569while((my$pos=index($line,"\t")) != -1) {1570if(my$count= (8- ($pos%8))) {1571my$spaces=' ' x $count;1572$line=~s/\t/$spaces/;1573}1574}15751576return$line;1577}15781579sub project_in_list {1580my$project=shift;1581my@list= git_get_projects_list();1582return@list&&scalar(grep{$_->{'path'}eq$project}@list);1583}15841585## ----------------------------------------------------------------------1586## HTML aware string manipulation15871588# Try to chop given string on a word boundary between position1589# $len and $len+$add_len. If there is no word boundary there,1590# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1591# (marking chopped part) would be longer than given string.1592sub chop_str {1593my$str=shift;1594my$len=shift;1595my$add_len=shift||10;1596my$where=shift||'right';# 'left' | 'center' | 'right'15971598# Make sure perl knows it is utf8 encoded so we don't1599# cut in the middle of a utf8 multibyte char.1600$str= to_utf8($str);16011602# allow only $len chars, but don't cut a word if it would fit in $add_len1603# if it doesn't fit, cut it if it's still longer than the dots we would add1604# remove chopped character entities entirely16051606# when chopping in the middle, distribute $len into left and right part1607# return early if chopping wouldn't make string shorter1608if($whereeq'center') {1609return$strif($len+5>=length($str));# filler is length 51610$len=int($len/2);1611}else{1612return$strif($len+4>=length($str));# filler is length 41613}16141615# regexps: ending and beginning with word part up to $add_len1616my$endre=qr/.{$len}\w{0,$add_len}/;1617my$begre=qr/\w{0,$add_len}.{$len}/;16181619if($whereeq'left') {1620$str=~m/^(.*?)($begre)$/;1621my($lead,$body) = ($1,$2);1622if(length($lead) >4) {1623$lead=" ...";1624}1625return"$lead$body";16261627}elsif($whereeq'center') {1628$str=~m/^($endre)(.*)$/;1629my($left,$str) = ($1,$2);1630$str=~m/^(.*?)($begre)$/;1631my($mid,$right) = ($1,$2);1632if(length($mid) >5) {1633$mid=" ... ";1634}1635return"$left$mid$right";16361637}else{1638$str=~m/^($endre)(.*)$/;1639my$body=$1;1640my$tail=$2;1641if(length($tail) >4) {1642$tail="... ";1643}1644return"$body$tail";1645}1646}16471648# takes the same arguments as chop_str, but also wraps a <span> around the1649# result with a title attribute if it does get chopped. Additionally, the1650# string is HTML-escaped.1651sub chop_and_escape_str {1652my($str) =@_;16531654my$chopped= chop_str(@_);1655if($choppedeq$str) {1656return esc_html($chopped);1657}else{1658$str=~s/[[:cntrl:]]/?/g;1659return$cgi->span({-title=>$str}, esc_html($chopped));1660}1661}16621663## ----------------------------------------------------------------------1664## functions returning short strings16651666# CSS class for given age value (in seconds)1667sub age_class {1668my$age=shift;16691670if(!defined$age) {1671return"noage";1672}elsif($age<60*60*2) {1673return"age0";1674}elsif($age<60*60*24*2) {1675return"age1";1676}else{1677return"age2";1678}1679}16801681# convert age in seconds to "nn units ago" string1682sub age_string {1683my$age=shift;1684my$age_str;16851686if($age>60*60*24*365*2) {1687$age_str= (int$age/60/60/24/365);1688$age_str.=" years ago";1689}elsif($age>60*60*24*(365/12)*2) {1690$age_str=int$age/60/60/24/(365/12);1691$age_str.=" months ago";1692}elsif($age>60*60*24*7*2) {1693$age_str=int$age/60/60/24/7;1694$age_str.=" weeks ago";1695}elsif($age>60*60*24*2) {1696$age_str=int$age/60/60/24;1697$age_str.=" days ago";1698}elsif($age>60*60*2) {1699$age_str=int$age/60/60;1700$age_str.=" hours ago";1701}elsif($age>60*2) {1702$age_str=int$age/60;1703$age_str.=" min ago";1704}elsif($age>2) {1705$age_str=int$age;1706$age_str.=" sec ago";1707}else{1708$age_str.=" right now";1709}1710return$age_str;1711}17121713useconstant{1714 S_IFINVALID =>0030000,1715 S_IFGITLINK =>0160000,1716};17171718# submodule/subproject, a commit object reference1719sub S_ISGITLINK {1720my$mode=shift;17211722return(($mode& S_IFMT) == S_IFGITLINK)1723}17241725# convert file mode in octal to symbolic file mode string1726sub mode_str {1727my$mode=oct shift;17281729if(S_ISGITLINK($mode)) {1730return'm---------';1731}elsif(S_ISDIR($mode& S_IFMT)) {1732return'drwxr-xr-x';1733}elsif(S_ISLNK($mode)) {1734return'lrwxrwxrwx';1735}elsif(S_ISREG($mode)) {1736# git cares only about the executable bit1737if($mode& S_IXUSR) {1738return'-rwxr-xr-x';1739}else{1740return'-rw-r--r--';1741};1742}else{1743return'----------';1744}1745}17461747# convert file mode in octal to file type string1748sub file_type {1749my$mode=shift;17501751if($mode!~m/^[0-7]+$/) {1752return$mode;1753}else{1754$mode=oct$mode;1755}17561757if(S_ISGITLINK($mode)) {1758return"submodule";1759}elsif(S_ISDIR($mode& S_IFMT)) {1760return"directory";1761}elsif(S_ISLNK($mode)) {1762return"symlink";1763}elsif(S_ISREG($mode)) {1764return"file";1765}else{1766return"unknown";1767}1768}17691770# convert file mode in octal to file type description string1771sub file_type_long {1772my$mode=shift;17731774if($mode!~m/^[0-7]+$/) {1775return$mode;1776}else{1777$mode=oct$mode;1778}17791780if(S_ISGITLINK($mode)) {1781return"submodule";1782}elsif(S_ISDIR($mode& S_IFMT)) {1783return"directory";1784}elsif(S_ISLNK($mode)) {1785return"symlink";1786}elsif(S_ISREG($mode)) {1787if($mode& S_IXUSR) {1788return"executable";1789}else{1790return"file";1791};1792}else{1793return"unknown";1794}1795}179617971798## ----------------------------------------------------------------------1799## functions returning short HTML fragments, or transforming HTML fragments1800## which don't belong to other sections18011802# format line of commit message.1803sub format_log_line_html {1804my$line=shift;18051806$line= esc_html($line, -nbsp=>1);1807$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1808$cgi->a({-href => href(action=>"object", hash=>$1),1809-class=>"text"},$1);1810}eg;18111812return$line;1813}18141815# format marker of refs pointing to given object18161817# the destination action is chosen based on object type and current context:1818# - for annotated tags, we choose the tag view unless it's the current view1819# already, in which case we go to shortlog view1820# - for other refs, we keep the current view if we're in history, shortlog or1821# log view, and select shortlog otherwise1822sub format_ref_marker {1823my($refs,$id) =@_;1824my$markers='';18251826if(defined$refs->{$id}) {1827foreachmy$ref(@{$refs->{$id}}) {1828# this code exploits the fact that non-lightweight tags are the1829# only indirect objects, and that they are the only objects for which1830# we want to use tag instead of shortlog as action1831my($type,$name) =qw();1832my$indirect= ($ref=~s/\^\{\}$//);1833# e.g. tags/v2.6.11 or heads/next1834if($ref=~m!^(.*?)s?/(.*)$!) {1835$type=$1;1836$name=$2;1837}else{1838$type="ref";1839$name=$ref;1840}18411842my$class=$type;1843$class.=" indirect"if$indirect;18441845my$dest_action="shortlog";18461847if($indirect) {1848$dest_action="tag"unless$actioneq"tag";1849}elsif($action=~/^(history|(short)?log)$/) {1850$dest_action=$action;1851}18521853my$dest="";1854$dest.="refs/"unless$ref=~ m!^refs/!;1855$dest.=$ref;18561857my$link=$cgi->a({1858-href => href(1859 action=>$dest_action,1860 hash=>$dest1861)},$name);18621863$markers.=" <span class=\"".esc_attr($class)."\"title=\"".esc_attr($ref)."\">".1864$link."</span>";1865}1866}18671868if($markers) {1869return' <span class="refs">'.$markers.'</span>';1870}else{1871return"";1872}1873}18741875# format, perhaps shortened and with markers, title line1876sub format_subject_html {1877my($long,$short,$href,$extra) =@_;1878$extra=''unlessdefined($extra);18791880if(length($short) <length($long)) {1881$long=~s/[[:cntrl:]]/?/g;1882return$cgi->a({-href =>$href, -class=>"list subject",1883-title => to_utf8($long)},1884 esc_html($short)) .$extra;1885}else{1886return$cgi->a({-href =>$href, -class=>"list subject"},1887 esc_html($long)) .$extra;1888}1889}18901891# Rather than recomputing the url for an email multiple times, we cache it1892# after the first hit. This gives a visible benefit in views where the avatar1893# for the same email is used repeatedly (e.g. shortlog).1894# The cache is shared by all avatar engines (currently gravatar only), which1895# are free to use it as preferred. Since only one avatar engine is used for any1896# given page, there's no risk for cache conflicts.1897our%avatar_cache= ();18981899# Compute the picon url for a given email, by using the picon search service over at1900# http://www.cs.indiana.edu/picons/search.html1901sub picon_url {1902my$email=lc shift;1903if(!$avatar_cache{$email}) {1904my($user,$domain) =split('@',$email);1905$avatar_cache{$email} =1906"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1907"$domain/$user/".1908"users+domains+unknown/up/single";1909}1910return$avatar_cache{$email};1911}19121913# Compute the gravatar url for a given email, if it's not in the cache already.1914# Gravatar stores only the part of the URL before the size, since that's the1915# one computationally more expensive. This also allows reuse of the cache for1916# different sizes (for this particular engine).1917sub gravatar_url {1918my$email=lc shift;1919my$size=shift;1920$avatar_cache{$email} ||=1921"http://www.gravatar.com/avatar/".1922 Digest::MD5::md5_hex($email) ."?s=";1923return$avatar_cache{$email} .$size;1924}19251926# Insert an avatar for the given $email at the given $size if the feature1927# is enabled.1928sub git_get_avatar {1929my($email,%opts) =@_;1930my$pre_white= ($opts{-pad_before} ?" ":"");1931my$post_white= ($opts{-pad_after} ?" ":"");1932$opts{-size} ||='default';1933my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1934my$url="";1935if($git_avatareq'gravatar') {1936$url= gravatar_url($email,$size);1937}elsif($git_avatareq'picon') {1938$url= picon_url($email);1939}1940# Other providers can be added by extending the if chain, defining $url1941# as needed. If no variant puts something in $url, we assume avatars1942# are completely disabled/unavailable.1943if($url) {1944return$pre_white.1945"<img width=\"$size\"".1946"class=\"avatar\"".1947"src=\"".esc_url($url)."\"".1948"alt=\"\"".1949"/>".$post_white;1950}else{1951return"";1952}1953}19541955sub format_search_author {1956my($author,$searchtype,$displaytext) =@_;1957my$have_search= gitweb_check_feature('search');19581959if($have_search) {1960my$performed="";1961if($searchtypeeq'author') {1962$performed="authored";1963}elsif($searchtypeeq'committer') {1964$performed="committed";1965}19661967return$cgi->a({-href => href(action=>"search", hash=>$hash,1968 searchtext=>$author,1969 searchtype=>$searchtype),class=>"list",1970 title=>"Search for commits$performedby$author"},1971$displaytext);19721973}else{1974return$displaytext;1975}1976}19771978# format the author name of the given commit with the given tag1979# the author name is chopped and escaped according to the other1980# optional parameters (see chop_str).1981sub format_author_html {1982my$tag=shift;1983my$co=shift;1984my$author= chop_and_escape_str($co->{'author_name'},@_);1985return"<$tagclass=\"author\">".1986 format_search_author($co->{'author_name'},"author",1987 git_get_avatar($co->{'author_email'}, -pad_after =>1) .1988$author) .1989"</$tag>";1990}19911992# format git diff header line, i.e. "diff --(git|combined|cc) ..."1993sub format_git_diff_header_line {1994my$line=shift;1995my$diffinfo=shift;1996my($from,$to) =@_;19971998if($diffinfo->{'nparents'}) {1999# combined diff2000$line=~s!^(diff (.*?) )"?.*$!$1!;2001if($to->{'href'}) {2002$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2003 esc_path($to->{'file'}));2004}else{# file was deleted (no href)2005$line.= esc_path($to->{'file'});2006}2007}else{2008# "ordinary" diff2009$line=~s!^(diff (.*?) )"?a/.*$!$1!;2010if($from->{'href'}) {2011$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},2012'a/'. esc_path($from->{'file'}));2013}else{# file was added (no href)2014$line.='a/'. esc_path($from->{'file'});2015}2016$line.=' ';2017if($to->{'href'}) {2018$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2019'b/'. esc_path($to->{'file'}));2020}else{# file was deleted2021$line.='b/'. esc_path($to->{'file'});2022}2023}20242025return"<div class=\"diff header\">$line</div>\n";2026}20272028# format extended diff header line, before patch itself2029sub format_extended_diff_header_line {2030my$line=shift;2031my$diffinfo=shift;2032my($from,$to) =@_;20332034# match <path>2035if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {2036$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},2037 esc_path($from->{'file'}));2038}2039if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {2040$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},2041 esc_path($to->{'file'}));2042}2043# match single <mode>2044if($line=~m/\s(\d{6})$/) {2045$line.='<span class="info"> ('.2046 file_type_long($1) .2047')</span>';2048}2049# match <hash>2050if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {2051# can match only for combined diff2052$line='index ';2053for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2054if($from->{'href'}[$i]) {2055$line.=$cgi->a({-href=>$from->{'href'}[$i],2056-class=>"hash"},2057substr($diffinfo->{'from_id'}[$i],0,7));2058}else{2059$line.='0' x 7;2060}2061# separator2062$line.=','if($i<$diffinfo->{'nparents'} -1);2063}2064$line.='..';2065if($to->{'href'}) {2066$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2067substr($diffinfo->{'to_id'},0,7));2068}else{2069$line.='0' x 7;2070}20712072}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {2073# can match only for ordinary diff2074my($from_link,$to_link);2075if($from->{'href'}) {2076$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},2077substr($diffinfo->{'from_id'},0,7));2078}else{2079$from_link='0' x 7;2080}2081if($to->{'href'}) {2082$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2083substr($diffinfo->{'to_id'},0,7));2084}else{2085$to_link='0' x 7;2086}2087my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});2088$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;2089}20902091return$line."<br/>\n";2092}20932094# format from-file/to-file diff header2095sub format_diff_from_to_header {2096my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2097my$line;2098my$result='';20992100$line=$from_line;2101#assert($line =~ m/^---/) if DEBUG;2102# no extra formatting for "^--- /dev/null"2103if(!$diffinfo->{'nparents'}) {2104# ordinary (single parent) diff2105if($line=~m!^--- "?a/!) {2106if($from->{'href'}) {2107$line='--- a/'.2108$cgi->a({-href=>$from->{'href'}, -class=>"path"},2109 esc_path($from->{'file'}));2110}else{2111$line='--- a/'.2112 esc_path($from->{'file'});2113}2114}2115$result.= qq!<div class="diff from_file">$line</div>\n!;21162117}else{2118# combined diff (merge commit)2119for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2120if($from->{'href'}[$i]) {2121$line='--- '.2122$cgi->a({-href=>href(action=>"blobdiff",2123 hash_parent=>$diffinfo->{'from_id'}[$i],2124 hash_parent_base=>$parents[$i],2125 file_parent=>$from->{'file'}[$i],2126 hash=>$diffinfo->{'to_id'},2127 hash_base=>$hash,2128 file_name=>$to->{'file'}),2129-class=>"path",2130-title=>"diff". ($i+1)},2131$i+1) .2132'/'.2133$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2134 esc_path($from->{'file'}[$i]));2135}else{2136$line='--- /dev/null';2137}2138$result.= qq!<div class="diff from_file">$line</div>\n!;2139}2140}21412142$line=$to_line;2143#assert($line =~ m/^\+\+\+/) if DEBUG;2144# no extra formatting for "^+++ /dev/null"2145if($line=~m!^\+\+\+ "?b/!) {2146if($to->{'href'}) {2147$line='+++ b/'.2148$cgi->a({-href=>$to->{'href'}, -class=>"path"},2149 esc_path($to->{'file'}));2150}else{2151$line='+++ b/'.2152 esc_path($to->{'file'});2153}2154}2155$result.= qq!<div class="diff to_file">$line</div>\n!;21562157return$result;2158}21592160# create note for patch simplified by combined diff2161sub format_diff_cc_simplified {2162my($diffinfo,@parents) =@_;2163my$result='';21642165$result.="<div class=\"diff header\">".2166"diff --cc ";2167if(!is_deleted($diffinfo)) {2168$result.=$cgi->a({-href => href(action=>"blob",2169 hash_base=>$hash,2170 hash=>$diffinfo->{'to_id'},2171 file_name=>$diffinfo->{'to_file'}),2172-class=>"path"},2173 esc_path($diffinfo->{'to_file'}));2174}else{2175$result.= esc_path($diffinfo->{'to_file'});2176}2177$result.="</div>\n".# class="diff header"2178"<div class=\"diff nodifferences\">".2179"Simple merge".2180"</div>\n";# class="diff nodifferences"21812182return$result;2183}21842185# format patch (diff) line (not to be used for diff headers)2186sub format_diff_line {2187my$line=shift;2188my($from,$to) =@_;2189my$diff_class="";21902191chomp$line;21922193if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2194# combined diff2195my$prefix=substr($line,0,scalar@{$from->{'href'}});2196if($line=~m/^\@{3}/) {2197$diff_class=" chunk_header";2198}elsif($line=~m/^\\/) {2199$diff_class=" incomplete";2200}elsif($prefix=~tr/+/+/) {2201$diff_class=" add";2202}elsif($prefix=~tr/-/-/) {2203$diff_class=" rem";2204}2205}else{2206# assume ordinary diff2207my$char=substr($line,0,1);2208if($chareq'+') {2209$diff_class=" add";2210}elsif($chareq'-') {2211$diff_class=" rem";2212}elsif($chareq'@') {2213$diff_class=" chunk_header";2214}elsif($chareq"\\") {2215$diff_class=" incomplete";2216}2217}2218$line= untabify($line);2219if($from&&$to&&$line=~m/^\@{2} /) {2220my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2221$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;22222223$from_lines=0unlessdefined$from_lines;2224$to_lines=0unlessdefined$to_lines;22252226if($from->{'href'}) {2227$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2228-class=>"list"},$from_text);2229}2230if($to->{'href'}) {2231$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2232-class=>"list"},$to_text);2233}2234$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2235"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2236return"<div class=\"diff$diff_class\">$line</div>\n";2237}elsif($from&&$to&&$line=~m/^\@{3}/) {2238my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2239my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);22402241@from_text=split(' ',$ranges);2242for(my$i=0;$i<@from_text; ++$i) {2243($from_start[$i],$from_nlines[$i]) =2244(split(',',substr($from_text[$i],1)),0);2245}22462247$to_text=pop@from_text;2248$to_start=pop@from_start;2249$to_nlines=pop@from_nlines;22502251$line="<span class=\"chunk_info\">$prefix";2252for(my$i=0;$i<@from_text; ++$i) {2253if($from->{'href'}[$i]) {2254$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2255-class=>"list"},$from_text[$i]);2256}else{2257$line.=$from_text[$i];2258}2259$line.=" ";2260}2261if($to->{'href'}) {2262$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2263-class=>"list"},$to_text);2264}else{2265$line.=$to_text;2266}2267$line.="$prefix</span>".2268"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2269return"<div class=\"diff$diff_class\">$line</div>\n";2270}2271return"<div class=\"diff$diff_class\">". esc_html($line, -nbsp=>1) ."</div>\n";2272}22732274# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2275# linked. Pass the hash of the tree/commit to snapshot.2276sub format_snapshot_links {2277my($hash) =@_;2278my$num_fmts=@snapshot_fmts;2279if($num_fmts>1) {2280# A parenthesized list of links bearing format names.2281# e.g. "snapshot (_tar.gz_ _zip_)"2282return"snapshot (".join(' ',map2283$cgi->a({2284-href => href(2285 action=>"snapshot",2286 hash=>$hash,2287 snapshot_format=>$_2288)2289},$known_snapshot_formats{$_}{'display'})2290,@snapshot_fmts) .")";2291}elsif($num_fmts==1) {2292# A single "snapshot" link whose tooltip bears the format name.2293# i.e. "_snapshot_"2294my($fmt) =@snapshot_fmts;2295return2296$cgi->a({2297-href => href(2298 action=>"snapshot",2299 hash=>$hash,2300 snapshot_format=>$fmt2301),2302-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2303},"snapshot");2304}else{# $num_fmts == 02305returnundef;2306}2307}23082309## ......................................................................2310## functions returning values to be passed, perhaps after some2311## transformation, to other functions; e.g. returning arguments to href()23122313# returns hash to be passed to href to generate gitweb URL2314# in -title key it returns description of link2315sub get_feed_info {2316my$format=shift||'Atom';2317my%res= (action =>lc($format));23182319# feed links are possible only for project views2320return unless(defined$project);2321# some views should link to OPML, or to generic project feed,2322# or don't have specific feed yet (so they should use generic)2323return if($action=~/^(?:tags|heads|forks|tag|search)$/x);23242325my$branch;2326# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2327# from tag links; this also makes possible to detect branch links2328if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2329(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2330$branch=$1;2331}2332# find log type for feed description (title)2333my$type='log';2334if(defined$file_name) {2335$type="history of$file_name";2336$type.="/"if($actioneq'tree');2337$type.=" on '$branch'"if(defined$branch);2338}else{2339$type="log of$branch"if(defined$branch);2340}23412342$res{-title} =$type;2343$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2344$res{'file_name'} =$file_name;23452346return%res;2347}23482349## ----------------------------------------------------------------------2350## git utility subroutines, invoking git commands23512352# returns path to the core git executable and the --git-dir parameter as list2353sub git_cmd {2354$number_of_git_cmds++;2355return$GIT,'--git-dir='.$git_dir;2356}23572358# quote the given arguments for passing them to the shell2359# quote_command("command", "arg 1", "arg with ' and ! characters")2360# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2361# Try to avoid using this function wherever possible.2362sub quote_command {2363returnjoin(' ',2364map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2365}23662367# get HEAD ref of given project as hash2368sub git_get_head_hash {2369return git_get_full_hash(shift,'HEAD');2370}23712372sub git_get_full_hash {2373return git_get_hash(@_);2374}23752376sub git_get_short_hash {2377return git_get_hash(@_,'--short=7');2378}23792380sub git_get_hash {2381my($project,$hash,@options) =@_;2382my$o_git_dir=$git_dir;2383my$retval=undef;2384$git_dir="$projectroot/$project";2385if(open my$fd,'-|', git_cmd(),'rev-parse',2386'--verify','-q',@options,$hash) {2387$retval= <$fd>;2388chomp$retvalifdefined$retval;2389close$fd;2390}2391if(defined$o_git_dir) {2392$git_dir=$o_git_dir;2393}2394return$retval;2395}23962397# get type of given object2398sub git_get_type {2399my$hash=shift;24002401open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2402my$type= <$fd>;2403close$fdorreturn;2404chomp$type;2405return$type;2406}24072408# repository configuration2409our$config_file='';2410our%config;24112412# store multiple values for single key as anonymous array reference2413# single values stored directly in the hash, not as [ <value> ]2414sub hash_set_multi {2415my($hash,$key,$value) =@_;24162417if(!exists$hash->{$key}) {2418$hash->{$key} =$value;2419}elsif(!ref$hash->{$key}) {2420$hash->{$key} = [$hash->{$key},$value];2421}else{2422push@{$hash->{$key}},$value;2423}2424}24252426# return hash of git project configuration2427# optionally limited to some section, e.g. 'gitweb'2428sub git_parse_project_config {2429my$section_regexp=shift;2430my%config;24312432local$/="\0";24332434open my$fh,"-|", git_cmd(),"config",'-z','-l',2435orreturn;24362437while(my$keyval= <$fh>) {2438chomp$keyval;2439my($key,$value) =split(/\n/,$keyval,2);24402441 hash_set_multi(\%config,$key,$value)2442if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2443}2444close$fh;24452446return%config;2447}24482449# convert config value to boolean: 'true' or 'false'2450# no value, number > 0, 'true' and 'yes' values are true2451# rest of values are treated as false (never as error)2452sub config_to_bool {2453my$val=shift;24542455return1if!defined$val;# section.key24562457# strip leading and trailing whitespace2458$val=~s/^\s+//;2459$val=~s/\s+$//;24602461return(($val=~/^\d+$/&&$val) ||# section.key = 12462($val=~/^(?:true|yes)$/i));# section.key = true2463}24642465# convert config value to simple decimal number2466# an optional value suffix of 'k', 'm', or 'g' will cause the value2467# to be multiplied by 1024, 1048576, or 10737418242468sub config_to_int {2469my$val=shift;24702471# strip leading and trailing whitespace2472$val=~s/^\s+//;2473$val=~s/\s+$//;24742475if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2476$unit=lc($unit);2477# unknown unit is treated as 12478return$num* ($uniteq'g'?1073741824:2479$uniteq'm'?1048576:2480$uniteq'k'?1024:1);2481}2482return$val;2483}24842485# convert config value to array reference, if needed2486sub config_to_multi {2487my$val=shift;24882489returnref($val) ?$val: (defined($val) ? [$val] : []);2490}24912492sub git_get_project_config {2493my($key,$type) =@_;24942495return unlessdefined$git_dir;24962497# key sanity check2498return unless($key);2499$key=~s/^gitweb\.//;2500return if($key=~m/\W/);25012502# type sanity check2503if(defined$type) {2504$type=~s/^--//;2505$type=undef2506unless($typeeq'bool'||$typeeq'int');2507}25082509# get config2510if(!defined$config_file||2511$config_filene"$git_dir/config") {2512%config= git_parse_project_config('gitweb');2513$config_file="$git_dir/config";2514}25152516# check if config variable (key) exists2517return unlessexists$config{"gitweb.$key"};25182519# ensure given type2520if(!defined$type) {2521return$config{"gitweb.$key"};2522}elsif($typeeq'bool') {2523# backward compatibility: 'git config --bool' returns true/false2524return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2525}elsif($typeeq'int') {2526return config_to_int($config{"gitweb.$key"});2527}2528return$config{"gitweb.$key"};2529}25302531# get hash of given path at given ref2532sub git_get_hash_by_path {2533my$base=shift;2534my$path=shift||returnundef;2535my$type=shift;25362537$path=~ s,/+$,,;25382539open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2540or die_error(500,"Open git-ls-tree failed");2541my$line= <$fd>;2542close$fdorreturnundef;25432544if(!defined$line) {2545# there is no tree or hash given by $path at $base2546returnundef;2547}25482549#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2550$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2551if(defined$type&&$typene$2) {2552# type doesn't match2553returnundef;2554}2555return$3;2556}25572558# get path of entry with given hash at given tree-ish (ref)2559# used to get 'from' filename for combined diff (merge commit) for renames2560sub git_get_path_by_hash {2561my$base=shift||return;2562my$hash=shift||return;25632564local$/="\0";25652566open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2567orreturnundef;2568while(my$line= <$fd>) {2569chomp$line;25702571#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2572#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2573if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2574close$fd;2575return$1;2576}2577}2578close$fd;2579returnundef;2580}25812582## ......................................................................2583## git utility functions, directly accessing git repository25842585# get the value of config variable either from file named as the variable2586# itself in the repository ($GIT_DIR/$name file), or from gitweb.$name2587# configuration variable in the repository config file.2588sub git_get_file_or_project_config {2589my($path,$name) =@_;25902591$git_dir="$projectroot/$path";2592open my$fd,'<',"$git_dir/$name"2593orreturn git_get_project_config($name);2594my$conf= <$fd>;2595close$fd;2596if(defined$conf) {2597chomp$conf;2598}2599return$conf;2600}26012602sub git_get_project_description {2603my$path=shift;2604return git_get_file_or_project_config($path,'description');2605}26062607sub git_get_project_category {2608my$path=shift;2609return git_get_file_or_project_config($path,'category');2610}261126122613# supported formats:2614# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2615# - if its contents is a number, use it as tag weight,2616# - otherwise add a tag with weight 12617# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2618# the same value multiple times increases tag weight2619# * `gitweb.ctag' multi-valued repo config variable2620sub git_get_project_ctags {2621my$project=shift;2622my$ctags= {};26232624$git_dir="$projectroot/$project";2625if(opendir my$dh,"$git_dir/ctags") {2626my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2627foreachmy$tagfile(@files) {2628open my$ct,'<',$tagfile2629ornext;2630my$val= <$ct>;2631chomp$valif$val;2632close$ct;26332634(my$ctag=$tagfile) =~ s#.*/##;2635if($val=~/\d+/) {2636$ctags->{$ctag} =$val;2637}else{2638$ctags->{$ctag} =1;2639}2640}2641closedir$dh;26422643}elsif(open my$fh,'<',"$git_dir/ctags") {2644while(my$line= <$fh>) {2645chomp$line;2646$ctags->{$line}++if$line;2647}2648close$fh;26492650}else{2651my$taglist= config_to_multi(git_get_project_config('ctag'));2652foreachmy$tag(@$taglist) {2653$ctags->{$tag}++;2654}2655}26562657return$ctags;2658}26592660# return hash, where keys are content tags ('ctags'),2661# and values are sum of weights of given tag in every project2662sub git_gather_all_ctags {2663my$projects=shift;2664my$ctags= {};26652666foreachmy$p(@$projects) {2667foreachmy$ct(keys%{$p->{'ctags'}}) {2668$ctags->{$ct} +=$p->{'ctags'}->{$ct};2669}2670}26712672return$ctags;2673}26742675sub git_populate_project_tagcloud {2676my$ctags=shift;26772678# First, merge different-cased tags; tags vote on casing2679my%ctags_lc;2680foreach(keys%$ctags) {2681$ctags_lc{lc$_}->{count} +=$ctags->{$_};2682if(not$ctags_lc{lc$_}->{topcount}2683or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2684$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2685$ctags_lc{lc$_}->{topname} =$_;2686}2687}26882689my$cloud;2690my$matched=$cgi->param('by_tag');2691if(eval{require HTML::TagCloud;1; }) {2692$cloud= HTML::TagCloud->new;2693foreachmy$ctag(sort keys%ctags_lc) {2694# Pad the title with spaces so that the cloud looks2695# less crammed.2696my$title= esc_html($ctags_lc{$ctag}->{topname});2697$title=~s/ / /g;2698$title=~s/^/ /g;2699$title=~s/$/ /g;2700if(defined$matched&&$matchedeq$ctag) {2701$title=qq(<span class="match">$title</span>);2702}2703$cloud->add($title, href(project=>undef, ctag=>$ctag),2704$ctags_lc{$ctag}->{count});2705}2706}else{2707$cloud= {};2708foreachmy$ctag(keys%ctags_lc) {2709my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2710if(defined$matched&&$matchedeq$ctag) {2711$title=qq(<span class="match">$title</span>);2712}2713$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};2714$cloud->{$ctag}{ctag} =2715$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);2716}2717}2718return$cloud;2719}27202721sub git_show_project_tagcloud {2722my($cloud,$count) =@_;2723if(ref$cloudeq'HTML::TagCloud') {2724return$cloud->html_and_css($count);2725}else{2726my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;2727return2728'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.2729join(', ',map{2730$cloud->{$_}->{'ctag'}2731}splice(@tags,0,$count)) .2732'</div>';2733}2734}27352736sub git_get_project_url_list {2737my$path=shift;27382739$git_dir="$projectroot/$path";2740open my$fd,'<',"$git_dir/cloneurl"2741orreturnwantarray?2742@{ config_to_multi(git_get_project_config('url')) } :2743 config_to_multi(git_get_project_config('url'));2744my@git_project_url_list=map{chomp;$_} <$fd>;2745close$fd;27462747returnwantarray?@git_project_url_list: \@git_project_url_list;2748}27492750sub git_get_projects_list {2751my$filter=shift||'';2752my@list;27532754$filter=~s/\.git$//;27552756if(-d $projects_list) {2757# search in directory2758my$dir=$projects_list;2759# remove the trailing "/"2760$dir=~s!/+$!!;2761my$pfxlen=length("$projects_list");2762my$pfxdepth= ($projects_list=~tr!/!!);2763# when filtering, search only given subdirectory2764if($filter) {2765$dir.="/$filter";2766$dir=~s!/+$!!;2767}27682769 File::Find::find({2770 follow_fast =>1,# follow symbolic links2771 follow_skip =>2,# ignore duplicates2772 dangling_symlinks =>0,# ignore dangling symlinks, silently2773 wanted =>sub{2774# global variables2775our$project_maxdepth;2776our$projectroot;2777# skip project-list toplevel, if we get it.2778return if(m!^[/.]$!);2779# only directories can be git repositories2780return unless(-d $_);2781# don't traverse too deep (Find is super slow on os x)2782# $project_maxdepth excludes depth of $projectroot2783if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2784$File::Find::prune =1;2785return;2786}27872788my$path=substr($File::Find::name,$pfxlen+1);2789# we check related file in $projectroot2790if(check_export_ok("$projectroot/$path")) {2791push@list, { path =>$path};2792$File::Find::prune =1;2793}2794},2795},"$dir");27962797}elsif(-f $projects_list) {2798# read from file(url-encoded):2799# 'git%2Fgit.git Linus+Torvalds'2800# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2801# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2802open my$fd,'<',$projects_listorreturn;2803 PROJECT:2804while(my$line= <$fd>) {2805chomp$line;2806my($path,$owner) =split' ',$line;2807$path= unescape($path);2808$owner= unescape($owner);2809if(!defined$path) {2810next;2811}2812# if $filter is rpovided, check if $path begins with $filter2813if($filter&&$path!~m!^\Q$filter\E/!) {2814next;2815}2816if(check_export_ok("$projectroot/$path")) {2817my$pr= {2818 path =>$path,2819 owner => to_utf8($owner),2820};2821push@list,$pr;2822}2823}2824close$fd;2825}2826return@list;2827}28282829# written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)2830# as side effects it sets 'forks' field to list of forks for forked projects2831sub filter_forks_from_projects_list {2832my$projects=shift;28332834my%trie;# prefix tree of directories (path components)2835# generate trie out of those directories that might contain forks2836foreachmy$pr(@$projects) {2837my$path=$pr->{'path'};2838$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory2839next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'2840next unless($path);# skip '.git' repository: tests, git-instaweb2841next unless(-d $path);# containing directory exists2842$pr->{'forks'} = [];# there can be 0 or more forks of project28432844# add to trie2845my@dirs=split('/',$path);2846# walk the trie, until either runs out of components or out of trie2847my$ref= \%trie;2848while(scalar@dirs&&2849exists($ref->{$dirs[0]})) {2850$ref=$ref->{shift@dirs};2851}2852# create rest of trie structure from rest of components2853foreachmy$dir(@dirs) {2854$ref=$ref->{$dir} = {};2855}2856# create end marker, store $pr as a data2857$ref->{''} =$prif(!exists$ref->{''});2858}28592860# filter out forks, by finding shortest prefix match for paths2861my@filtered;2862 PROJECT:2863foreachmy$pr(@$projects) {2864# trie lookup2865my$ref= \%trie;2866 DIR:2867foreachmy$dir(split('/',$pr->{'path'})) {2868if(exists$ref->{''}) {2869# found [shortest] prefix, is a fork - skip it2870push@{$ref->{''}{'forks'}},$pr;2871next PROJECT;2872}2873if(!exists$ref->{$dir}) {2874# not in trie, cannot have prefix, not a fork2875push@filtered,$pr;2876next PROJECT;2877}2878# If the dir is there, we just walk one step down the trie.2879$ref=$ref->{$dir};2880}2881# we ran out of trie2882# (shouldn't happen: it's either no match, or end marker)2883push@filtered,$pr;2884}28852886return@filtered;2887}28882889# note: fill_project_list_info must be run first,2890# for 'descr_long' and 'ctags' to be filled2891sub search_projects_list {2892my($projlist,%opts) =@_;2893my$tagfilter=$opts{'tagfilter'};2894my$searchtext=$opts{'searchtext'};28952896return@$projlist2897unless($tagfilter||$searchtext);28982899my@projects;2900 PROJECT:2901foreachmy$pr(@$projlist) {29022903if($tagfilter) {2904next unlessref($pr->{'ctags'})eq'HASH';2905next unless2906grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};2907}29082909if($searchtext) {2910next unless2911$pr->{'path'} =~/$searchtext/||2912$pr->{'descr_long'} =~/$searchtext/;2913}29142915push@projects,$pr;2916}29172918return@projects;2919}29202921our$gitweb_project_owner=undef;2922sub git_get_project_list_from_file {29232924return if(defined$gitweb_project_owner);29252926$gitweb_project_owner= {};2927# read from file (url-encoded):2928# 'git%2Fgit.git Linus+Torvalds'2929# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2930# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2931if(-f $projects_list) {2932open(my$fd,'<',$projects_list);2933while(my$line= <$fd>) {2934chomp$line;2935my($pr,$ow) =split' ',$line;2936$pr= unescape($pr);2937$ow= unescape($ow);2938$gitweb_project_owner->{$pr} = to_utf8($ow);2939}2940close$fd;2941}2942}29432944sub git_get_project_owner {2945my$project=shift;2946my$owner;29472948returnundefunless$project;2949$git_dir="$projectroot/$project";29502951if(!defined$gitweb_project_owner) {2952 git_get_project_list_from_file();2953}29542955if(exists$gitweb_project_owner->{$project}) {2956$owner=$gitweb_project_owner->{$project};2957}2958if(!defined$owner){2959$owner= git_get_project_config('owner');2960}2961if(!defined$owner) {2962$owner= get_file_owner("$git_dir");2963}29642965return$owner;2966}29672968sub git_get_last_activity {2969my($path) =@_;2970my$fd;29712972$git_dir="$projectroot/$path";2973open($fd,"-|", git_cmd(),'for-each-ref',2974'--format=%(committer)',2975'--sort=-committerdate',2976'--count=1',2977'refs/heads')orreturn;2978my$most_recent= <$fd>;2979close$fdorreturn;2980if(defined$most_recent&&2981$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {2982my$timestamp=$1;2983my$age=time-$timestamp;2984return($age, age_string($age));2985}2986return(undef,undef);2987}29882989# Implementation note: when a single remote is wanted, we cannot use 'git2990# remote show -n' because that command always work (assuming it's a remote URL2991# if it's not defined), and we cannot use 'git remote show' because that would2992# try to make a network roundtrip. So the only way to find if that particular2993# remote is defined is to walk the list provided by 'git remote -v' and stop if2994# and when we find what we want.2995sub git_get_remotes_list {2996my$wanted=shift;2997my%remotes= ();29982999open my$fd,'-|', git_cmd(),'remote','-v';3000return unless$fd;3001while(my$remote= <$fd>) {3002chomp$remote;3003$remote=~s!\t(.*?)\s+\((\w+)\)$!!;3004next if$wantedand not$remoteeq$wanted;3005my($url,$key) = ($1,$2);30063007$remotes{$remote} ||= {'heads'=> () };3008$remotes{$remote}{$key} =$url;3009}3010close$fdorreturn;3011returnwantarray?%remotes: \%remotes;3012}30133014# Takes a hash of remotes as first parameter and fills it by adding the3015# available remote heads for each of the indicated remotes.3016sub fill_remote_heads {3017my$remotes=shift;3018my@heads=map{"remotes/$_"}keys%$remotes;3019my@remoteheads= git_get_heads_list(undef,@heads);3020foreachmy$remote(keys%$remotes) {3021$remotes->{$remote}{'heads'} = [grep{3022$_->{'name'} =~s!^$remote/!!3023}@remoteheads];3024}3025}30263027sub git_get_references {3028my$type=shift||"";3029my%refs;3030# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113031# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3032open my$fd,"-|", git_cmd(),"show-ref","--dereference",3033($type? ("--","refs/$type") : ())# use -- <pattern> if $type3034orreturn;30353036while(my$line= <$fd>) {3037chomp$line;3038if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3039if(defined$refs{$1}) {3040push@{$refs{$1}},$2;3041}else{3042$refs{$1} = [$2];3043}3044}3045}3046close$fdorreturn;3047return \%refs;3048}30493050sub git_get_rev_name_tags {3051my$hash=shift||returnundef;30523053open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3054orreturn;3055my$name_rev= <$fd>;3056close$fd;30573058if($name_rev=~ m|^$hash tags/(.*)$|) {3059return$1;3060}else{3061# catches also '$hash undefined' output3062returnundef;3063}3064}30653066## ----------------------------------------------------------------------3067## parse to hash functions30683069sub parse_date {3070my$epoch=shift;3071my$tz=shift||"-0000";30723073my%date;3074my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3075my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3076my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3077$date{'hour'} =$hour;3078$date{'minute'} =$min;3079$date{'mday'} =$mday;3080$date{'day'} =$days[$wday];3081$date{'month'} =$months[$mon];3082$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3083$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3084$date{'mday-time'} =sprintf"%d%s%02d:%02d",3085$mday,$months[$mon],$hour,$min;3086$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",30871900+$year,1+$mon,$mday,$hour,$min,$sec;30883089my($tz_sign,$tz_hour,$tz_min) =3090($tz=~m/^([-+])(\d\d)(\d\d)$/);3091$tz_sign= ($tz_signeq'-'? -1: +1);3092my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3093($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3094$date{'hour_local'} =$hour;3095$date{'minute_local'} =$min;3096$date{'tz_local'} =$tz;3097$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",30981900+$year,$mon+1,$mday,3099$hour,$min,$sec,$tz);3100return%date;3101}31023103sub parse_tag {3104my$tag_id=shift;3105my%tag;3106my@comment;31073108open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3109$tag{'id'} =$tag_id;3110while(my$line= <$fd>) {3111chomp$line;3112if($line=~m/^object ([0-9a-fA-F]{40})$/) {3113$tag{'object'} =$1;3114}elsif($line=~m/^type (.+)$/) {3115$tag{'type'} =$1;3116}elsif($line=~m/^tag (.+)$/) {3117$tag{'name'} =$1;3118}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3119$tag{'author'} =$1;3120$tag{'author_epoch'} =$2;3121$tag{'author_tz'} =$3;3122if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3123$tag{'author_name'} =$1;3124$tag{'author_email'} =$2;3125}else{3126$tag{'author_name'} =$tag{'author'};3127}3128}elsif($line=~m/--BEGIN/) {3129push@comment,$line;3130last;3131}elsif($lineeq"") {3132last;3133}3134}3135push@comment, <$fd>;3136$tag{'comment'} = \@comment;3137close$fdorreturn;3138if(!defined$tag{'name'}) {3139return3140};3141return%tag3142}31433144sub parse_commit_text {3145my($commit_text,$withparents) =@_;3146my@commit_lines=split'\n',$commit_text;3147my%co;31483149pop@commit_lines;# Remove '\0'31503151if(!@commit_lines) {3152return;3153}31543155my$header=shift@commit_lines;3156if($header!~m/^[0-9a-fA-F]{40}/) {3157return;3158}3159($co{'id'},my@parents) =split' ',$header;3160while(my$line=shift@commit_lines) {3161last if$lineeq"\n";3162if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3163$co{'tree'} =$1;3164}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3165push@parents,$1;3166}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3167$co{'author'} = to_utf8($1);3168$co{'author_epoch'} =$2;3169$co{'author_tz'} =$3;3170if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3171$co{'author_name'} =$1;3172$co{'author_email'} =$2;3173}else{3174$co{'author_name'} =$co{'author'};3175}3176}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3177$co{'committer'} = to_utf8($1);3178$co{'committer_epoch'} =$2;3179$co{'committer_tz'} =$3;3180if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3181$co{'committer_name'} =$1;3182$co{'committer_email'} =$2;3183}else{3184$co{'committer_name'} =$co{'committer'};3185}3186}3187}3188if(!defined$co{'tree'}) {3189return;3190};3191$co{'parents'} = \@parents;3192$co{'parent'} =$parents[0];31933194foreachmy$title(@commit_lines) {3195$title=~s/^ //;3196if($titlene"") {3197$co{'title'} = chop_str($title,80,5);3198# remove leading stuff of merges to make the interesting part visible3199if(length($title) >50) {3200$title=~s/^Automatic //;3201$title=~s/^merge (of|with) /Merge ... /i;3202if(length($title) >50) {3203$title=~s/(http|rsync):\/\///;3204}3205if(length($title) >50) {3206$title=~s/(master|www|rsync)\.//;3207}3208if(length($title) >50) {3209$title=~s/kernel.org:?//;3210}3211if(length($title) >50) {3212$title=~s/\/pub\/scm//;3213}3214}3215$co{'title_short'} = chop_str($title,50,5);3216last;3217}3218}3219if(!defined$co{'title'} ||$co{'title'}eq"") {3220$co{'title'} =$co{'title_short'} ='(no commit message)';3221}3222# remove added spaces3223foreachmy$line(@commit_lines) {3224$line=~s/^ //;3225}3226$co{'comment'} = \@commit_lines;32273228my$age=time-$co{'committer_epoch'};3229$co{'age'} =$age;3230$co{'age_string'} = age_string($age);3231my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3232if($age>60*60*24*7*2) {3233$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3234$co{'age_string_age'} =$co{'age_string'};3235}else{3236$co{'age_string_date'} =$co{'age_string'};3237$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3238}3239return%co;3240}32413242sub parse_commit {3243my($commit_id) =@_;3244my%co;32453246local$/="\0";32473248open my$fd,"-|", git_cmd(),"rev-list",3249"--parents",3250"--header",3251"--max-count=1",3252$commit_id,3253"--",3254or die_error(500,"Open git-rev-list failed");3255%co= parse_commit_text(<$fd>,1);3256close$fd;32573258return%co;3259}32603261sub parse_commits {3262my($commit_id,$maxcount,$skip,$filename,@args) =@_;3263my@cos;32643265$maxcount||=1;3266$skip||=0;32673268local$/="\0";32693270open my$fd,"-|", git_cmd(),"rev-list",3271"--header",3272@args,3273("--max-count=".$maxcount),3274("--skip=".$skip),3275@extra_options,3276$commit_id,3277"--",3278($filename? ($filename) : ())3279or die_error(500,"Open git-rev-list failed");3280while(my$line= <$fd>) {3281my%co= parse_commit_text($line);3282push@cos, \%co;3283}3284close$fd;32853286returnwantarray?@cos: \@cos;3287}32883289# parse line of git-diff-tree "raw" output3290sub parse_difftree_raw_line {3291my$line=shift;3292my%res;32933294# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3295# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3296if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3297$res{'from_mode'} =$1;3298$res{'to_mode'} =$2;3299$res{'from_id'} =$3;3300$res{'to_id'} =$4;3301$res{'status'} =$5;3302$res{'similarity'} =$6;3303if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3304($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3305}else{3306$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3307}3308}3309# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3310# combined diff (for merge commit)3311elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3312$res{'nparents'} =length($1);3313$res{'from_mode'} = [split(' ',$2) ];3314$res{'to_mode'} =pop@{$res{'from_mode'}};3315$res{'from_id'} = [split(' ',$3) ];3316$res{'to_id'} =pop@{$res{'from_id'}};3317$res{'status'} = [split('',$4) ];3318$res{'to_file'} = unquote($5);3319}3320# 'c512b523472485aef4fff9e57b229d9d243c967f'3321elsif($line=~m/^([0-9a-fA-F]{40})$/) {3322$res{'commit'} =$1;3323}33243325returnwantarray?%res: \%res;3326}33273328# wrapper: return parsed line of git-diff-tree "raw" output3329# (the argument might be raw line, or parsed info)3330sub parsed_difftree_line {3331my$line_or_ref=shift;33323333if(ref($line_or_ref)eq"HASH") {3334# pre-parsed (or generated by hand)3335return$line_or_ref;3336}else{3337return parse_difftree_raw_line($line_or_ref);3338}3339}33403341# parse line of git-ls-tree output3342sub parse_ls_tree_line {3343my$line=shift;3344my%opts=@_;3345my%res;33463347if($opts{'-l'}) {3348#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3349$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;33503351$res{'mode'} =$1;3352$res{'type'} =$2;3353$res{'hash'} =$3;3354$res{'size'} =$4;3355if($opts{'-z'}) {3356$res{'name'} =$5;3357}else{3358$res{'name'} = unquote($5);3359}3360}else{3361#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3362$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;33633364$res{'mode'} =$1;3365$res{'type'} =$2;3366$res{'hash'} =$3;3367if($opts{'-z'}) {3368$res{'name'} =$4;3369}else{3370$res{'name'} = unquote($4);3371}3372}33733374returnwantarray?%res: \%res;3375}33763377# generates _two_ hashes, references to which are passed as 2 and 3 argument3378sub parse_from_to_diffinfo {3379my($diffinfo,$from,$to,@parents) =@_;33803381if($diffinfo->{'nparents'}) {3382# combined diff3383$from->{'file'} = [];3384$from->{'href'} = [];3385 fill_from_file_info($diffinfo,@parents)3386unlessexists$diffinfo->{'from_file'};3387for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3388$from->{'file'}[$i] =3389defined$diffinfo->{'from_file'}[$i] ?3390$diffinfo->{'from_file'}[$i] :3391$diffinfo->{'to_file'};3392if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3393$from->{'href'}[$i] = href(action=>"blob",3394 hash_base=>$parents[$i],3395 hash=>$diffinfo->{'from_id'}[$i],3396 file_name=>$from->{'file'}[$i]);3397}else{3398$from->{'href'}[$i] =undef;3399}3400}3401}else{3402# ordinary (not combined) diff3403$from->{'file'} =$diffinfo->{'from_file'};3404if($diffinfo->{'status'}ne"A") {# not new (added) file3405$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3406 hash=>$diffinfo->{'from_id'},3407 file_name=>$from->{'file'});3408}else{3409delete$from->{'href'};3410}3411}34123413$to->{'file'} =$diffinfo->{'to_file'};3414if(!is_deleted($diffinfo)) {# file exists in result3415$to->{'href'} = href(action=>"blob", hash_base=>$hash,3416 hash=>$diffinfo->{'to_id'},3417 file_name=>$to->{'file'});3418}else{3419delete$to->{'href'};3420}3421}34223423## ......................................................................3424## parse to array of hashes functions34253426sub git_get_heads_list {3427my($limit,@classes) =@_;3428@classes= ('heads')unless@classes;3429my@patterns=map{"refs/$_"}@classes;3430my@headslist;34313432open my$fd,'-|', git_cmd(),'for-each-ref',3433($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3434'--format=%(objectname) %(refname) %(subject)%00%(committer)',3435@patterns3436orreturn;3437while(my$line= <$fd>) {3438my%ref_item;34393440chomp$line;3441my($refinfo,$committerinfo) =split(/\0/,$line);3442my($hash,$name,$title) =split(' ',$refinfo,3);3443my($committer,$epoch,$tz) =3444($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3445$ref_item{'fullname'} =$name;3446$name=~s!^refs/(?:head|remote)s/!!;34473448$ref_item{'name'} =$name;3449$ref_item{'id'} =$hash;3450$ref_item{'title'} =$title||'(no commit message)';3451$ref_item{'epoch'} =$epoch;3452if($epoch) {3453$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3454}else{3455$ref_item{'age'} ="unknown";3456}34573458push@headslist, \%ref_item;3459}3460close$fd;34613462returnwantarray?@headslist: \@headslist;3463}34643465sub git_get_tags_list {3466my$limit=shift;3467my@tagslist;34683469open my$fd,'-|', git_cmd(),'for-each-ref',3470($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3471'--format=%(objectname) %(objecttype) %(refname) '.3472'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3473'refs/tags'3474orreturn;3475while(my$line= <$fd>) {3476my%ref_item;34773478chomp$line;3479my($refinfo,$creatorinfo) =split(/\0/,$line);3480my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3481my($creator,$epoch,$tz) =3482($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3483$ref_item{'fullname'} =$name;3484$name=~s!^refs/tags/!!;34853486$ref_item{'type'} =$type;3487$ref_item{'id'} =$id;3488$ref_item{'name'} =$name;3489if($typeeq"tag") {3490$ref_item{'subject'} =$title;3491$ref_item{'reftype'} =$reftype;3492$ref_item{'refid'} =$refid;3493}else{3494$ref_item{'reftype'} =$type;3495$ref_item{'refid'} =$id;3496}34973498if($typeeq"tag"||$typeeq"commit") {3499$ref_item{'epoch'} =$epoch;3500if($epoch) {3501$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3502}else{3503$ref_item{'age'} ="unknown";3504}3505}35063507push@tagslist, \%ref_item;3508}3509close$fd;35103511returnwantarray?@tagslist: \@tagslist;3512}35133514## ----------------------------------------------------------------------3515## filesystem-related functions35163517sub get_file_owner {3518my$path=shift;35193520my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3521my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3522if(!defined$gcos) {3523returnundef;3524}3525my$owner=$gcos;3526$owner=~s/[,;].*$//;3527return to_utf8($owner);3528}35293530# assume that file exists3531sub insert_file {3532my$filename=shift;35333534open my$fd,'<',$filename;3535print map{ to_utf8($_) } <$fd>;3536close$fd;3537}35383539## ......................................................................3540## mimetype related functions35413542sub mimetype_guess_file {3543my$filename=shift;3544my$mimemap=shift;3545-r $mimemaporreturnundef;35463547my%mimemap;3548open(my$mh,'<',$mimemap)orreturnundef;3549while(<$mh>) {3550next ifm/^#/;# skip comments3551my($mimetype,$exts) =split(/\t+/);3552if(defined$exts) {3553my@exts=split(/\s+/,$exts);3554foreachmy$ext(@exts) {3555$mimemap{$ext} =$mimetype;3556}3557}3558}3559close($mh);35603561$filename=~/\.([^.]*)$/;3562return$mimemap{$1};3563}35643565sub mimetype_guess {3566my$filename=shift;3567my$mime;3568$filename=~/\./orreturnundef;35693570if($mimetypes_file) {3571my$file=$mimetypes_file;3572if($file!~m!^/!) {# if it is relative path3573# it is relative to project3574$file="$projectroot/$project/$file";3575}3576$mime= mimetype_guess_file($filename,$file);3577}3578$mime||= mimetype_guess_file($filename,'/etc/mime.types');3579return$mime;3580}35813582sub blob_mimetype {3583my$fd=shift;3584my$filename=shift;35853586if($filename) {3587my$mime= mimetype_guess($filename);3588$mimeandreturn$mime;3589}35903591# just in case3592return$default_blob_plain_mimetypeunless$fd;35933594if(-T $fd) {3595return'text/plain';3596}elsif(!$filename) {3597return'application/octet-stream';3598}elsif($filename=~m/\.png$/i) {3599return'image/png';3600}elsif($filename=~m/\.gif$/i) {3601return'image/gif';3602}elsif($filename=~m/\.jpe?g$/i) {3603return'image/jpeg';3604}else{3605return'application/octet-stream';3606}3607}36083609sub blob_contenttype {3610my($fd,$file_name,$type) =@_;36113612$type||= blob_mimetype($fd,$file_name);3613if($typeeq'text/plain'&&defined$default_text_plain_charset) {3614$type.="; charset=$default_text_plain_charset";3615}36163617return$type;3618}36193620# guess file syntax for syntax highlighting; return undef if no highlighting3621# the name of syntax can (in the future) depend on syntax highlighter used3622sub guess_file_syntax {3623my($highlight,$mimetype,$file_name) =@_;3624returnundefunless($highlight&&defined$file_name);3625my$basename= basename($file_name,'.in');3626return$highlight_basename{$basename}3627ifexists$highlight_basename{$basename};36283629$basename=~/\.([^.]*)$/;3630my$ext=$1orreturnundef;3631return$highlight_ext{$ext}3632ifexists$highlight_ext{$ext};36333634returnundef;3635}36363637# run highlighter and return FD of its output,3638# or return original FD if no highlighting3639sub run_highlighter {3640my($fd,$highlight,$syntax) =@_;3641return$fdunless($highlight&&defined$syntax);36423643close$fd;3644open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3645 quote_command($highlight_bin).3646" --replace-tabs=8 --fragment --syntax$syntax|"3647or die_error(500,"Couldn't open file or run syntax highlighter");3648return$fd;3649}36503651## ======================================================================3652## functions printing HTML: header, footer, error page36533654sub get_page_title {3655my$title= to_utf8($site_name);36563657return$titleunless(defined$project);3658$title.=" - ". to_utf8($project);36593660return$titleunless(defined$action);3661$title.="/$action";# $action is US-ASCII (7bit ASCII)36623663return$titleunless(defined$file_name);3664$title.=" - ". esc_path($file_name);3665if($actioneq"tree"&&$file_name!~ m|/$|) {3666$title.="/";3667}36683669return$title;3670}36713672sub print_feed_meta {3673if(defined$project) {3674my%href_params= get_feed_info();3675if(!exists$href_params{'-title'}) {3676$href_params{'-title'} ='log';3677}36783679foreachmy$format(qw(RSS Atom)) {3680my$type=lc($format);3681my%link_attr= (3682'-rel'=>'alternate',3683'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3684'-type'=>"application/$type+xml"3685);36863687$href_params{'action'} =$type;3688$link_attr{'-href'} = href(%href_params);3689print"<link ".3690"rel=\"$link_attr{'-rel'}\"".3691"title=\"$link_attr{'-title'}\"".3692"href=\"$link_attr{'-href'}\"".3693"type=\"$link_attr{'-type'}\"".3694"/>\n";36953696$href_params{'extra_options'} ='--no-merges';3697$link_attr{'-href'} = href(%href_params);3698$link_attr{'-title'} .=' (no merges)';3699print"<link ".3700"rel=\"$link_attr{'-rel'}\"".3701"title=\"$link_attr{'-title'}\"".3702"href=\"$link_attr{'-href'}\"".3703"type=\"$link_attr{'-type'}\"".3704"/>\n";3705}37063707}else{3708printf('<link rel="alternate" title="%sprojects list" '.3709'href="%s" type="text/plain; charset=utf-8" />'."\n",3710 esc_attr($site_name), href(project=>undef, action=>"project_index"));3711printf('<link rel="alternate" title="%sprojects feeds" '.3712'href="%s" type="text/x-opml" />'."\n",3713 esc_attr($site_name), href(project=>undef, action=>"opml"));3714}3715}37163717sub git_header_html {3718my$status=shift||"200 OK";3719my$expires=shift;3720my%opts=@_;37213722my$title= get_page_title();3723my$content_type;3724# require explicit support from the UA if we are to send the page as3725# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3726# we have to do this because MSIE sometimes globs '*/*', pretending to3727# support xhtml+xml but choking when it gets what it asked for.3728if(defined$cgi->http('HTTP_ACCEPT') &&3729$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3730$cgi->Accept('application/xhtml+xml') !=0) {3731$content_type='application/xhtml+xml';3732}else{3733$content_type='text/html';3734}3735print$cgi->header(-type=>$content_type, -charset =>'utf-8',3736-status=>$status, -expires =>$expires)3737unless($opts{'-no_http_header'});3738my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3739print<<EOF;3740<?xml version="1.0" encoding="utf-8"?>3741<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3742<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3743<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3744<!-- git core binaries version$git_version-->3745<head>3746<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3747<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3748<meta name="robots" content="index, nofollow"/>3749<title>$title</title>3750EOF3751# the stylesheet, favicon etc urls won't work correctly with path_info3752# unless we set the appropriate base URL3753if($ENV{'PATH_INFO'}) {3754print"<base href=\"".esc_url($base_url)."\"/>\n";3755}3756# print out each stylesheet that exist, providing backwards capability3757# for those people who defined $stylesheet in a config file3758if(defined$stylesheet) {3759print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3760}else{3761foreachmy$stylesheet(@stylesheets) {3762next unless$stylesheet;3763print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3764}3765}3766 print_feed_meta()3767if($statuseq'200 OK');3768if(defined$favicon) {3769printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);3770}37713772print"</head>\n".3773"<body>\n";37743775if(defined$site_header&& -f $site_header) {3776 insert_file($site_header);3777}37783779print"<div class=\"page_header\">\n";3780if(defined$logo) {3781print$cgi->a({-href => esc_url($logo_url),3782-title =>$logo_label},3783$cgi->img({-src => esc_url($logo),3784-width =>72, -height =>27,3785-alt =>"git",3786-class=>"logo"}));3787}3788print$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}3804print"</div>\n";38053806my$have_search= gitweb_check_feature('search');3807if(defined$project&&$have_search) {3808if(!defined$searchtext) {3809$searchtext="";3810}3811my$search_hash;3812if(defined$hash_base) {3813$search_hash=$hash_base;3814}elsif(defined$hash) {3815$search_hash=$hash;3816}else{3817$search_hash="HEAD";3818}3819my$action=$my_uri;3820my$use_pathinfo= gitweb_check_feature('pathinfo');3821if($use_pathinfo) {3822$action.="/".esc_url($project);3823}3824print$cgi->startform(-method=>"get", -action =>$action) .3825"<div class=\"search\">\n".3826(!$use_pathinfo&&3827$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3828$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3829$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3830$cgi->popup_menu(-name =>'st', -default=>'commit',3831-values=> ['commit','grep','author','committer','pickaxe']) .3832$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3833" search:\n",3834$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3835"<span title=\"Extended regular expression\">".3836$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3837-checked =>$search_use_regexp) .3838"</span>".3839"</div>".3840$cgi->end_form() ."\n";3841}3842}38433844sub git_footer_html {3845my$feed_class='rss_logo';38463847print"<div class=\"page_footer\">\n";3848if(defined$project) {3849my$descr= git_get_project_description($project);3850if(defined$descr) {3851print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3852}38533854my%href_params= get_feed_info();3855if(!%href_params) {3856$feed_class.=' generic';3857}3858$href_params{'-title'} ||='log';38593860foreachmy$format(qw(RSS Atom)) {3861$href_params{'action'} =lc($format);3862print$cgi->a({-href => href(%href_params),3863-title =>"$href_params{'-title'}$formatfeed",3864-class=>$feed_class},$format)."\n";3865}38663867}else{3868print$cgi->a({-href => href(project=>undef, action=>"opml"),3869-class=>$feed_class},"OPML") ." ";3870print$cgi->a({-href => href(project=>undef, action=>"project_index"),3871-class=>$feed_class},"TXT") ."\n";3872}3873print"</div>\n";# class="page_footer"38743875if(defined$t0&& gitweb_check_feature('timed')) {3876print"<div id=\"generating_info\">\n";3877print'This page took '.3878'<span id="generating_time" class="time_span">'.3879 tv_interval($t0, [ gettimeofday() ]).3880' seconds </span>'.3881' and '.3882'<span id="generating_cmd">'.3883$number_of_git_cmds.3884'</span> git commands '.3885" to generate.\n";3886print"</div>\n";# class="page_footer"3887}38883889if(defined$site_footer&& -f $site_footer) {3890 insert_file($site_footer);3891}38923893print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;3894if(defined$action&&3895$actioneq'blame_incremental') {3896print qq!<script type="text/javascript">\n!.3897 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.3898 qq!"!. href() .qq!");\n!.3899 qq!</script>\n!;3900}elsif(gitweb_check_feature('javascript-actions')) {3901print qq!<script type="text/javascript">\n!.3902 qq!window.onload = fixLinks;\n!.3903 qq!</script>\n!;3904}39053906print"</body>\n".3907"</html>";3908}39093910# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])3911# Example: die_error(404, 'Hash not found')3912# By convention, use the following status codes (as defined in RFC 2616):3913# 400: Invalid or missing CGI parameters, or3914# requested object exists but has wrong type.3915# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3916# this server or project.3917# 404: Requested object/revision/project doesn't exist.3918# 500: The server isn't configured properly, or3919# an internal error occurred (e.g. failed assertions caused by bugs), or3920# an unknown error occurred (e.g. the git binary died unexpectedly).3921# 503: The server is currently unavailable (because it is overloaded,3922# or down for maintenance). Generally, this is a temporary state.3923sub die_error {3924my$status=shift||500;3925my$error= esc_html(shift) ||"Internal Server Error";3926my$extra=shift;3927my%opts=@_;39283929my%http_responses= (3930400=>'400 Bad Request',3931403=>'403 Forbidden',3932404=>'404 Not Found',3933500=>'500 Internal Server Error',3934503=>'503 Service Unavailable',3935);3936 git_header_html($http_responses{$status},undef,%opts);3937print<<EOF;3938<div class="page_body">3939<br /><br />3940$status-$error3941<br />3942EOF3943if(defined$extra) {3944print"<hr />\n".3945"$extra\n";3946}3947print"</div>\n";39483949 git_footer_html();3950goto DONE_GITWEB3951unless($opts{'-error_handler'});3952}39533954## ----------------------------------------------------------------------3955## functions printing or outputting HTML: navigation39563957sub git_print_page_nav {3958my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;3959$extra=''if!defined$extra;# pager or formats39603961my@navs=qw(summary shortlog log commit commitdiff tree);3962if($suppress) {3963@navs=grep{$_ne$suppress}@navs;3964}39653966my%arg=map{$_=> {action=>$_} }@navs;3967if(defined$head) {3968for(qw(commit commitdiff)) {3969$arg{$_}{'hash'} =$head;3970}3971if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {3972for(qw(shortlog log)) {3973$arg{$_}{'hash'} =$head;3974}3975}3976}39773978$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;3979$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;39803981my@actions= gitweb_get_feature('actions');3982my%repl= (3983'%'=>'%',3984'n'=>$project,# project name3985'f'=>$git_dir,# project path within filesystem3986'h'=>$treehead||'',# current hash ('h' parameter)3987'b'=>$treebase||'',# hash base ('hb' parameter)3988);3989while(@actions) {3990my($label,$link,$pos) =splice(@actions,0,3);3991# insert3992@navs=map{$_eq$pos? ($_,$label) :$_}@navs;3993# munch munch3994$link=~s/%([%nfhb])/$repl{$1}/g;3995$arg{$label}{'_href'} =$link;3996}39973998print"<div class=\"page_nav\">\n".3999(join" | ",4000map{$_eq$current?4001$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4002}@navs);4003print"<br/>\n$extra<br/>\n".4004"</div>\n";4005}40064007# returns a submenu for the nagivation of the refs views (tags, heads,4008# remotes) with the current view disabled and the remotes view only4009# available if the feature is enabled4010sub format_ref_views {4011my($current) =@_;4012my@ref_views=qw{tags heads};4013push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4014returnjoin" | ",map{4015$_eq$current?$_:4016$cgi->a({-href => href(action=>$_)},$_)4017}@ref_views4018}40194020sub format_paging_nav {4021my($action,$page,$has_next_link) =@_;4022my$paging_nav;402340244025if($page>0) {4026$paging_nav.=4027$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4028" ⋅ ".4029$cgi->a({-href => href(-replay=>1, page=>$page-1),4030-accesskey =>"p", -title =>"Alt-p"},"prev");4031}else{4032$paging_nav.="first ⋅ prev";4033}40344035if($has_next_link) {4036$paging_nav.=" ⋅ ".4037$cgi->a({-href => href(-replay=>1, page=>$page+1),4038-accesskey =>"n", -title =>"Alt-n"},"next");4039}else{4040$paging_nav.=" ⋅ next";4041}40424043return$paging_nav;4044}40454046## ......................................................................4047## functions printing or outputting HTML: div40484049sub git_print_header_div {4050my($action,$title,$hash,$hash_base) =@_;4051my%args= ();40524053$args{'action'} =$action;4054$args{'hash'} =$hashif$hash;4055$args{'hash_base'} =$hash_baseif$hash_base;40564057print"<div class=\"header\">\n".4058$cgi->a({-href => href(%args), -class=>"title"},4059$title?$title:$action) .4060"\n</div>\n";4061}40624063sub format_repo_url {4064my($name,$url) =@_;4065return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4066}40674068# Group output by placing it in a DIV element and adding a header.4069# Options for start_div() can be provided by passing a hash reference as the4070# first parameter to the function.4071# Options to git_print_header_div() can be provided by passing an array4072# reference. This must follow the options to start_div if they are present.4073# The content can be a scalar, which is output as-is, a scalar reference, which4074# is output after html escaping, an IO handle passed either as *handle or4075# *handle{IO}, or a function reference. In the latter case all following4076# parameters will be taken as argument to the content function call.4077sub git_print_section {4078my($div_args,$header_args,$content);4079my$arg=shift;4080if(ref($arg)eq'HASH') {4081$div_args=$arg;4082$arg=shift;4083}4084if(ref($arg)eq'ARRAY') {4085$header_args=$arg;4086$arg=shift;4087}4088$content=$arg;40894090print$cgi->start_div($div_args);4091 git_print_header_div(@$header_args);40924093if(ref($content)eq'CODE') {4094$content->(@_);4095}elsif(ref($content)eq'SCALAR') {4096print esc_html($$content);4097}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4098print<$content>;4099}elsif(!ref($content) &&defined($content)) {4100print$content;4101}41024103print$cgi->end_div;4104}41054106sub print_local_time {4107print format_local_time(@_);4108}41094110sub format_local_time {4111my$localtime='';4112my%date=@_;4113if($date{'hour_local'} <6) {4114$localtime.=sprintf(" (<span class=\"atnight\">%02d:%02d</span>%s)",4115$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});4116}else{4117$localtime.=sprintf(" (%02d:%02d%s)",4118$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});4119}41204121return$localtime;4122}41234124# Outputs the author name and date in long form4125sub git_print_authorship {4126my$co=shift;4127my%opts=@_;4128my$tag=$opts{-tag} ||'div';4129my$author=$co->{'author_name'};41304131my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4132print"<$tagclass=\"author_date\">".4133 format_search_author($author,"author", esc_html($author)) .4134" [$ad{'rfc2822'}";4135 print_local_time(%ad)if($opts{-localtime});4136print"]". git_get_avatar($co->{'author_email'}, -pad_before =>1)4137."</$tag>\n";4138}41394140# Outputs table rows containing the full author or committer information,4141# in the format expected for 'commit' view (& similar).4142# Parameters are a commit hash reference, followed by the list of people4143# to output information for. If the list is empty it defaults to both4144# author and committer.4145sub git_print_authorship_rows {4146my$co=shift;4147# too bad we can't use @people = @_ || ('author', 'committer')4148my@people=@_;4149@people= ('author','committer')unless@people;4150foreachmy$who(@people) {4151my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4152print"<tr><td>$who</td><td>".4153 format_search_author($co->{"${who}_name"},$who,4154 esc_html($co->{"${who}_name"})) ." ".4155 format_search_author($co->{"${who}_email"},$who,4156 esc_html("<".$co->{"${who}_email"} .">")) .4157"</td><td rowspan=\"2\">".4158 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4159"</td></tr>\n".4160"<tr>".4161"<td></td><td>$wd{'rfc2822'}";4162 print_local_time(%wd);4163print"</td>".4164"</tr>\n";4165}4166}41674168sub git_print_page_path {4169my$name=shift;4170my$type=shift;4171my$hb=shift;417241734174print"<div class=\"page_path\">";4175print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4176-title =>'tree root'}, to_utf8("[$project]"));4177print" / ";4178if(defined$name) {4179my@dirname=split'/',$name;4180my$basename=pop@dirname;4181my$fullname='';41824183foreachmy$dir(@dirname) {4184$fullname.= ($fullname?'/':'') .$dir;4185print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4186 hash_base=>$hb),4187-title =>$fullname}, esc_path($dir));4188print" / ";4189}4190if(defined$type&&$typeeq'blob') {4191print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4192 hash_base=>$hb),4193-title =>$name}, esc_path($basename));4194}elsif(defined$type&&$typeeq'tree') {4195print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4196 hash_base=>$hb),4197-title =>$name}, esc_path($basename));4198print" / ";4199}else{4200print esc_path($basename);4201}4202}4203print"<br/></div>\n";4204}42054206sub git_print_log {4207my$log=shift;4208my%opts=@_;42094210if($opts{'-remove_title'}) {4211# remove title, i.e. first line of log4212shift@$log;4213}4214# remove leading empty lines4215while(defined$log->[0] &&$log->[0]eq"") {4216shift@$log;4217}42184219# print log4220my$signoff=0;4221my$empty=0;4222foreachmy$line(@$log) {4223if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {4224$signoff=1;4225$empty=0;4226if(!$opts{'-remove_signoff'}) {4227print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4228next;4229}else{4230# remove signoff lines4231next;4232}4233}else{4234$signoff=0;4235}42364237# print only one empty line4238# do not print empty line after signoff4239if($lineeq"") {4240next if($empty||$signoff);4241$empty=1;4242}else{4243$empty=0;4244}42454246print format_log_line_html($line) ."<br/>\n";4247}42484249if($opts{'-final_empty_line'}) {4250# end with single empty line4251print"<br/>\n"unless$empty;4252}4253}42544255# return link target (what link points to)4256sub git_get_link_target {4257my$hash=shift;4258my$link_target;42594260# read link4261open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4262orreturn;4263{4264local$/=undef;4265$link_target= <$fd>;4266}4267close$fd4268orreturn;42694270return$link_target;4271}42724273# given link target, and the directory (basedir) the link is in,4274# return target of link relative to top directory (top tree);4275# return undef if it is not possible (including absolute links).4276sub normalize_link_target {4277my($link_target,$basedir) =@_;42784279# absolute symlinks (beginning with '/') cannot be normalized4280return if(substr($link_target,0,1)eq'/');42814282# normalize link target to path from top (root) tree (dir)4283my$path;4284if($basedir) {4285$path=$basedir.'/'.$link_target;4286}else{4287# we are in top (root) tree (dir)4288$path=$link_target;4289}42904291# remove //, /./, and /../4292my@path_parts;4293foreachmy$part(split('/',$path)) {4294# discard '.' and ''4295next if(!$part||$parteq'.');4296# handle '..'4297if($parteq'..') {4298if(@path_parts) {4299pop@path_parts;4300}else{4301# link leads outside repository (outside top dir)4302return;4303}4304}else{4305push@path_parts,$part;4306}4307}4308$path=join('/',@path_parts);43094310return$path;4311}43124313# print tree entry (row of git_tree), but without encompassing <tr> element4314sub git_print_tree_entry {4315my($t,$basedir,$hash_base,$have_blame) =@_;43164317my%base_key= ();4318$base_key{'hash_base'} =$hash_baseifdefined$hash_base;43194320# The format of a table row is: mode list link. Where mode is4321# the mode of the entry, list is the name of the entry, an href,4322# and link is the action links of the entry.43234324print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4325if(exists$t->{'size'}) {4326print"<td class=\"size\">$t->{'size'}</td>\n";4327}4328if($t->{'type'}eq"blob") {4329print"<td class=\"list\">".4330$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4331 file_name=>"$basedir$t->{'name'}",%base_key),4332-class=>"list"}, esc_path($t->{'name'}));4333if(S_ISLNK(oct$t->{'mode'})) {4334my$link_target= git_get_link_target($t->{'hash'});4335if($link_target) {4336my$norm_target= normalize_link_target($link_target,$basedir);4337if(defined$norm_target) {4338print" -> ".4339$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4340 file_name=>$norm_target),4341-title =>$norm_target}, esc_path($link_target));4342}else{4343print" -> ". esc_path($link_target);4344}4345}4346}4347print"</td>\n";4348print"<td class=\"link\">";4349print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4350 file_name=>"$basedir$t->{'name'}",%base_key)},4351"blob");4352if($have_blame) {4353print" | ".4354$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4355 file_name=>"$basedir$t->{'name'}",%base_key)},4356"blame");4357}4358if(defined$hash_base) {4359print" | ".4360$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4361 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4362"history");4363}4364print" | ".4365$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4366 file_name=>"$basedir$t->{'name'}")},4367"raw");4368print"</td>\n";43694370}elsif($t->{'type'}eq"tree") {4371print"<td class=\"list\">";4372print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4373 file_name=>"$basedir$t->{'name'}",4374%base_key)},4375 esc_path($t->{'name'}));4376print"</td>\n";4377print"<td class=\"link\">";4378print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4379 file_name=>"$basedir$t->{'name'}",4380%base_key)},4381"tree");4382if(defined$hash_base) {4383print" | ".4384$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4385 file_name=>"$basedir$t->{'name'}")},4386"history");4387}4388print"</td>\n";4389}else{4390# unknown object: we can only present history for it4391# (this includes 'commit' object, i.e. submodule support)4392print"<td class=\"list\">".4393 esc_path($t->{'name'}) .4394"</td>\n";4395print"<td class=\"link\">";4396if(defined$hash_base) {4397print$cgi->a({-href => href(action=>"history",4398 hash_base=>$hash_base,4399 file_name=>"$basedir$t->{'name'}")},4400"history");4401}4402print"</td>\n";4403}4404}44054406## ......................................................................4407## functions printing large fragments of HTML44084409# get pre-image filenames for merge (combined) diff4410sub fill_from_file_info {4411my($diff,@parents) =@_;44124413$diff->{'from_file'} = [ ];4414$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4415for(my$i=0;$i<$diff->{'nparents'};$i++) {4416if($diff->{'status'}[$i]eq'R'||4417$diff->{'status'}[$i]eq'C') {4418$diff->{'from_file'}[$i] =4419 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4420}4421}44224423return$diff;4424}44254426# is current raw difftree line of file deletion4427sub is_deleted {4428my$diffinfo=shift;44294430return$diffinfo->{'to_id'}eq('0' x 40);4431}44324433# does patch correspond to [previous] difftree raw line4434# $diffinfo - hashref of parsed raw diff format4435# $patchinfo - hashref of parsed patch diff format4436# (the same keys as in $diffinfo)4437sub is_patch_split {4438my($diffinfo,$patchinfo) =@_;44394440returndefined$diffinfo&&defined$patchinfo4441&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4442}444344444445sub git_difftree_body {4446my($difftree,$hash,@parents) =@_;4447my($parent) =$parents[0];4448my$have_blame= gitweb_check_feature('blame');4449print"<div class=\"list_head\">\n";4450if($#{$difftree} >10) {4451print(($#{$difftree} +1) ." files changed:\n");4452}4453print"</div>\n";44544455print"<table class=\"".4456(@parents>1?"combined ":"") .4457"diff_tree\">\n";44584459# header only for combined diff in 'commitdiff' view4460my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4461if($has_header) {4462# table header4463print"<thead><tr>\n".4464"<th></th><th></th>\n";# filename, patchN link4465for(my$i=0;$i<@parents;$i++) {4466my$par=$parents[$i];4467print"<th>".4468$cgi->a({-href => href(action=>"commitdiff",4469 hash=>$hash, hash_parent=>$par),4470-title =>'commitdiff to parent number '.4471($i+1) .': '.substr($par,0,7)},4472$i+1) .4473" </th>\n";4474}4475print"</tr></thead>\n<tbody>\n";4476}44774478my$alternate=1;4479my$patchno=0;4480foreachmy$line(@{$difftree}) {4481my$diff= parsed_difftree_line($line);44824483if($alternate) {4484print"<tr class=\"dark\">\n";4485}else{4486print"<tr class=\"light\">\n";4487}4488$alternate^=1;44894490if(exists$diff->{'nparents'}) {# combined diff44914492 fill_from_file_info($diff,@parents)4493unlessexists$diff->{'from_file'};44944495if(!is_deleted($diff)) {4496# file exists in the result (child) commit4497print"<td>".4498$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4499 file_name=>$diff->{'to_file'},4500 hash_base=>$hash),4501-class=>"list"}, esc_path($diff->{'to_file'})) .4502"</td>\n";4503}else{4504print"<td>".4505 esc_path($diff->{'to_file'}) .4506"</td>\n";4507}45084509if($actioneq'commitdiff') {4510# link to patch4511$patchno++;4512print"<td class=\"link\">".4513$cgi->a({-href => href(-anchor=>"patch$patchno")},4514"patch") .4515" | ".4516"</td>\n";4517}45184519my$has_history=0;4520my$not_deleted=0;4521for(my$i=0;$i<$diff->{'nparents'};$i++) {4522my$hash_parent=$parents[$i];4523my$from_hash=$diff->{'from_id'}[$i];4524my$from_path=$diff->{'from_file'}[$i];4525my$status=$diff->{'status'}[$i];45264527$has_history||= ($statusne'A');4528$not_deleted||= ($statusne'D');45294530if($statuseq'A') {4531print"<td class=\"link\"align=\"right\"> | </td>\n";4532}elsif($statuseq'D') {4533print"<td class=\"link\">".4534$cgi->a({-href => href(action=>"blob",4535 hash_base=>$hash,4536 hash=>$from_hash,4537 file_name=>$from_path)},4538"blob". ($i+1)) .4539" | </td>\n";4540}else{4541if($diff->{'to_id'}eq$from_hash) {4542print"<td class=\"link nochange\">";4543}else{4544print"<td class=\"link\">";4545}4546print$cgi->a({-href => href(action=>"blobdiff",4547 hash=>$diff->{'to_id'},4548 hash_parent=>$from_hash,4549 hash_base=>$hash,4550 hash_parent_base=>$hash_parent,4551 file_name=>$diff->{'to_file'},4552 file_parent=>$from_path)},4553"diff". ($i+1)) .4554" | </td>\n";4555}4556}45574558print"<td class=\"link\">";4559if($not_deleted) {4560print$cgi->a({-href => href(action=>"blob",4561 hash=>$diff->{'to_id'},4562 file_name=>$diff->{'to_file'},4563 hash_base=>$hash)},4564"blob");4565print" | "if($has_history);4566}4567if($has_history) {4568print$cgi->a({-href => href(action=>"history",4569 file_name=>$diff->{'to_file'},4570 hash_base=>$hash)},4571"history");4572}4573print"</td>\n";45744575print"</tr>\n";4576next;# instead of 'else' clause, to avoid extra indent4577}4578# else ordinary diff45794580my($to_mode_oct,$to_mode_str,$to_file_type);4581my($from_mode_oct,$from_mode_str,$from_file_type);4582if($diff->{'to_mode'}ne('0' x 6)) {4583$to_mode_oct=oct$diff->{'to_mode'};4584if(S_ISREG($to_mode_oct)) {# only for regular file4585$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4586}4587$to_file_type= file_type($diff->{'to_mode'});4588}4589if($diff->{'from_mode'}ne('0' x 6)) {4590$from_mode_oct=oct$diff->{'from_mode'};4591if(S_ISREG($from_mode_oct)) {# only for regular file4592$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4593}4594$from_file_type= file_type($diff->{'from_mode'});4595}45964597if($diff->{'status'}eq"A") {# created4598my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4599$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4600$mode_chng.="]</span>";4601print"<td>";4602print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4603 hash_base=>$hash, file_name=>$diff->{'file'}),4604-class=>"list"}, esc_path($diff->{'file'}));4605print"</td>\n";4606print"<td>$mode_chng</td>\n";4607print"<td class=\"link\">";4608if($actioneq'commitdiff') {4609# link to patch4610$patchno++;4611print$cgi->a({-href => href(-anchor=>"patch$patchno")},4612"patch") .4613" | ";4614}4615print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4616 hash_base=>$hash, file_name=>$diff->{'file'})},4617"blob");4618print"</td>\n";46194620}elsif($diff->{'status'}eq"D") {# deleted4621my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4622print"<td>";4623print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4624 hash_base=>$parent, file_name=>$diff->{'file'}),4625-class=>"list"}, esc_path($diff->{'file'}));4626print"</td>\n";4627print"<td>$mode_chng</td>\n";4628print"<td class=\"link\">";4629if($actioneq'commitdiff') {4630# link to patch4631$patchno++;4632print$cgi->a({-href => href(-anchor=>"patch$patchno")},4633"patch") .4634" | ";4635}4636print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4637 hash_base=>$parent, file_name=>$diff->{'file'})},4638"blob") ." | ";4639if($have_blame) {4640print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4641 file_name=>$diff->{'file'})},4642"blame") ." | ";4643}4644print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4645 file_name=>$diff->{'file'})},4646"history");4647print"</td>\n";46484649}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4650my$mode_chnge="";4651if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4652$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4653if($from_file_typene$to_file_type) {4654$mode_chnge.=" from$from_file_typeto$to_file_type";4655}4656if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4657if($from_mode_str&&$to_mode_str) {4658$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4659}elsif($to_mode_str) {4660$mode_chnge.=" mode:$to_mode_str";4661}4662}4663$mode_chnge.="]</span>\n";4664}4665print"<td>";4666print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4667 hash_base=>$hash, file_name=>$diff->{'file'}),4668-class=>"list"}, esc_path($diff->{'file'}));4669print"</td>\n";4670print"<td>$mode_chnge</td>\n";4671print"<td class=\"link\">";4672if($actioneq'commitdiff') {4673# link to patch4674$patchno++;4675print$cgi->a({-href => href(-anchor=>"patch$patchno")},4676"patch") .4677" | ";4678}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4679# "commit" view and modified file (not onlu mode changed)4680print$cgi->a({-href => href(action=>"blobdiff",4681 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4682 hash_base=>$hash, hash_parent_base=>$parent,4683 file_name=>$diff->{'file'})},4684"diff") .4685" | ";4686}4687print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4688 hash_base=>$hash, file_name=>$diff->{'file'})},4689"blob") ." | ";4690if($have_blame) {4691print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4692 file_name=>$diff->{'file'})},4693"blame") ." | ";4694}4695print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4696 file_name=>$diff->{'file'})},4697"history");4698print"</td>\n";46994700}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4701my%status_name= ('R'=>'moved','C'=>'copied');4702my$nstatus=$status_name{$diff->{'status'}};4703my$mode_chng="";4704if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4705# mode also for directories, so we cannot use $to_mode_str4706$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4707}4708print"<td>".4709$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4710 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4711-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4712"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4713$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4714 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4715-class=>"list"}, esc_path($diff->{'from_file'})) .4716" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4717"<td class=\"link\">";4718if($actioneq'commitdiff') {4719# link to patch4720$patchno++;4721print$cgi->a({-href => href(-anchor=>"patch$patchno")},4722"patch") .4723" | ";4724}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4725# "commit" view and modified file (not only pure rename or copy)4726print$cgi->a({-href => href(action=>"blobdiff",4727 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4728 hash_base=>$hash, hash_parent_base=>$parent,4729 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4730"diff") .4731" | ";4732}4733print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4734 hash_base=>$parent, file_name=>$diff->{'to_file'})},4735"blob") ." | ";4736if($have_blame) {4737print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4738 file_name=>$diff->{'to_file'})},4739"blame") ." | ";4740}4741print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4742 file_name=>$diff->{'to_file'})},4743"history");4744print"</td>\n";47454746}# we should not encounter Unmerged (U) or Unknown (X) status4747print"</tr>\n";4748}4749print"</tbody>"if$has_header;4750print"</table>\n";4751}47524753sub git_patchset_body {4754my($fd,$difftree,$hash,@hash_parents) =@_;4755my($hash_parent) =$hash_parents[0];47564757my$is_combined= (@hash_parents>1);4758my$patch_idx=0;4759my$patch_number=0;4760my$patch_line;4761my$diffinfo;4762my$to_name;4763my(%from,%to);47644765print"<div class=\"patchset\">\n";47664767# skip to first patch4768while($patch_line= <$fd>) {4769chomp$patch_line;47704771last if($patch_line=~m/^diff /);4772}47734774 PATCH:4775while($patch_line) {47764777# parse "git diff" header line4778if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4779# $1 is from_name, which we do not use4780$to_name= unquote($2);4781$to_name=~s!^b/!!;4782}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4783# $1 is 'cc' or 'combined', which we do not use4784$to_name= unquote($2);4785}else{4786$to_name=undef;4787}47884789# check if current patch belong to current raw line4790# and parse raw git-diff line if needed4791if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4792# this is continuation of a split patch4793print"<div class=\"patch cont\">\n";4794}else{4795# advance raw git-diff output if needed4796$patch_idx++ifdefined$diffinfo;47974798# read and prepare patch information4799$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);48004801# compact combined diff output can have some patches skipped4802# find which patch (using pathname of result) we are at now;4803if($is_combined) {4804while($to_namene$diffinfo->{'to_file'}) {4805print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4806 format_diff_cc_simplified($diffinfo,@hash_parents) .4807"</div>\n";# class="patch"48084809$patch_idx++;4810$patch_number++;48114812last if$patch_idx>$#$difftree;4813$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4814}4815}48164817# modifies %from, %to hashes4818 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);48194820# this is first patch for raw difftree line with $patch_idx index4821# we index @$difftree array from 0, but number patches from 14822print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4823}48244825# git diff header4826#assert($patch_line =~ m/^diff /) if DEBUG;4827#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4828$patch_number++;4829# print "git diff" header4830print format_git_diff_header_line($patch_line,$diffinfo,4831 \%from, \%to);48324833# print extended diff header4834print"<div class=\"diff extended_header\">\n";4835 EXTENDED_HEADER:4836while($patch_line= <$fd>) {4837chomp$patch_line;48384839last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);48404841print format_extended_diff_header_line($patch_line,$diffinfo,4842 \%from, \%to);4843}4844print"</div>\n";# class="diff extended_header"48454846# from-file/to-file diff header4847if(!$patch_line) {4848print"</div>\n";# class="patch"4849last PATCH;4850}4851next PATCH if($patch_line=~m/^diff /);4852#assert($patch_line =~ m/^---/) if DEBUG;48534854my$last_patch_line=$patch_line;4855$patch_line= <$fd>;4856chomp$patch_line;4857#assert($patch_line =~ m/^\+\+\+/) if DEBUG;48584859print format_diff_from_to_header($last_patch_line,$patch_line,4860$diffinfo, \%from, \%to,4861@hash_parents);48624863# the patch itself4864 LINE:4865while($patch_line= <$fd>) {4866chomp$patch_line;48674868next PATCH if($patch_line=~m/^diff /);48694870print format_diff_line($patch_line, \%from, \%to);4871}48724873}continue{4874print"</div>\n";# class="patch"4875}48764877# for compact combined (--cc) format, with chunk and patch simplification4878# the patchset might be empty, but there might be unprocessed raw lines4879for(++$patch_idxif$patch_number>0;4880$patch_idx<@$difftree;4881++$patch_idx) {4882# read and prepare patch information4883$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);48844885# generate anchor for "patch" links in difftree / whatchanged part4886print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4887 format_diff_cc_simplified($diffinfo,@hash_parents) .4888"</div>\n";# class="patch"48894890$patch_number++;4891}48924893if($patch_number==0) {4894if(@hash_parents>1) {4895print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4896}else{4897print"<div class=\"diff nodifferences\">No differences found</div>\n";4898}4899}49004901print"</div>\n";# class="patchset"4902}49034904# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49054906# fills project list info (age, description, owner, category, forks)4907# for each project in the list, removing invalid projects from4908# returned list4909# NOTE: modifies $projlist, but does not remove entries from it4910sub fill_project_list_info {4911my$projlist=shift;4912my@projects;49134914my$show_ctags= gitweb_check_feature('ctags');4915 PROJECT:4916foreachmy$pr(@$projlist) {4917my(@activity) = git_get_last_activity($pr->{'path'});4918unless(@activity) {4919next PROJECT;4920}4921($pr->{'age'},$pr->{'age_string'}) =@activity;4922if(!defined$pr->{'descr'}) {4923my$descr= git_get_project_description($pr->{'path'}) ||"";4924$descr= to_utf8($descr);4925$pr->{'descr_long'} =$descr;4926$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);4927}4928if(!defined$pr->{'owner'}) {4929$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";4930}4931if($show_ctags) {4932$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});4933}4934if($projects_list_group_categories&& !defined$pr->{'category'}) {4935my$cat= git_get_project_category($pr->{'path'}) ||4936$project_list_default_category;4937$pr->{'category'} = to_utf8($cat);4938}49394940push@projects,$pr;4941}49424943return@projects;4944}49454946sub sort_projects_list {4947my($projlist,$order) =@_;4948my@projects;49494950my%order_info= (4951 project => { key =>'path', type =>'str'},4952 descr => { key =>'descr_long', type =>'str'},4953 owner => { key =>'owner', type =>'str'},4954 age => { key =>'age', type =>'num'}4955);4956my$oi=$order_info{$order};4957return@$projlistunlessdefined$oi;4958if($oi->{'type'}eq'str') {4959@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@$projlist;4960}else{4961@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@$projlist;4962}49634964return@projects;4965}49664967# returns a hash of categories, containing the list of project4968# belonging to each category4969sub build_projlist_by_category {4970my($projlist,$from,$to) =@_;4971my%categories;49724973$from=0unlessdefined$from;4974$to=$#$projlistif(!defined$to||$#$projlist<$to);49754976for(my$i=$from;$i<=$to;$i++) {4977my$pr=$projlist->[$i];4978push@{$categories{$pr->{'category'} }},$pr;4979}49804981returnwantarray?%categories: \%categories;4982}49834984# print 'sort by' <th> element, generating 'sort by $name' replay link4985# if that order is not selected4986sub print_sort_th {4987print format_sort_th(@_);4988}49894990sub format_sort_th {4991my($name,$order,$header) =@_;4992my$sort_th="";4993$header||=ucfirst($name);49944995if($ordereq$name) {4996$sort_th.="<th>$header</th>\n";4997}else{4998$sort_th.="<th>".4999$cgi->a({-href => href(-replay=>1, order=>$name),5000-class=>"header"},$header) .5001"</th>\n";5002}50035004return$sort_th;5005}50065007sub git_project_list_rows {5008my($projlist,$from,$to,$check_forks) =@_;50095010$from=0unlessdefined$from;5011$to=$#$projlistif(!defined$to||$#$projlist<$to);50125013my$alternate=1;5014for(my$i=$from;$i<=$to;$i++) {5015my$pr=$projlist->[$i];50165017if($alternate) {5018print"<tr class=\"dark\">\n";5019}else{5020print"<tr class=\"light\">\n";5021}5022$alternate^=1;50235024if($check_forks) {5025print"<td>";5026if($pr->{'forks'}) {5027my$nforks=scalar@{$pr->{'forks'}};5028if($nforks>0) {5029print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5030-title =>"$nforksforks"},"+");5031}else{5032print$cgi->span({-title =>"$nforksforks"},"+");5033}5034}5035print"</td>\n";5036}5037print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5038-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".5039"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5040-class=>"list", -title =>$pr->{'descr_long'}},5041 esc_html($pr->{'descr'})) ."</td>\n".5042"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5043print"<td class=\"". age_class($pr->{'age'}) ."\">".5044(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".5045"<td class=\"link\">".5046$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5047$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5048$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5049$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5050($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5051"</td>\n".5052"</tr>\n";5053}5054}50555056sub git_project_list_body {5057# actually uses global variable $project5058my($projlist,$order,$from,$to,$extra,$no_header) =@_;5059my@projects=@$projlist;50605061my$check_forks= gitweb_check_feature('forks');5062my$show_ctags= gitweb_check_feature('ctags');5063my$tagfilter=$show_ctags?$cgi->param('by_tag') :undef;5064$check_forks=undef5065if($tagfilter||$searchtext);50665067# filtering out forks before filling info allows to do less work5068@projects= filter_forks_from_projects_list(\@projects)5069if($check_forks);5070@projects= fill_project_list_info(\@projects);5071# searching projects require filling to be run before it5072@projects= search_projects_list(\@projects,5073'searchtext'=>$searchtext,5074'tagfilter'=>$tagfilter)5075if($tagfilter||$searchtext);50765077$order||=$default_projects_order;5078$from=0unlessdefined$from;5079$to=$#projectsif(!defined$to||$#projects<$to);50805081# short circuit5082if($from>$to) {5083print"<center>\n".5084"<b>No such projects found</b><br />\n".5085"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5086"</center>\n<br />\n";5087return;5088}50895090@projects= sort_projects_list(\@projects,$order);50915092if($show_ctags) {5093my$ctags= git_gather_all_ctags(\@projects);5094my$cloud= git_populate_project_tagcloud($ctags);5095print git_show_project_tagcloud($cloud,64);5096}50975098print"<table class=\"project_list\">\n";5099unless($no_header) {5100print"<tr>\n";5101if($check_forks) {5102print"<th></th>\n";5103}5104 print_sort_th('project',$order,'Project');5105 print_sort_th('descr',$order,'Description');5106 print_sort_th('owner',$order,'Owner');5107 print_sort_th('age',$order,'Last Change');5108print"<th></th>\n".# for links5109"</tr>\n";5110}51115112if($projects_list_group_categories) {5113# only display categories with projects in the $from-$to window5114@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5115my%categories= build_projlist_by_category(\@projects,$from,$to);5116foreachmy$cat(sort keys%categories) {5117unless($cateq"") {5118print"<tr>\n";5119if($check_forks) {5120print"<td></td>\n";5121}5122print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5123print"</tr>\n";5124}51255126 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5127}5128}else{5129 git_project_list_rows(\@projects,$from,$to,$check_forks);5130}51315132if(defined$extra) {5133print"<tr>\n";5134if($check_forks) {5135print"<td></td>\n";5136}5137print"<td colspan=\"5\">$extra</td>\n".5138"</tr>\n";5139}5140print"</table>\n";5141}51425143sub git_log_body {5144# uses global variable $project5145my($commitlist,$from,$to,$refs,$extra) =@_;51465147$from=0unlessdefined$from;5148$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);51495150for(my$i=0;$i<=$to;$i++) {5151my%co= %{$commitlist->[$i]};5152next if!%co;5153my$commit=$co{'id'};5154my$ref= format_ref_marker($refs,$commit);5155 git_print_header_div('commit',5156"<span class=\"age\">$co{'age_string'}</span>".5157 esc_html($co{'title'}) .$ref,5158$commit);5159print"<div class=\"title_text\">\n".5160"<div class=\"log_link\">\n".5161$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5162" | ".5163$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5164" | ".5165$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5166"<br/>\n".5167"</div>\n";5168 git_print_authorship(\%co, -tag =>'span');5169print"<br/>\n</div>\n";51705171print"<div class=\"log_body\">\n";5172 git_print_log($co{'comment'}, -final_empty_line=>1);5173print"</div>\n";5174}5175if($extra) {5176print"<div class=\"page_nav\">\n";5177print"$extra\n";5178print"</div>\n";5179}5180}51815182sub git_shortlog_body {5183# uses global variable $project5184my($commitlist,$from,$to,$refs,$extra) =@_;51855186$from=0unlessdefined$from;5187$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);51885189print"<table class=\"shortlog\">\n";5190my$alternate=1;5191for(my$i=$from;$i<=$to;$i++) {5192my%co= %{$commitlist->[$i]};5193my$commit=$co{'id'};5194my$ref= format_ref_marker($refs,$commit);5195if($alternate) {5196print"<tr class=\"dark\">\n";5197}else{5198print"<tr class=\"light\">\n";5199}5200$alternate^=1;5201# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5202print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5203 format_author_html('td', \%co,10) ."<td>";5204print format_subject_html($co{'title'},$co{'title_short'},5205 href(action=>"commit", hash=>$commit),$ref);5206print"</td>\n".5207"<td class=\"link\">".5208$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5209$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5210$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5211my$snapshot_links= format_snapshot_links($commit);5212if(defined$snapshot_links) {5213print" | ".$snapshot_links;5214}5215print"</td>\n".5216"</tr>\n";5217}5218if(defined$extra) {5219print"<tr>\n".5220"<td colspan=\"4\">$extra</td>\n".5221"</tr>\n";5222}5223print"</table>\n";5224}52255226sub git_history_body {5227# Warning: assumes constant type (blob or tree) during history5228my($commitlist,$from,$to,$refs,$extra,5229$file_name,$file_hash,$ftype) =@_;52305231$from=0unlessdefined$from;5232$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});52335234print"<table class=\"history\">\n";5235my$alternate=1;5236for(my$i=$from;$i<=$to;$i++) {5237my%co= %{$commitlist->[$i]};5238if(!%co) {5239next;5240}5241my$commit=$co{'id'};52425243my$ref= format_ref_marker($refs,$commit);52445245if($alternate) {5246print"<tr class=\"dark\">\n";5247}else{5248print"<tr class=\"light\">\n";5249}5250$alternate^=1;5251print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5252# shortlog: format_author_html('td', \%co, 10)5253 format_author_html('td', \%co,15,3) ."<td>";5254# originally git_history used chop_str($co{'title'}, 50)5255print format_subject_html($co{'title'},$co{'title_short'},5256 href(action=>"commit", hash=>$commit),$ref);5257print"</td>\n".5258"<td class=\"link\">".5259$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5260$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");52615262if($ftypeeq'blob') {5263my$blob_current=$file_hash;5264my$blob_parent= git_get_hash_by_path($commit,$file_name);5265if(defined$blob_current&&defined$blob_parent&&5266$blob_currentne$blob_parent) {5267print" | ".5268$cgi->a({-href => href(action=>"blobdiff",5269 hash=>$blob_current, hash_parent=>$blob_parent,5270 hash_base=>$hash_base, hash_parent_base=>$commit,5271 file_name=>$file_name)},5272"diff to current");5273}5274}5275print"</td>\n".5276"</tr>\n";5277}5278if(defined$extra) {5279print"<tr>\n".5280"<td colspan=\"4\">$extra</td>\n".5281"</tr>\n";5282}5283print"</table>\n";5284}52855286sub git_tags_body {5287# uses global variable $project5288my($taglist,$from,$to,$extra) =@_;5289$from=0unlessdefined$from;5290$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);52915292print"<table class=\"tags\">\n";5293my$alternate=1;5294for(my$i=$from;$i<=$to;$i++) {5295my$entry=$taglist->[$i];5296my%tag=%$entry;5297my$comment=$tag{'subject'};5298my$comment_short;5299if(defined$comment) {5300$comment_short= chop_str($comment,30,5);5301}5302if($alternate) {5303print"<tr class=\"dark\">\n";5304}else{5305print"<tr class=\"light\">\n";5306}5307$alternate^=1;5308if(defined$tag{'age'}) {5309print"<td><i>$tag{'age'}</i></td>\n";5310}else{5311print"<td></td>\n";5312}5313print"<td>".5314$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5315-class=>"list name"}, esc_html($tag{'name'})) .5316"</td>\n".5317"<td>";5318if(defined$comment) {5319print format_subject_html($comment,$comment_short,5320 href(action=>"tag", hash=>$tag{'id'}));5321}5322print"</td>\n".5323"<td class=\"selflink\">";5324if($tag{'type'}eq"tag") {5325print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");5326}else{5327print" ";5328}5329print"</td>\n".5330"<td class=\"link\">"." | ".5331$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});5332if($tag{'reftype'}eq"commit") {5333print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .5334" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");5335}elsif($tag{'reftype'}eq"blob") {5336print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");5337}5338print"</td>\n".5339"</tr>";5340}5341if(defined$extra) {5342print"<tr>\n".5343"<td colspan=\"5\">$extra</td>\n".5344"</tr>\n";5345}5346print"</table>\n";5347}53485349sub git_heads_body {5350# uses global variable $project5351my($headlist,$head,$from,$to,$extra) =@_;5352$from=0unlessdefined$from;5353$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);53545355print"<table class=\"heads\">\n";5356my$alternate=1;5357for(my$i=$from;$i<=$to;$i++) {5358my$entry=$headlist->[$i];5359my%ref=%$entry;5360my$curr=$ref{'id'}eq$head;5361if($alternate) {5362print"<tr class=\"dark\">\n";5363}else{5364print"<tr class=\"light\">\n";5365}5366$alternate^=1;5367print"<td><i>$ref{'age'}</i></td>\n".5368($curr?"<td class=\"current_head\">":"<td>") .5369$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),5370-class=>"list name"},esc_html($ref{'name'})) .5371"</td>\n".5372"<td class=\"link\">".5373$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".5374$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".5375$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .5376"</td>\n".5377"</tr>";5378}5379if(defined$extra) {5380print"<tr>\n".5381"<td colspan=\"3\">$extra</td>\n".5382"</tr>\n";5383}5384print"</table>\n";5385}53865387# Display a single remote block5388sub git_remote_block {5389my($remote,$rdata,$limit,$head) =@_;53905391my$heads=$rdata->{'heads'};5392my$fetch=$rdata->{'fetch'};5393my$push=$rdata->{'push'};53945395my$urls_table="<table class=\"projects_list\">\n";53965397if(defined$fetch) {5398if($fetcheq$push) {5399$urls_table.= format_repo_url("URL",$fetch);5400}else{5401$urls_table.= format_repo_url("Fetch URL",$fetch);5402$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;5403}5404}elsif(defined$push) {5405$urls_table.= format_repo_url("Push URL",$push);5406}else{5407$urls_table.= format_repo_url("","No remote URL");5408}54095410$urls_table.="</table>\n";54115412my$dots;5413if(defined$limit&&$limit<@$heads) {5414$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");5415}54165417print$urls_table;5418 git_heads_body($heads,$head,0,$limit,$dots);5419}54205421# Display a list of remote names with the respective fetch and push URLs5422sub git_remotes_list {5423my($remotedata,$limit) =@_;5424print"<table class=\"heads\">\n";5425my$alternate=1;5426my@remotes=sort keys%$remotedata;54275428my$limited=$limit&&$limit<@remotes;54295430$#remotes=$limit-1if$limited;54315432while(my$remote=shift@remotes) {5433my$rdata=$remotedata->{$remote};5434my$fetch=$rdata->{'fetch'};5435my$push=$rdata->{'push'};5436if($alternate) {5437print"<tr class=\"dark\">\n";5438}else{5439print"<tr class=\"light\">\n";5440}5441$alternate^=1;5442print"<td>".5443$cgi->a({-href=> href(action=>'remotes', hash=>$remote),5444-class=>"list name"},esc_html($remote)) .5445"</td>";5446print"<td class=\"link\">".5447(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .5448" | ".5449(defined$push?$cgi->a({-href=>$push},"push") :"push") .5450"</td>";54515452print"</tr>\n";5453}54545455if($limited) {5456print"<tr>\n".5457"<td colspan=\"3\">".5458$cgi->a({-href => href(action=>"remotes")},"...") .5459"</td>\n"."</tr>\n";5460}54615462print"</table>";5463}54645465# Display remote heads grouped by remote, unless there are too many5466# remotes, in which case we only display the remote names5467sub git_remotes_body {5468my($remotedata,$limit,$head) =@_;5469if($limitand$limit<keys%$remotedata) {5470 git_remotes_list($remotedata,$limit);5471}else{5472 fill_remote_heads($remotedata);5473while(my($remote,$rdata) =each%$remotedata) {5474 git_print_section({-class=>"remote", -id=>$remote},5475["remotes",$remote,$remote],sub{5476 git_remote_block($remote,$rdata,$limit,$head);5477});5478}5479}5480}54815482sub git_search_grep_body {5483my($commitlist,$from,$to,$extra) =@_;5484$from=0unlessdefined$from;5485$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);54865487print"<table class=\"commit_search\">\n";5488my$alternate=1;5489for(my$i=$from;$i<=$to;$i++) {5490my%co= %{$commitlist->[$i]};5491if(!%co) {5492next;5493}5494my$commit=$co{'id'};5495if($alternate) {5496print"<tr class=\"dark\">\n";5497}else{5498print"<tr class=\"light\">\n";5499}5500$alternate^=1;5501print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5502 format_author_html('td', \%co,15,5) .5503"<td>".5504$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5505-class=>"list subject"},5506 chop_and_escape_str($co{'title'},50) ."<br/>");5507my$comment=$co{'comment'};5508foreachmy$line(@$comment) {5509if($line=~m/^(.*?)($search_regexp)(.*)$/i) {5510my($lead,$match,$trail) = ($1,$2,$3);5511$match= chop_str($match,70,5,'center');5512my$contextlen=int((80-length($match))/2);5513$contextlen=30if($contextlen>30);5514$lead= chop_str($lead,$contextlen,10,'left');5515$trail= chop_str($trail,$contextlen,10,'right');55165517$lead= esc_html($lead);5518$match= esc_html($match);5519$trail= esc_html($trail);55205521print"$lead<span class=\"match\">$match</span>$trail<br />";5522}5523}5524print"</td>\n".5525"<td class=\"link\">".5526$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .5527" | ".5528$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .5529" | ".5530$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");5531print"</td>\n".5532"</tr>\n";5533}5534if(defined$extra) {5535print"<tr>\n".5536"<td colspan=\"3\">$extra</td>\n".5537"</tr>\n";5538}5539print"</table>\n";5540}55415542## ======================================================================5543## ======================================================================5544## actions55455546sub git_project_list {5547my$order=$input_params{'order'};5548if(defined$order&&$order!~m/none|project|descr|owner|age/) {5549 die_error(400,"Unknown order parameter");5550}55515552my@list= git_get_projects_list();5553if(!@list) {5554 die_error(404,"No projects found");5555}55565557 git_header_html();5558if(defined$home_text&& -f $home_text) {5559print"<div class=\"index_include\">\n";5560 insert_file($home_text);5561print"</div>\n";5562}5563print$cgi->startform(-method=>"get") .5564"<p class=\"projsearch\">Search:\n".5565$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".5566"</p>".5567$cgi->end_form() ."\n";5568 git_project_list_body(\@list,$order);5569 git_footer_html();5570}55715572sub git_forks {5573my$order=$input_params{'order'};5574if(defined$order&&$order!~m/none|project|descr|owner|age/) {5575 die_error(400,"Unknown order parameter");5576}55775578my@list= git_get_projects_list($project);5579if(!@list) {5580 die_error(404,"No forks found");5581}55825583 git_header_html();5584 git_print_page_nav('','');5585 git_print_header_div('summary',"$projectforks");5586 git_project_list_body(\@list,$order);5587 git_footer_html();5588}55895590sub git_project_index {5591my@projects= git_get_projects_list();5592if(!@projects) {5593 die_error(404,"No projects found");5594}55955596print$cgi->header(5597-type =>'text/plain',5598-charset =>'utf-8',5599-content_disposition =>'inline; filename="index.aux"');56005601foreachmy$pr(@projects) {5602if(!exists$pr->{'owner'}) {5603$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");5604}56055606my($path,$owner) = ($pr->{'path'},$pr->{'owner'});5607# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '5608$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5609$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5610$path=~s/ /\+/g;5611$owner=~s/ /\+/g;56125613print"$path$owner\n";5614}5615}56165617sub git_summary {5618my$descr= git_get_project_description($project) ||"none";5619my%co= parse_commit("HEAD");5620my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();5621my$head=$co{'id'};5622my$remote_heads= gitweb_check_feature('remote_heads');56235624my$owner= git_get_project_owner($project);56255626my$refs= git_get_references();5627# These get_*_list functions return one more to allow us to see if5628# there are more ...5629my@taglist= git_get_tags_list(16);5630my@headlist= git_get_heads_list(16);5631my%remotedata=$remote_heads? git_get_remotes_list() : ();5632my@forklist;5633my$check_forks= gitweb_check_feature('forks');56345635if($check_forks) {5636# find forks of a project5637@forklist= git_get_projects_list($project);5638# filter out forks of forks5639@forklist= filter_forks_from_projects_list(\@forklist)5640if(@forklist);5641}56425643 git_header_html();5644 git_print_page_nav('summary','',$head);56455646print"<div class=\"title\"> </div>\n";5647print"<table class=\"projects_list\">\n".5648"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".5649"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";5650if(defined$cd{'rfc2822'}) {5651print"<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";5652}56535654# use per project git URL list in $projectroot/$project/cloneurl5655# or make project git URL from git base URL and project name5656my$url_tag="URL";5657my@url_list= git_get_project_url_list($project);5658@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;5659foreachmy$git_url(@url_list) {5660next unless$git_url;5661print format_repo_url($url_tag,$git_url);5662$url_tag="";5663}56645665# Tag cloud5666my$show_ctags= gitweb_check_feature('ctags');5667if($show_ctags) {5668my$ctags= git_get_project_ctags($project);5669if(%$ctags) {5670# without ability to add tags, don't show if there are none5671my$cloud= git_populate_project_tagcloud($ctags);5672print"<tr id=\"metadata_ctags\">".5673"<td>content tags</td>".5674"<td>".git_show_project_tagcloud($cloud,48)."</td>".5675"</tr>\n";5676}5677}56785679print"</table>\n";56805681# If XSS prevention is on, we don't include README.html.5682# TODO: Allow a readme in some safe format.5683if(!$prevent_xss&& -s "$projectroot/$project/README.html") {5684print"<div class=\"title\">readme</div>\n".5685"<div class=\"readme\">\n";5686 insert_file("$projectroot/$project/README.html");5687print"\n</div>\n";# class="readme"5688}56895690# we need to request one more than 16 (0..15) to check if5691# those 16 are all5692my@commitlist=$head? parse_commits($head,17) : ();5693if(@commitlist) {5694 git_print_header_div('shortlog');5695 git_shortlog_body(\@commitlist,0,15,$refs,5696$#commitlist<=15?undef:5697$cgi->a({-href => href(action=>"shortlog")},"..."));5698}56995700if(@taglist) {5701 git_print_header_div('tags');5702 git_tags_body(\@taglist,0,15,5703$#taglist<=15?undef:5704$cgi->a({-href => href(action=>"tags")},"..."));5705}57065707if(@headlist) {5708 git_print_header_div('heads');5709 git_heads_body(\@headlist,$head,0,15,5710$#headlist<=15?undef:5711$cgi->a({-href => href(action=>"heads")},"..."));5712}57135714if(%remotedata) {5715 git_print_header_div('remotes');5716 git_remotes_body(\%remotedata,15,$head);5717}57185719if(@forklist) {5720 git_print_header_div('forks');5721 git_project_list_body(\@forklist,'age',0,15,5722$#forklist<=15?undef:5723$cgi->a({-href => href(action=>"forks")},"..."),5724'no_header');5725}57265727 git_footer_html();5728}57295730sub git_tag {5731my%tag= parse_tag($hash);57325733if(!%tag) {5734 die_error(404,"Unknown tag object");5735}57365737my$head= git_get_head_hash($project);5738 git_header_html();5739 git_print_page_nav('','',$head,undef,$head);5740 git_print_header_div('commit', esc_html($tag{'name'}),$hash);5741print"<div class=\"title_text\">\n".5742"<table class=\"object_header\">\n".5743"<tr>\n".5744"<td>object</td>\n".5745"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5746$tag{'object'}) ."</td>\n".5747"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5748$tag{'type'}) ."</td>\n".5749"</tr>\n";5750if(defined($tag{'author'})) {5751 git_print_authorship_rows(\%tag,'author');5752}5753print"</table>\n\n".5754"</div>\n";5755print"<div class=\"page_body\">";5756my$comment=$tag{'comment'};5757foreachmy$line(@$comment) {5758chomp$line;5759print esc_html($line, -nbsp=>1) ."<br/>\n";5760}5761print"</div>\n";5762 git_footer_html();5763}57645765sub git_blame_common {5766my$format=shift||'porcelain';5767if($formateq'porcelain'&&$cgi->param('js')) {5768$format='incremental';5769$action='blame_incremental';# for page title etc5770}57715772# permissions5773 gitweb_check_feature('blame')5774or die_error(403,"Blame view not allowed");57755776# error checking5777 die_error(400,"No file name given")unless$file_name;5778$hash_base||= git_get_head_hash($project);5779 die_error(404,"Couldn't find base commit")unless$hash_base;5780my%co= parse_commit($hash_base)5781or die_error(404,"Commit not found");5782my$ftype="blob";5783if(!defined$hash) {5784$hash= git_get_hash_by_path($hash_base,$file_name,"blob")5785or die_error(404,"Error looking up file");5786}else{5787$ftype= git_get_type($hash);5788if($ftype!~"blob") {5789 die_error(400,"Object is not a blob");5790}5791}57925793my$fd;5794if($formateq'incremental') {5795# get file contents (as base)5796open$fd,"-|", git_cmd(),'cat-file','blob',$hash5797or die_error(500,"Open git-cat-file failed");5798}elsif($formateq'data') {5799# run git-blame --incremental5800open$fd,"-|", git_cmd(),"blame","--incremental",5801$hash_base,"--",$file_name5802or die_error(500,"Open git-blame --incremental failed");5803}else{5804# run git-blame --porcelain5805open$fd,"-|", git_cmd(),"blame",'-p',5806$hash_base,'--',$file_name5807or die_error(500,"Open git-blame --porcelain failed");5808}58095810# incremental blame data returns early5811if($formateq'data') {5812print$cgi->header(5813-type=>"text/plain", -charset =>"utf-8",5814-status=>"200 OK");5815local$| =1;# output autoflush5816printwhile<$fd>;5817close$fd5818or print"ERROR$!\n";58195820print'END';5821if(defined$t0&& gitweb_check_feature('timed')) {5822print' '.5823 tv_interval($t0, [ gettimeofday() ]).5824' '.$number_of_git_cmds;5825}5826print"\n";58275828return;5829}58305831# page header5832 git_header_html();5833my$formats_nav=5834$cgi->a({-href => href(action=>"blob", -replay=>1)},5835"blob") .5836" | ";5837if($formateq'incremental') {5838$formats_nav.=5839$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},5840"blame") ." (non-incremental)";5841}else{5842$formats_nav.=5843$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},5844"blame") ." (incremental)";5845}5846$formats_nav.=5847" | ".5848$cgi->a({-href => href(action=>"history", -replay=>1)},5849"history") .5850" | ".5851$cgi->a({-href => href(action=>$action, file_name=>$file_name)},5852"HEAD");5853 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5854 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5855 git_print_page_path($file_name,$ftype,$hash_base);58565857# page body5858if($formateq'incremental') {5859print"<noscript>\n<div class=\"error\"><center><b>\n".5860"This page requires JavaScript to run.\nUse ".5861$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},5862'this page').5863" instead.\n".5864"</b></center></div>\n</noscript>\n";58655866print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;5867}58685869print qq!<div class="page_body">\n!;5870print qq!<div id="progress_info">.../ ...</div>\n!5871if($formateq'incremental');5872print qq!<table id="blame_table"class="blame" width="100%">\n!.5873#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.5874 qq!<thead>\n!.5875 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.5876 qq!</thead>\n!.5877 qq!<tbody>\n!;58785879my@rev_color=qw(light dark);5880my$num_colors=scalar(@rev_color);5881my$current_color=0;58825883if($formateq'incremental') {5884my$color_class=$rev_color[$current_color];58855886#contents of a file5887my$linenr=0;5888 LINE:5889while(my$line= <$fd>) {5890chomp$line;5891$linenr++;58925893print qq!<tr id="l$linenr"class="$color_class">!.5894 qq!<td class="sha1"><a href=""> </a></td>!.5895 qq!<td class="linenr">!.5896 qq!<a class="linenr" href="">$linenr</a></td>!;5897print qq!<td class="pre">! . esc_html($line) ."</td>\n";5898print qq!</tr>\n!;5899}59005901}else{# porcelain, i.e. ordinary blame5902my%metainfo= ();# saves information about commits59035904# blame data5905 LINE:5906while(my$line= <$fd>) {5907chomp$line;5908# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]5909# no <lines in group> for subsequent lines in group of lines5910my($full_rev,$orig_lineno,$lineno,$group_size) =5911($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);5912if(!exists$metainfo{$full_rev}) {5913$metainfo{$full_rev} = {'nprevious'=>0};5914}5915my$meta=$metainfo{$full_rev};5916my$data;5917while($data= <$fd>) {5918chomp$data;5919last if($data=~s/^\t//);# contents of line5920if($data=~/^(\S+)(?: (.*))?$/) {5921$meta->{$1} =$2unlessexists$meta->{$1};5922}5923if($data=~/^previous /) {5924$meta->{'nprevious'}++;5925}5926}5927my$short_rev=substr($full_rev,0,8);5928my$author=$meta->{'author'};5929my%date=5930 parse_date($meta->{'author-time'},$meta->{'author-tz'});5931my$date=$date{'iso-tz'};5932if($group_size) {5933$current_color= ($current_color+1) %$num_colors;5934}5935my$tr_class=$rev_color[$current_color];5936$tr_class.=' boundary'if(exists$meta->{'boundary'});5937$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);5938$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);5939print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";5940if($group_size) {5941print"<td class=\"sha1\"";5942print" title=\"". esc_html($author) .",$date\"";5943print" rowspan=\"$group_size\""if($group_size>1);5944print">";5945print$cgi->a({-href => href(action=>"commit",5946 hash=>$full_rev,5947 file_name=>$file_name)},5948 esc_html($short_rev));5949if($group_size>=2) {5950my@author_initials= ($author=~/\b([[:upper:]])\B/g);5951if(@author_initials) {5952print"<br />".5953 esc_html(join('',@author_initials));5954# or join('.', ...)5955}5956}5957print"</td>\n";5958}5959# 'previous' <sha1 of parent commit> <filename at commit>5960if(exists$meta->{'previous'} &&5961$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {5962$meta->{'parent'} =$1;5963$meta->{'file_parent'} = unquote($2);5964}5965my$linenr_commit=5966exists($meta->{'parent'}) ?5967$meta->{'parent'} :$full_rev;5968my$linenr_filename=5969exists($meta->{'file_parent'}) ?5970$meta->{'file_parent'} : unquote($meta->{'filename'});5971my$blamed= href(action =>'blame',5972 file_name =>$linenr_filename,5973 hash_base =>$linenr_commit);5974print"<td class=\"linenr\">";5975print$cgi->a({ -href =>"$blamed#l$orig_lineno",5976-class=>"linenr"},5977 esc_html($lineno));5978print"</td>";5979print"<td class=\"pre\">". esc_html($data) ."</td>\n";5980print"</tr>\n";5981}# end while59825983}59845985# footer5986print"</tbody>\n".5987"</table>\n";# class="blame"5988print"</div>\n";# class="blame_body"5989close$fd5990or print"Reading blob failed\n";59915992 git_footer_html();5993}59945995sub git_blame {5996 git_blame_common();5997}59985999sub git_blame_incremental {6000 git_blame_common('incremental');6001}60026003sub git_blame_data {6004 git_blame_common('data');6005}60066007sub git_tags {6008my$head= git_get_head_hash($project);6009 git_header_html();6010 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6011 git_print_header_div('summary',$project);60126013my@tagslist= git_get_tags_list();6014if(@tagslist) {6015 git_tags_body(\@tagslist);6016}6017 git_footer_html();6018}60196020sub git_heads {6021my$head= git_get_head_hash($project);6022 git_header_html();6023 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6024 git_print_header_div('summary',$project);60256026my@headslist= git_get_heads_list();6027if(@headslist) {6028 git_heads_body(\@headslist,$head);6029}6030 git_footer_html();6031}60326033# used both for single remote view and for list of all the remotes6034sub git_remotes {6035 gitweb_check_feature('remote_heads')6036or die_error(403,"Remote heads view is disabled");60376038my$head= git_get_head_hash($project);6039my$remote=$input_params{'hash'};60406041my$remotedata= git_get_remotes_list($remote);6042 die_error(500,"Unable to get remote information")unlessdefined$remotedata;60436044unless(%$remotedata) {6045 die_error(404,defined$remote?6046"Remote$remotenot found":6047"No remotes found");6048}60496050 git_header_html(undef,undef, -action_extra =>$remote);6051 git_print_page_nav('','',$head,undef,$head,6052 format_ref_views($remote?'':'remotes'));60536054 fill_remote_heads($remotedata);6055if(defined$remote) {6056 git_print_header_div('remotes',"$remoteremote for$project");6057 git_remote_block($remote,$remotedata->{$remote},undef,$head);6058}else{6059 git_print_header_div('summary',"$projectremotes");6060 git_remotes_body($remotedata,undef,$head);6061}60626063 git_footer_html();6064}60656066sub git_blob_plain {6067my$type=shift;6068my$expires;60696070if(!defined$hash) {6071if(defined$file_name) {6072my$base=$hash_base|| git_get_head_hash($project);6073$hash= git_get_hash_by_path($base,$file_name,"blob")6074or die_error(404,"Cannot find file");6075}else{6076 die_error(400,"No file name defined");6077}6078}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6079# blobs defined by non-textual hash id's can be cached6080$expires="+1d";6081}60826083open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6084or die_error(500,"Open git-cat-file blob '$hash' failed");60856086# content-type (can include charset)6087$type= blob_contenttype($fd,$file_name,$type);60886089# "save as" filename, even when no $file_name is given6090my$save_as="$hash";6091if(defined$file_name) {6092$save_as=$file_name;6093}elsif($type=~m/^text\//) {6094$save_as.='.txt';6095}60966097# With XSS prevention on, blobs of all types except a few known safe6098# ones are served with "Content-Disposition: attachment" to make sure6099# they don't run in our security domain. For certain image types,6100# blob view writes an <img> tag referring to blob_plain view, and we6101# want to be sure not to break that by serving the image as an6102# attachment (though Firefox 3 doesn't seem to care).6103my$sandbox=$prevent_xss&&6104$type!~m!^(?:text/plain|image/(?:gif|png|jpeg))$!;61056106print$cgi->header(6107-type =>$type,6108-expires =>$expires,6109-content_disposition =>6110($sandbox?'attachment':'inline')6111.'; filename="'.$save_as.'"');6112local$/=undef;6113binmode STDOUT,':raw';6114print<$fd>;6115binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6116close$fd;6117}61186119sub git_blob {6120my$expires;61216122if(!defined$hash) {6123if(defined$file_name) {6124my$base=$hash_base|| git_get_head_hash($project);6125$hash= git_get_hash_by_path($base,$file_name,"blob")6126or die_error(404,"Cannot find file");6127}else{6128 die_error(400,"No file name defined");6129}6130}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6131# blobs defined by non-textual hash id's can be cached6132$expires="+1d";6133}61346135my$have_blame= gitweb_check_feature('blame');6136open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6137or die_error(500,"Couldn't cat$file_name,$hash");6138my$mimetype= blob_mimetype($fd,$file_name);6139# use 'blob_plain' (aka 'raw') view for files that cannot be displayed6140if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {6141close$fd;6142return git_blob_plain($mimetype);6143}6144# we can have blame only for text/* mimetype6145$have_blame&&= ($mimetype=~m!^text/!);61466147my$highlight= gitweb_check_feature('highlight');6148my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);6149$fd= run_highlighter($fd,$highlight,$syntax)6150if$syntax;61516152 git_header_html(undef,$expires);6153my$formats_nav='';6154if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6155if(defined$file_name) {6156if($have_blame) {6157$formats_nav.=6158$cgi->a({-href => href(action=>"blame", -replay=>1)},6159"blame") .6160" | ";6161}6162$formats_nav.=6163$cgi->a({-href => href(action=>"history", -replay=>1)},6164"history") .6165" | ".6166$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6167"raw") .6168" | ".6169$cgi->a({-href => href(action=>"blob",6170 hash_base=>"HEAD", file_name=>$file_name)},6171"HEAD");6172}else{6173$formats_nav.=6174$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6175"raw");6176}6177 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6178 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6179}else{6180print"<div class=\"page_nav\">\n".6181"<br/><br/></div>\n".6182"<div class=\"title\">".esc_html($hash)."</div>\n";6183}6184 git_print_page_path($file_name,"blob",$hash_base);6185print"<div class=\"page_body\">\n";6186if($mimetype=~m!^image/!) {6187print qq!<img type="!.esc_attr($mimetype).qq!"!;6188if($file_name) {6189print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;6190}6191print qq! src="! .6192 href(action=>"blob_plain", hash=>$hash,6193 hash_base=>$hash_base, file_name=>$file_name) .6194 qq!"/>\n!;6195}else{6196my$nr;6197while(my$line= <$fd>) {6198chomp$line;6199$nr++;6200$line= untabify($line);6201printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,6202$nr, esc_attr(href(-replay =>1)),$nr,$nr,$syntax?$line: esc_html($line, -nbsp=>1);6203}6204}6205close$fd6206or print"Reading blob failed.\n";6207print"</div>";6208 git_footer_html();6209}62106211sub git_tree {6212if(!defined$hash_base) {6213$hash_base="HEAD";6214}6215if(!defined$hash) {6216if(defined$file_name) {6217$hash= git_get_hash_by_path($hash_base,$file_name,"tree");6218}else{6219$hash=$hash_base;6220}6221}6222 die_error(404,"No such tree")unlessdefined($hash);62236224my$show_sizes= gitweb_check_feature('show-sizes');6225my$have_blame= gitweb_check_feature('blame');62266227my@entries= ();6228{6229local$/="\0";6230open my$fd,"-|", git_cmd(),"ls-tree",'-z',6231($show_sizes?'-l': ()),@extra_options,$hash6232or die_error(500,"Open git-ls-tree failed");6233@entries=map{chomp;$_} <$fd>;6234close$fd6235or die_error(404,"Reading tree failed");6236}62376238my$refs= git_get_references();6239my$ref= format_ref_marker($refs,$hash_base);6240 git_header_html();6241my$basedir='';6242if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6243my@views_nav= ();6244if(defined$file_name) {6245push@views_nav,6246$cgi->a({-href => href(action=>"history", -replay=>1)},6247"history"),6248$cgi->a({-href => href(action=>"tree",6249 hash_base=>"HEAD", file_name=>$file_name)},6250"HEAD"),6251}6252my$snapshot_links= format_snapshot_links($hash);6253if(defined$snapshot_links) {6254# FIXME: Should be available when we have no hash base as well.6255push@views_nav,$snapshot_links;6256}6257 git_print_page_nav('tree','',$hash_base,undef,undef,6258join(' | ',@views_nav));6259 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);6260}else{6261undef$hash_base;6262print"<div class=\"page_nav\">\n";6263print"<br/><br/></div>\n";6264print"<div class=\"title\">".esc_html($hash)."</div>\n";6265}6266if(defined$file_name) {6267$basedir=$file_name;6268if($basedirne''&&substr($basedir, -1)ne'/') {6269$basedir.='/';6270}6271 git_print_page_path($file_name,'tree',$hash_base);6272}6273print"<div class=\"page_body\">\n";6274print"<table class=\"tree\">\n";6275my$alternate=1;6276# '..' (top directory) link if possible6277if(defined$hash_base&&6278defined$file_name&&$file_name=~m![^/]+$!) {6279if($alternate) {6280print"<tr class=\"dark\">\n";6281}else{6282print"<tr class=\"light\">\n";6283}6284$alternate^=1;62856286my$up=$file_name;6287$up=~s!/?[^/]+$!!;6288undef$upunless$up;6289# based on git_print_tree_entry6290print'<td class="mode">'. mode_str('040000') ."</td>\n";6291print'<td class="size"> </td>'."\n"if$show_sizes;6292print'<td class="list">';6293print$cgi->a({-href => href(action=>"tree",6294 hash_base=>$hash_base,6295 file_name=>$up)},6296"..");6297print"</td>\n";6298print"<td class=\"link\"></td>\n";62996300print"</tr>\n";6301}6302foreachmy$line(@entries) {6303my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);63046305if($alternate) {6306print"<tr class=\"dark\">\n";6307}else{6308print"<tr class=\"light\">\n";6309}6310$alternate^=1;63116312 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);63136314print"</tr>\n";6315}6316print"</table>\n".6317"</div>";6318 git_footer_html();6319}63206321sub snapshot_name {6322my($project,$hash) =@_;63236324# path/to/project.git -> project6325# path/to/project/.git -> project6326my$name= to_utf8($project);6327$name=~ s,([^/])/*\.git$,$1,;6328$name= basename($name);6329# sanitize name6330$name=~s/[[:cntrl:]]/?/g;63316332my$ver=$hash;6333if($hash=~/^[0-9a-fA-F]+$/) {6334# shorten SHA-1 hash6335my$full_hash= git_get_full_hash($project,$hash);6336if($full_hash=~/^$hash/&&length($hash) >7) {6337$ver= git_get_short_hash($project,$hash);6338}6339}elsif($hash=~m!^refs/tags/(.*)$!) {6340# tags don't need shortened SHA-1 hash6341$ver=$1;6342}else{6343# branches and other need shortened SHA-1 hash6344if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {6345$ver=$1;6346}6347$ver.='-'. git_get_short_hash($project,$hash);6348}6349# in case of hierarchical branch names6350$ver=~s!/!.!g;63516352# name = project-version_string6353$name="$name-$ver";63546355returnwantarray? ($name,$name) :$name;6356}63576358sub git_snapshot {6359my$format=$input_params{'snapshot_format'};6360if(!@snapshot_fmts) {6361 die_error(403,"Snapshots not allowed");6362}6363# default to first supported snapshot format6364$format||=$snapshot_fmts[0];6365if($format!~m/^[a-z0-9]+$/) {6366 die_error(400,"Invalid snapshot format parameter");6367}elsif(!exists($known_snapshot_formats{$format})) {6368 die_error(400,"Unknown snapshot format");6369}elsif($known_snapshot_formats{$format}{'disabled'}) {6370 die_error(403,"Snapshot format not allowed");6371}elsif(!grep($_eq$format,@snapshot_fmts)) {6372 die_error(403,"Unsupported snapshot format");6373}63746375my$type= git_get_type("$hash^{}");6376if(!$type) {6377 die_error(404,'Object does not exist');6378}elsif($typeeq'blob') {6379 die_error(400,'Object is not a tree-ish');6380}63816382my($name,$prefix) = snapshot_name($project,$hash);6383my$filename="$name$known_snapshot_formats{$format}{'suffix'}";6384my$cmd= quote_command(6385 git_cmd(),'archive',6386"--format=$known_snapshot_formats{$format}{'format'}",6387"--prefix=$prefix/",$hash);6388if(exists$known_snapshot_formats{$format}{'compressor'}) {6389$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});6390}63916392$filename=~s/(["\\])/\\$1/g;6393print$cgi->header(6394-type =>$known_snapshot_formats{$format}{'type'},6395-content_disposition =>'inline; filename="'.$filename.'"',6396-status =>'200 OK');63976398open my$fd,"-|",$cmd6399or die_error(500,"Execute git-archive failed");6400binmode STDOUT,':raw';6401print<$fd>;6402binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6403close$fd;6404}64056406sub git_log_generic {6407my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;64086409my$head= git_get_head_hash($project);6410if(!defined$base) {6411$base=$head;6412}6413if(!defined$page) {6414$page=0;6415}6416my$refs= git_get_references();64176418my$commit_hash=$base;6419if(defined$parent) {6420$commit_hash="$parent..$base";6421}6422my@commitlist=6423 parse_commits($commit_hash,101, (100*$page),6424defined$file_name? ($file_name,"--full-history") : ());64256426my$ftype;6427if(!defined$file_hash&&defined$file_name) {6428# some commits could have deleted file in question,6429# and not have it in tree, but one of them has to have it6430for(my$i=0;$i<@commitlist;$i++) {6431$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);6432last ifdefined$file_hash;6433}6434}6435if(defined$file_hash) {6436$ftype= git_get_type($file_hash);6437}6438if(defined$file_name&& !defined$ftype) {6439 die_error(500,"Unknown type of object");6440}6441my%co;6442if(defined$file_name) {6443%co= parse_commit($base)6444or die_error(404,"Unknown commit object");6445}644664476448my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);6449my$next_link='';6450if($#commitlist>=100) {6451$next_link=6452$cgi->a({-href => href(-replay=>1, page=>$page+1),6453-accesskey =>"n", -title =>"Alt-n"},"next");6454}6455my$patch_max= gitweb_get_feature('patches');6456if($patch_max&& !defined$file_name) {6457if($patch_max<0||@commitlist<=$patch_max) {6458$paging_nav.=" ⋅ ".6459$cgi->a({-href => href(action=>"patches", -replay=>1)},6460"patches");6461}6462}64636464 git_header_html();6465 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);6466if(defined$file_name) {6467 git_print_header_div('commit', esc_html($co{'title'}),$base);6468}else{6469 git_print_header_div('summary',$project)6470}6471 git_print_page_path($file_name,$ftype,$hash_base)6472if(defined$file_name);64736474$body_subr->(\@commitlist,0,99,$refs,$next_link,6475$file_name,$file_hash,$ftype);64766477 git_footer_html();6478}64796480sub git_log {6481 git_log_generic('log', \&git_log_body,6482$hash,$hash_parent);6483}64846485sub git_commit {6486$hash||=$hash_base||"HEAD";6487my%co= parse_commit($hash)6488or die_error(404,"Unknown commit object");64896490my$parent=$co{'parent'};6491my$parents=$co{'parents'};# listref64926493# we need to prepare $formats_nav before any parameter munging6494my$formats_nav;6495if(!defined$parent) {6496# --root commitdiff6497$formats_nav.='(initial)';6498}elsif(@$parents==1) {6499# single parent commit6500$formats_nav.=6501'(parent: '.6502$cgi->a({-href => href(action=>"commit",6503 hash=>$parent)},6504 esc_html(substr($parent,0,7))) .6505')';6506}else{6507# merge commit6508$formats_nav.=6509'(merge: '.6510join(' ',map{6511$cgi->a({-href => href(action=>"commit",6512 hash=>$_)},6513 esc_html(substr($_,0,7)));6514}@$parents) .6515')';6516}6517if(gitweb_check_feature('patches') &&@$parents<=1) {6518$formats_nav.=" | ".6519$cgi->a({-href => href(action=>"patch", -replay=>1)},6520"patch");6521}65226523if(!defined$parent) {6524$parent="--root";6525}6526my@difftree;6527open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",6528@diff_opts,6529(@$parents<=1?$parent:'-c'),6530$hash,"--"6531or die_error(500,"Open git-diff-tree failed");6532@difftree=map{chomp;$_} <$fd>;6533close$fdor die_error(404,"Reading git-diff-tree failed");65346535# non-textual hash id's can be cached6536my$expires;6537if($hash=~m/^[0-9a-fA-F]{40}$/) {6538$expires="+1d";6539}6540my$refs= git_get_references();6541my$ref= format_ref_marker($refs,$co{'id'});65426543 git_header_html(undef,$expires);6544 git_print_page_nav('commit','',6545$hash,$co{'tree'},$hash,6546$formats_nav);65476548if(defined$co{'parent'}) {6549 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);6550}else{6551 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);6552}6553print"<div class=\"title_text\">\n".6554"<table class=\"object_header\">\n";6555 git_print_authorship_rows(\%co);6556print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";6557print"<tr>".6558"<td>tree</td>".6559"<td class=\"sha1\">".6560$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),6561class=>"list"},$co{'tree'}) .6562"</td>".6563"<td class=\"link\">".6564$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},6565"tree");6566my$snapshot_links= format_snapshot_links($hash);6567if(defined$snapshot_links) {6568print" | ".$snapshot_links;6569}6570print"</td>".6571"</tr>\n";65726573foreachmy$par(@$parents) {6574print"<tr>".6575"<td>parent</td>".6576"<td class=\"sha1\">".6577$cgi->a({-href => href(action=>"commit", hash=>$par),6578class=>"list"},$par) .6579"</td>".6580"<td class=\"link\">".6581$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .6582" | ".6583$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .6584"</td>".6585"</tr>\n";6586}6587print"</table>".6588"</div>\n";65896590print"<div class=\"page_body\">\n";6591 git_print_log($co{'comment'});6592print"</div>\n";65936594 git_difftree_body(\@difftree,$hash,@$parents);65956596 git_footer_html();6597}65986599sub git_object {6600# object is defined by:6601# - hash or hash_base alone6602# - hash_base and file_name6603my$type;66046605# - hash or hash_base alone6606if($hash|| ($hash_base&& !defined$file_name)) {6607my$object_id=$hash||$hash_base;66086609open my$fd,"-|", quote_command(6610 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'6611or die_error(404,"Object does not exist");6612$type= <$fd>;6613chomp$type;6614close$fd6615or die_error(404,"Object does not exist");66166617# - hash_base and file_name6618}elsif($hash_base&&defined$file_name) {6619$file_name=~ s,/+$,,;66206621system(git_cmd(),"cat-file",'-e',$hash_base) ==06622or die_error(404,"Base object does not exist");66236624# here errors should not hapen6625open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name6626or die_error(500,"Open git-ls-tree failed");6627my$line= <$fd>;6628close$fd;66296630#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'6631unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {6632 die_error(404,"File or directory for given base does not exist");6633}6634$type=$2;6635$hash=$3;6636}else{6637 die_error(400,"Not enough information to find object");6638}66396640print$cgi->redirect(-uri => href(action=>$type, -full=>1,6641 hash=>$hash, hash_base=>$hash_base,6642 file_name=>$file_name),6643-status =>'302 Found');6644}66456646sub git_blobdiff {6647my$format=shift||'html';66486649my$fd;6650my@difftree;6651my%diffinfo;6652my$expires;66536654# preparing $fd and %diffinfo for git_patchset_body6655# new style URI6656if(defined$hash_base&&defined$hash_parent_base) {6657if(defined$file_name) {6658# read raw output6659open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6660$hash_parent_base,$hash_base,6661"--", (defined$file_parent?$file_parent: ()),$file_name6662or die_error(500,"Open git-diff-tree failed");6663@difftree=map{chomp;$_} <$fd>;6664close$fd6665or die_error(404,"Reading git-diff-tree failed");6666@difftree6667or die_error(404,"Blob diff not found");66686669}elsif(defined$hash&&6670$hash=~/[0-9a-fA-F]{40}/) {6671# try to find filename from $hash66726673# read filtered raw output6674open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6675$hash_parent_base,$hash_base,"--"6676or die_error(500,"Open git-diff-tree failed");6677@difftree=6678# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'6679# $hash == to_id6680grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}6681map{chomp;$_} <$fd>;6682close$fd6683or die_error(404,"Reading git-diff-tree failed");6684@difftree6685or die_error(404,"Blob diff not found");66866687}else{6688 die_error(400,"Missing one of the blob diff parameters");6689}66906691if(@difftree>1) {6692 die_error(400,"Ambiguous blob diff specification");6693}66946695%diffinfo= parse_difftree_raw_line($difftree[0]);6696$file_parent||=$diffinfo{'from_file'} ||$file_name;6697$file_name||=$diffinfo{'to_file'};66986699$hash_parent||=$diffinfo{'from_id'};6700$hash||=$diffinfo{'to_id'};67016702# non-textual hash id's can be cached6703if($hash_base=~m/^[0-9a-fA-F]{40}$/&&6704$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {6705$expires='+1d';6706}67076708# open patch output6709open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6710'-p', ($formateq'html'?"--full-index": ()),6711$hash_parent_base,$hash_base,6712"--", (defined$file_parent?$file_parent: ()),$file_name6713or die_error(500,"Open git-diff-tree failed");6714}67156716# old/legacy style URI -- not generated anymore since 1.4.3.6717if(!%diffinfo) {6718 die_error('404 Not Found',"Missing one of the blob diff parameters")6719}67206721# header6722if($formateq'html') {6723my$formats_nav=6724$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},6725"raw");6726 git_header_html(undef,$expires);6727if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6728 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6729 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6730}else{6731print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";6732print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";6733}6734if(defined$file_name) {6735 git_print_page_path($file_name,"blob",$hash_base);6736}else{6737print"<div class=\"page_path\"></div>\n";6738}67396740}elsif($formateq'plain') {6741print$cgi->header(6742-type =>'text/plain',6743-charset =>'utf-8',6744-expires =>$expires,6745-content_disposition =>'inline; filename="'."$file_name".'.patch"');67466747print"X-Git-Url: ".$cgi->self_url() ."\n\n";67486749}else{6750 die_error(400,"Unknown blobdiff format");6751}67526753# patch6754if($formateq'html') {6755print"<div class=\"page_body\">\n";67566757 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);6758close$fd;67596760print"</div>\n";# class="page_body"6761 git_footer_html();67626763}else{6764while(my$line= <$fd>) {6765$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;6766$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;67676768print$line;67696770last if$line=~m!^\+\+\+!;6771}6772local$/=undef;6773print<$fd>;6774close$fd;6775}6776}67776778sub git_blobdiff_plain {6779 git_blobdiff('plain');6780}67816782sub git_commitdiff {6783my%params=@_;6784my$format=$params{-format} ||'html';67856786my($patch_max) = gitweb_get_feature('patches');6787if($formateq'patch') {6788 die_error(403,"Patch view not allowed")unless$patch_max;6789}67906791$hash||=$hash_base||"HEAD";6792my%co= parse_commit($hash)6793or die_error(404,"Unknown commit object");67946795# choose format for commitdiff for merge6796if(!defined$hash_parent&& @{$co{'parents'}} >1) {6797$hash_parent='--cc';6798}6799# we need to prepare $formats_nav before almost any parameter munging6800my$formats_nav;6801if($formateq'html') {6802$formats_nav=6803$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},6804"raw");6805if($patch_max&& @{$co{'parents'}} <=1) {6806$formats_nav.=" | ".6807$cgi->a({-href => href(action=>"patch", -replay=>1)},6808"patch");6809}68106811if(defined$hash_parent&&6812$hash_parentne'-c'&&$hash_parentne'--cc') {6813# commitdiff with two commits given6814my$hash_parent_short=$hash_parent;6815if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {6816$hash_parent_short=substr($hash_parent,0,7);6817}6818$formats_nav.=6819' (from';6820for(my$i=0;$i< @{$co{'parents'}};$i++) {6821if($co{'parents'}[$i]eq$hash_parent) {6822$formats_nav.=' parent '. ($i+1);6823last;6824}6825}6826$formats_nav.=': '.6827$cgi->a({-href => href(action=>"commitdiff",6828 hash=>$hash_parent)},6829 esc_html($hash_parent_short)) .6830')';6831}elsif(!$co{'parent'}) {6832# --root commitdiff6833$formats_nav.=' (initial)';6834}elsif(scalar@{$co{'parents'}} ==1) {6835# single parent commit6836$formats_nav.=6837' (parent: '.6838$cgi->a({-href => href(action=>"commitdiff",6839 hash=>$co{'parent'})},6840 esc_html(substr($co{'parent'},0,7))) .6841')';6842}else{6843# merge commit6844if($hash_parenteq'--cc') {6845$formats_nav.=' | '.6846$cgi->a({-href => href(action=>"commitdiff",6847 hash=>$hash, hash_parent=>'-c')},6848'combined');6849}else{# $hash_parent eq '-c'6850$formats_nav.=' | '.6851$cgi->a({-href => href(action=>"commitdiff",6852 hash=>$hash, hash_parent=>'--cc')},6853'compact');6854}6855$formats_nav.=6856' (merge: '.6857join(' ',map{6858$cgi->a({-href => href(action=>"commitdiff",6859 hash=>$_)},6860 esc_html(substr($_,0,7)));6861} @{$co{'parents'}} ) .6862')';6863}6864}68656866my$hash_parent_param=$hash_parent;6867if(!defined$hash_parent_param) {6868# --cc for multiple parents, --root for parentless6869$hash_parent_param=6870@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';6871}68726873# read commitdiff6874my$fd;6875my@difftree;6876if($formateq'html') {6877open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6878"--no-commit-id","--patch-with-raw","--full-index",6879$hash_parent_param,$hash,"--"6880or die_error(500,"Open git-diff-tree failed");68816882while(my$line= <$fd>) {6883chomp$line;6884# empty line ends raw part of diff-tree output6885last unless$line;6886push@difftree,scalar parse_difftree_raw_line($line);6887}68886889}elsif($formateq'plain') {6890open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6891'-p',$hash_parent_param,$hash,"--"6892or die_error(500,"Open git-diff-tree failed");6893}elsif($formateq'patch') {6894# For commit ranges, we limit the output to the number of6895# patches specified in the 'patches' feature.6896# For single commits, we limit the output to a single patch,6897# diverging from the git-format-patch default.6898my@commit_spec= ();6899if($hash_parent) {6900if($patch_max>0) {6901push@commit_spec,"-$patch_max";6902}6903push@commit_spec,'-n',"$hash_parent..$hash";6904}else{6905if($params{-single}) {6906push@commit_spec,'-1';6907}else{6908if($patch_max>0) {6909push@commit_spec,"-$patch_max";6910}6911push@commit_spec,"-n";6912}6913push@commit_spec,'--root',$hash;6914}6915open$fd,"-|", git_cmd(),"format-patch",@diff_opts,6916'--encoding=utf8','--stdout',@commit_spec6917or die_error(500,"Open git-format-patch failed");6918}else{6919 die_error(400,"Unknown commitdiff format");6920}69216922# non-textual hash id's can be cached6923my$expires;6924if($hash=~m/^[0-9a-fA-F]{40}$/) {6925$expires="+1d";6926}69276928# write commit message6929if($formateq'html') {6930my$refs= git_get_references();6931my$ref= format_ref_marker($refs,$co{'id'});69326933 git_header_html(undef,$expires);6934 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);6935 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);6936print"<div class=\"title_text\">\n".6937"<table class=\"object_header\">\n";6938 git_print_authorship_rows(\%co);6939print"</table>".6940"</div>\n";6941print"<div class=\"page_body\">\n";6942if(@{$co{'comment'}} >1) {6943print"<div class=\"log\">\n";6944 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);6945print"</div>\n";# class="log"6946}69476948}elsif($formateq'plain') {6949my$refs= git_get_references("tags");6950my$tagname= git_get_rev_name_tags($hash);6951my$filename= basename($project) ."-$hash.patch";69526953print$cgi->header(6954-type =>'text/plain',6955-charset =>'utf-8',6956-expires =>$expires,6957-content_disposition =>'inline; filename="'."$filename".'"');6958my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});6959print"From: ". to_utf8($co{'author'}) ."\n";6960print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";6961print"Subject: ". to_utf8($co{'title'}) ."\n";69626963print"X-Git-Tag:$tagname\n"if$tagname;6964print"X-Git-Url: ".$cgi->self_url() ."\n\n";69656966foreachmy$line(@{$co{'comment'}}) {6967print to_utf8($line) ."\n";6968}6969print"---\n\n";6970}elsif($formateq'patch') {6971my$filename= basename($project) ."-$hash.patch";69726973print$cgi->header(6974-type =>'text/plain',6975-charset =>'utf-8',6976-expires =>$expires,6977-content_disposition =>'inline; filename="'."$filename".'"');6978}69796980# write patch6981if($formateq'html') {6982my$use_parents= !defined$hash_parent||6983$hash_parenteq'-c'||$hash_parenteq'--cc';6984 git_difftree_body(\@difftree,$hash,6985$use_parents? @{$co{'parents'}} :$hash_parent);6986print"<br/>\n";69876988 git_patchset_body($fd, \@difftree,$hash,6989$use_parents? @{$co{'parents'}} :$hash_parent);6990close$fd;6991print"</div>\n";# class="page_body"6992 git_footer_html();69936994}elsif($formateq'plain') {6995local$/=undef;6996print<$fd>;6997close$fd6998or print"Reading git-diff-tree failed\n";6999}elsif($formateq'patch') {7000local$/=undef;7001print<$fd>;7002close$fd7003or print"Reading git-format-patch failed\n";7004}7005}70067007sub git_commitdiff_plain {7008 git_commitdiff(-format =>'plain');7009}70107011# format-patch-style patches7012sub git_patch {7013 git_commitdiff(-format =>'patch', -single =>1);7014}70157016sub git_patches {7017 git_commitdiff(-format =>'patch');7018}70197020sub git_history {7021 git_log_generic('history', \&git_history_body,7022$hash_base,$hash_parent_base,7023$file_name,$hash);7024}70257026sub git_search {7027 gitweb_check_feature('search')or die_error(403,"Search is disabled");7028if(!defined$searchtext) {7029 die_error(400,"Text field is empty");7030}7031if(!defined$hash) {7032$hash= git_get_head_hash($project);7033}7034my%co= parse_commit($hash);7035if(!%co) {7036 die_error(404,"Unknown commit object");7037}7038if(!defined$page) {7039$page=0;7040}70417042$searchtype||='commit';7043if($searchtypeeq'pickaxe') {7044# pickaxe may take all resources of your box and run for several minutes7045# with every query - so decide by yourself how public you make this feature7046 gitweb_check_feature('pickaxe')7047or die_error(403,"Pickaxe is disabled");7048}7049if($searchtypeeq'grep') {7050 gitweb_check_feature('grep')7051or die_error(403,"Grep is disabled");7052}70537054 git_header_html();70557056if($searchtypeeq'commit'or$searchtypeeq'author'or$searchtypeeq'committer') {7057my$greptype;7058if($searchtypeeq'commit') {7059$greptype="--grep=";7060}elsif($searchtypeeq'author') {7061$greptype="--author=";7062}elsif($searchtypeeq'committer') {7063$greptype="--committer=";7064}7065$greptype.=$searchtext;7066my@commitlist= parse_commits($hash,101, (100*$page),undef,7067$greptype,'--regexp-ignore-case',7068$search_use_regexp?'--extended-regexp':'--fixed-strings');70697070my$paging_nav='';7071if($page>0) {7072$paging_nav.=7073$cgi->a({-href => href(action=>"search", hash=>$hash,7074 searchtext=>$searchtext,7075 searchtype=>$searchtype)},7076"first");7077$paging_nav.=" ⋅ ".7078$cgi->a({-href => href(-replay=>1, page=>$page-1),7079-accesskey =>"p", -title =>"Alt-p"},"prev");7080}else{7081$paging_nav.="first";7082$paging_nav.=" ⋅ prev";7083}7084my$next_link='';7085if($#commitlist>=100) {7086$next_link=7087$cgi->a({-href => href(-replay=>1, page=>$page+1),7088-accesskey =>"n", -title =>"Alt-n"},"next");7089$paging_nav.=" ⋅$next_link";7090}else{7091$paging_nav.=" ⋅ next";7092}70937094 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);7095 git_print_header_div('commit', esc_html($co{'title'}),$hash);7096if($page==0&& !@commitlist) {7097print"<p>No match.</p>\n";7098}else{7099 git_search_grep_body(\@commitlist,0,99,$next_link);7100}7101}71027103if($searchtypeeq'pickaxe') {7104 git_print_page_nav('','',$hash,$co{'tree'},$hash);7105 git_print_header_div('commit', esc_html($co{'title'}),$hash);71067107print"<table class=\"pickaxe search\">\n";7108my$alternate=1;7109local$/="\n";7110open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,7111'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",7112($search_use_regexp?'--pickaxe-regex': ());7113undef%co;7114my@files;7115while(my$line= <$fd>) {7116chomp$line;7117next unless$line;71187119my%set= parse_difftree_raw_line($line);7120if(defined$set{'commit'}) {7121# finish previous commit7122if(%co) {7123print"</td>\n".7124"<td class=\"link\">".7125$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .7126" | ".7127$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");7128print"</td>\n".7129"</tr>\n";7130}71317132if($alternate) {7133print"<tr class=\"dark\">\n";7134}else{7135print"<tr class=\"light\">\n";7136}7137$alternate^=1;7138%co= parse_commit($set{'commit'});7139my$author= chop_and_escape_str($co{'author_name'},15,5);7140print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".7141"<td><i>$author</i></td>\n".7142"<td>".7143$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),7144-class=>"list subject"},7145 chop_and_escape_str($co{'title'},50) ."<br/>");7146}elsif(defined$set{'to_id'}) {7147next if($set{'to_id'} =~m/^0{40}$/);71487149print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},7150 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),7151-class=>"list"},7152"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .7153"<br/>\n";7154}7155}7156close$fd;71577158# finish last commit (warning: repetition!)7159if(%co) {7160print"</td>\n".7161"<td class=\"link\">".7162$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .7163" | ".7164$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");7165print"</td>\n".7166"</tr>\n";7167}71687169print"</table>\n";7170}71717172if($searchtypeeq'grep') {7173 git_print_page_nav('','',$hash,$co{'tree'},$hash);7174 git_print_header_div('commit', esc_html($co{'title'}),$hash);71757176print"<table class=\"grep_search\">\n";7177my$alternate=1;7178my$matches=0;7179local$/="\n";7180open my$fd,"-|", git_cmd(),'grep','-n',7181$search_use_regexp? ('-E','-i') :'-F',7182$searchtext,$co{'tree'};7183my$lastfile='';7184while(my$line= <$fd>) {7185chomp$line;7186my($file,$lno,$ltext,$binary);7187last if($matches++>1000);7188if($line=~/^Binary file (.+) matches$/) {7189$file=$1;7190$binary=1;7191}else{7192(undef,$file,$lno,$ltext) =split(/:/,$line,4);7193}7194if($filene$lastfile) {7195$lastfileand print"</td></tr>\n";7196if($alternate++) {7197print"<tr class=\"dark\">\n";7198}else{7199print"<tr class=\"light\">\n";7200}7201print"<td class=\"list\">".7202$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},7203 file_name=>"$file"),7204-class=>"list"}, esc_path($file));7205print"</td><td>\n";7206$lastfile=$file;7207}7208if($binary) {7209print"<div class=\"binary\">Binary file</div>\n";7210}else{7211$ltext= untabify($ltext);7212if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {7213$ltext= esc_html($1, -nbsp=>1);7214$ltext.='<span class="match">';7215$ltext.= esc_html($2, -nbsp=>1);7216$ltext.='</span>';7217$ltext.= esc_html($3, -nbsp=>1);7218}else{7219$ltext= esc_html($ltext, -nbsp=>1);7220}7221print"<div class=\"pre\">".7222$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},7223 file_name=>"$file").'#l'.$lno,7224-class=>"linenr"},sprintf('%4i',$lno))7225.' '.$ltext."</div>\n";7226}7227}7228if($lastfile) {7229print"</td></tr>\n";7230if($matches>1000) {7231print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";7232}7233}else{7234print"<div class=\"diff nodifferences\">No matches found</div>\n";7235}7236close$fd;72377238print"</table>\n";7239}7240 git_footer_html();7241}72427243sub git_search_help {7244 git_header_html();7245 git_print_page_nav('','',$hash,$hash,$hash);7246print<<EOT;7247<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without7248regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,7249the pattern entered is recognized as the POSIX extended7250<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case7251insensitive).</p>7252<dl>7253<dt><b>commit</b></dt>7254<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>7255EOT7256my$have_grep= gitweb_check_feature('grep');7257if($have_grep) {7258print<<EOT;7259<dt><b>grep</b></dt>7260<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing7261 a different one) are searched for the given pattern. On large trees, this search can take7262a while and put some strain on the server, so please use it with some consideration. Note that7263due to git-grep peculiarity, currently if regexp mode is turned off, the matches are7264case-sensitive.</dd>7265EOT7266}7267print<<EOT;7268<dt><b>author</b></dt>7269<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>7270<dt><b>committer</b></dt>7271<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>7272EOT7273my$have_pickaxe= gitweb_check_feature('pickaxe');7274if($have_pickaxe) {7275print<<EOT;7276<dt><b>pickaxe</b></dt>7277<dd>All commits that caused the string to appear or disappear from any file (changes that7278added, removed or "modified" the string) will be listed. This search can take a while and7279takes a lot of strain on the server, so please use it wisely. Note that since you may be7280interested even in changes just changing the case as well, this search is case sensitive.</dd>7281EOT7282}7283print"</dl>\n";7284 git_footer_html();7285}72867287sub git_shortlog {7288 git_log_generic('shortlog', \&git_shortlog_body,7289$hash,$hash_parent);7290}72917292## ......................................................................7293## feeds (RSS, Atom; OPML)72947295sub git_feed {7296my$format=shift||'atom';7297my$have_blame= gitweb_check_feature('blame');72987299# Atom: http://www.atomenabled.org/developers/syndication/7300# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ7301if($formatne'rss'&&$formatne'atom') {7302 die_error(400,"Unknown web feed format");7303}73047305# log/feed of current (HEAD) branch, log of given branch, history of file/directory7306my$head=$hash||'HEAD';7307my@commitlist= parse_commits($head,150,0,$file_name);73087309my%latest_commit;7310my%latest_date;7311my$content_type="application/$format+xml";7312if(defined$cgi->http('HTTP_ACCEPT') &&7313$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {7314# browser (feed reader) prefers text/xml7315$content_type='text/xml';7316}7317if(defined($commitlist[0])) {7318%latest_commit= %{$commitlist[0]};7319my$latest_epoch=$latest_commit{'committer_epoch'};7320%latest_date= parse_date($latest_epoch,$latest_commit{'comitter_tz'});7321my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7322if(defined$if_modified) {7323my$since;7324if(eval{require HTTP::Date;1; }) {7325$since= HTTP::Date::str2time($if_modified);7326}elsif(eval{require Time::ParseDate;1; }) {7327$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7328}7329if(defined$since&&$latest_epoch<=$since) {7330print$cgi->header(7331-type =>$content_type,7332-charset =>'utf-8',7333-last_modified =>$latest_date{'rfc2822'},7334-status =>'304 Not Modified');7335return;7336}7337}7338print$cgi->header(7339-type =>$content_type,7340-charset =>'utf-8',7341-last_modified =>$latest_date{'rfc2822'});7342}else{7343print$cgi->header(7344-type =>$content_type,7345-charset =>'utf-8');7346}73477348# Optimization: skip generating the body if client asks only7349# for Last-Modified date.7350return if($cgi->request_method()eq'HEAD');73517352# header variables7353my$title="$site_name-$project/$action";7354my$feed_type='log';7355if(defined$hash) {7356$title.=" - '$hash'";7357$feed_type='branch log';7358if(defined$file_name) {7359$title.=" ::$file_name";7360$feed_type='history';7361}7362}elsif(defined$file_name) {7363$title.=" -$file_name";7364$feed_type='history';7365}7366$title.="$feed_type";7367my$descr= git_get_project_description($project);7368if(defined$descr) {7369$descr= esc_html($descr);7370}else{7371$descr="$project".7372($formateq'rss'?'RSS':'Atom') .7373" feed";7374}7375my$owner= git_get_project_owner($project);7376$owner= esc_html($owner);73777378#header7379my$alt_url;7380if(defined$file_name) {7381$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);7382}elsif(defined$hash) {7383$alt_url= href(-full=>1, action=>"log", hash=>$hash);7384}else{7385$alt_url= href(-full=>1, action=>"summary");7386}7387print qq!<?xml version="1.0" encoding="utf-8"?>\n!;7388if($formateq'rss') {7389print<<XML;7390<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">7391<channel>7392XML7393print"<title>$title</title>\n".7394"<link>$alt_url</link>\n".7395"<description>$descr</description>\n".7396"<language>en</language>\n".7397# project owner is responsible for 'editorial' content7398"<managingEditor>$owner</managingEditor>\n";7399if(defined$logo||defined$favicon) {7400# prefer the logo to the favicon, since RSS7401# doesn't allow both7402my$img= esc_url($logo||$favicon);7403print"<image>\n".7404"<url>$img</url>\n".7405"<title>$title</title>\n".7406"<link>$alt_url</link>\n".7407"</image>\n";7408}7409if(%latest_date) {7410print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";7411print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";7412}7413print"<generator>gitweb v.$version/$git_version</generator>\n";7414}elsif($formateq'atom') {7415print<<XML;7416<feed xmlns="http://www.w3.org/2005/Atom">7417XML7418print"<title>$title</title>\n".7419"<subtitle>$descr</subtitle>\n".7420'<link rel="alternate" type="text/html" href="'.7421$alt_url.'" />'."\n".7422'<link rel="self" type="'.$content_type.'" href="'.7423$cgi->self_url() .'" />'."\n".7424"<id>". href(-full=>1) ."</id>\n".7425# use project owner for feed author7426"<author><name>$owner</name></author>\n";7427if(defined$favicon) {7428print"<icon>". esc_url($favicon) ."</icon>\n";7429}7430if(defined$logo) {7431# not twice as wide as tall: 72 x 27 pixels7432print"<logo>". esc_url($logo) ."</logo>\n";7433}7434if(!%latest_date) {7435# dummy date to keep the feed valid until commits trickle in:7436print"<updated>1970-01-01T00:00:00Z</updated>\n";7437}else{7438print"<updated>$latest_date{'iso-8601'}</updated>\n";7439}7440print"<generator version='$version/$git_version'>gitweb</generator>\n";7441}74427443# contents7444for(my$i=0;$i<=$#commitlist;$i++) {7445my%co= %{$commitlist[$i]};7446my$commit=$co{'id'};7447# we read 150, we always show 30 and the ones more recent than 48 hours7448if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {7449last;7450}7451my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});74527453# get list of changed files7454open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7455$co{'parent'} ||"--root",7456$co{'id'},"--", (defined$file_name?$file_name: ())7457ornext;7458my@difftree=map{chomp;$_} <$fd>;7459close$fd7460ornext;74617462# print element (entry, item)7463my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);7464if($formateq'rss') {7465print"<item>\n".7466"<title>". esc_html($co{'title'}) ."</title>\n".7467"<author>". esc_html($co{'author'}) ."</author>\n".7468"<pubDate>$cd{'rfc2822'}</pubDate>\n".7469"<guid isPermaLink=\"true\">$co_url</guid>\n".7470"<link>$co_url</link>\n".7471"<description>". esc_html($co{'title'}) ."</description>\n".7472"<content:encoded>".7473"<![CDATA[\n";7474}elsif($formateq'atom') {7475print"<entry>\n".7476"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".7477"<updated>$cd{'iso-8601'}</updated>\n".7478"<author>\n".7479" <name>". esc_html($co{'author_name'}) ."</name>\n";7480if($co{'author_email'}) {7481print" <email>". esc_html($co{'author_email'}) ."</email>\n";7482}7483print"</author>\n".7484# use committer for contributor7485"<contributor>\n".7486" <name>". esc_html($co{'committer_name'}) ."</name>\n";7487if($co{'committer_email'}) {7488print" <email>". esc_html($co{'committer_email'}) ."</email>\n";7489}7490print"</contributor>\n".7491"<published>$cd{'iso-8601'}</published>\n".7492"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".7493"<id>$co_url</id>\n".7494"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".7495"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";7496}7497my$comment=$co{'comment'};7498print"<pre>\n";7499foreachmy$line(@$comment) {7500$line= esc_html($line);7501print"$line\n";7502}7503print"</pre><ul>\n";7504foreachmy$difftree_line(@difftree) {7505my%difftree= parse_difftree_raw_line($difftree_line);7506next if!$difftree{'from_id'};75077508my$file=$difftree{'file'} ||$difftree{'to_file'};75097510print"<li>".7511"[".7512$cgi->a({-href => href(-full=>1, action=>"blobdiff",7513 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},7514 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},7515 file_name=>$file, file_parent=>$difftree{'from_file'}),7516-title =>"diff"},'D');7517if($have_blame) {7518print$cgi->a({-href => href(-full=>1, action=>"blame",7519 file_name=>$file, hash_base=>$commit),7520-title =>"blame"},'B');7521}7522# if this is not a feed of a file history7523if(!defined$file_name||$file_namene$file) {7524print$cgi->a({-href => href(-full=>1, action=>"history",7525 file_name=>$file, hash=>$commit),7526-title =>"history"},'H');7527}7528$file= esc_path($file);7529print"] ".7530"$file</li>\n";7531}7532if($formateq'rss') {7533print"</ul>]]>\n".7534"</content:encoded>\n".7535"</item>\n";7536}elsif($formateq'atom') {7537print"</ul>\n</div>\n".7538"</content>\n".7539"</entry>\n";7540}7541}75427543# end of feed7544if($formateq'rss') {7545print"</channel>\n</rss>\n";7546}elsif($formateq'atom') {7547print"</feed>\n";7548}7549}75507551sub git_rss {7552 git_feed('rss');7553}75547555sub git_atom {7556 git_feed('atom');7557}75587559sub git_opml {7560my@list= git_get_projects_list();7561if(!@list) {7562 die_error(404,"No projects found");7563}75647565print$cgi->header(7566-type =>'text/xml',7567-charset =>'utf-8',7568-content_disposition =>'inline; filename="opml.xml"');75697570print<<XML;7571<?xml version="1.0" encoding="utf-8"?>7572<opml version="1.0">7573<head>7574 <title>$site_nameOPML Export</title>7575</head>7576<body>7577<outline text="git RSS feeds">7578XML75797580foreachmy$pr(@list) {7581my%proj=%$pr;7582my$head= git_get_head_hash($proj{'path'});7583if(!defined$head) {7584next;7585}7586$git_dir="$projectroot/$proj{'path'}";7587my%co= parse_commit($head);7588if(!%co) {7589next;7590}75917592my$path= esc_html(chop_str($proj{'path'},25,5));7593my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);7594my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);7595print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";7596}7597print<<XML;7598</outline>7599</body>7600</opml>7601XML7602}