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# default order of projects list 119# valid values are none, project, descr, owner, and age 120our$default_projects_order="project"; 121 122# show repository only if this file exists 123# (only effective if this variable evaluates to true) 124our$export_ok="++GITWEB_EXPORT_OK++"; 125 126# show repository only if this subroutine returns true 127# when given the path to the project, for example: 128# sub { return -e "$_[0]/git-daemon-export-ok"; } 129our$export_auth_hook=undef; 130 131# only allow viewing of repositories also shown on the overview page 132our$strict_export="++GITWEB_STRICT_EXPORT++"; 133 134# list of git base URLs used for URL to where fetch project from, 135# i.e. full URL is "$git_base_url/$project" 136our@git_base_url_list=grep{$_ne''} ("++GITWEB_BASE_URL++"); 137 138# default blob_plain mimetype and default charset for text/plain blob 139our$default_blob_plain_mimetype='text/plain'; 140our$default_text_plain_charset=undef; 141 142# file to use for guessing MIME types before trying /etc/mime.types 143# (relative to the current git repository) 144our$mimetypes_file=undef; 145 146# assume this charset if line contains non-UTF-8 characters; 147# it should be valid encoding (see Encoding::Supported(3pm) for list), 148# for which encoding all byte sequences are valid, for example 149# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it 150# could be even 'utf-8' for the old behavior) 151our$fallback_encoding='latin1'; 152 153# rename detection options for git-diff and git-diff-tree 154# - default is '-M', with the cost proportional to 155# (number of removed files) * (number of new files). 156# - more costly is '-C' (which implies '-M'), with the cost proportional to 157# (number of changed files + number of removed files) * (number of new files) 158# - even more costly is '-C', '--find-copies-harder' with cost 159# (number of files in the original tree) * (number of new files) 160# - one might want to include '-B' option, e.g. '-B', '-M' 161our@diff_opts= ('-M');# taken from git_commit 162 163# Disables features that would allow repository owners to inject script into 164# the gitweb domain. 165our$prevent_xss=0; 166 167# Path to the highlight executable to use (must be the one from 168# http://www.andre-simon.de due to assumptions about parameters and output). 169# Useful if highlight is not installed on your webserver's PATH. 170# [Default: highlight] 171our$highlight_bin="++HIGHLIGHT_BIN++"; 172 173# information about snapshot formats that gitweb is capable of serving 174our%known_snapshot_formats= ( 175# name => { 176# 'display' => display name, 177# 'type' => mime type, 178# 'suffix' => filename suffix, 179# 'format' => --format for git-archive, 180# 'compressor' => [compressor command and arguments] 181# (array reference, optional) 182# 'disabled' => boolean (optional)} 183# 184'tgz'=> { 185'display'=>'tar.gz', 186'type'=>'application/x-gzip', 187'suffix'=>'.tar.gz', 188'format'=>'tar', 189'compressor'=> ['gzip','-n']}, 190 191'tbz2'=> { 192'display'=>'tar.bz2', 193'type'=>'application/x-bzip2', 194'suffix'=>'.tar.bz2', 195'format'=>'tar', 196'compressor'=> ['bzip2']}, 197 198'txz'=> { 199'display'=>'tar.xz', 200'type'=>'application/x-xz', 201'suffix'=>'.tar.xz', 202'format'=>'tar', 203'compressor'=> ['xz'], 204'disabled'=>1}, 205 206'zip'=> { 207'display'=>'zip', 208'type'=>'application/x-zip', 209'suffix'=>'.zip', 210'format'=>'zip'}, 211); 212 213# Aliases so we understand old gitweb.snapshot values in repository 214# configuration. 215our%known_snapshot_format_aliases= ( 216'gzip'=>'tgz', 217'bzip2'=>'tbz2', 218'xz'=>'txz', 219 220# backward compatibility: legacy gitweb config support 221'x-gzip'=>undef,'gz'=>undef, 222'x-bzip2'=>undef,'bz2'=>undef, 223'x-zip'=>undef,''=>undef, 224); 225 226# Pixel sizes for icons and avatars. If the default font sizes or lineheights 227# are changed, it may be appropriate to change these values too via 228# $GITWEB_CONFIG. 229our%avatar_size= ( 230'default'=>16, 231'double'=>32 232); 233 234# Used to set the maximum load that we will still respond to gitweb queries. 235# If server load exceed this value then return "503 server busy" error. 236# If gitweb cannot determined server load, it is taken to be 0. 237# Leave it undefined (or set to 'undef') to turn off load checking. 238our$maxload=300; 239 240# configuration for 'highlight' (http://www.andre-simon.de/) 241# match by basename 242our%highlight_basename= ( 243#'Program' => 'py', 244#'Library' => 'py', 245'SConstruct'=>'py',# SCons equivalent of Makefile 246'Makefile'=>'make', 247); 248# match by extension 249our%highlight_ext= ( 250# main extensions, defining name of syntax; 251# see files in /usr/share/highlight/langDefs/ directory 252map{$_=>$_} 253qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl sql make), 254# alternate extensions, see /etc/highlight/filetypes.conf 255'h'=>'c', 256map{$_=>'sh'}qw(bash zsh ksh), 257map{$_=>'cpp'}qw(cxx c++ cc), 258map{$_=>'php'}qw(php3 php4 php5 phps), 259map{$_=>'pl'}qw(perl pm),# perhaps also 'cgi' 260map{$_=>'make'}qw(mak mk), 261map{$_=>'xml'}qw(xhtml html htm), 262); 263 264# You define site-wide feature defaults here; override them with 265# $GITWEB_CONFIG as necessary. 266our%feature= ( 267# feature => { 268# 'sub' => feature-sub (subroutine), 269# 'override' => allow-override (boolean), 270# 'default' => [ default options...] (array reference)} 271# 272# if feature is overridable (it means that allow-override has true value), 273# then feature-sub will be called with default options as parameters; 274# return value of feature-sub indicates if to enable specified feature 275# 276# if there is no 'sub' key (no feature-sub), then feature cannot be 277# overridden 278# 279# use gitweb_get_feature(<feature>) to retrieve the <feature> value 280# (an array) or gitweb_check_feature(<feature>) to check if <feature> 281# is enabled 282 283# Enable the 'blame' blob view, showing the last commit that modified 284# each line in the file. This can be very CPU-intensive. 285 286# To enable system wide have in $GITWEB_CONFIG 287# $feature{'blame'}{'default'} = [1]; 288# To have project specific config enable override in $GITWEB_CONFIG 289# $feature{'blame'}{'override'} = 1; 290# and in project config gitweb.blame = 0|1; 291'blame'=> { 292'sub'=>sub{ feature_bool('blame',@_) }, 293'override'=>0, 294'default'=> [0]}, 295 296# Enable the 'snapshot' link, providing a compressed archive of any 297# tree. This can potentially generate high traffic if you have large 298# project. 299 300# Value is a list of formats defined in %known_snapshot_formats that 301# you wish to offer. 302# To disable system wide have in $GITWEB_CONFIG 303# $feature{'snapshot'}{'default'} = []; 304# To have project specific config enable override in $GITWEB_CONFIG 305# $feature{'snapshot'}{'override'} = 1; 306# and in project config, a comma-separated list of formats or "none" 307# to disable. Example: gitweb.snapshot = tbz2,zip; 308'snapshot'=> { 309'sub'=> \&feature_snapshot, 310'override'=>0, 311'default'=> ['tgz']}, 312 313# Enable text search, which will list the commits which match author, 314# committer or commit text to a given string. Enabled by default. 315# Project specific override is not supported. 316'search'=> { 317'override'=>0, 318'default'=> [1]}, 319 320# Enable grep search, which will list the files in currently selected 321# tree containing the given string. Enabled by default. This can be 322# potentially CPU-intensive, of course. 323 324# To enable system wide have in $GITWEB_CONFIG 325# $feature{'grep'}{'default'} = [1]; 326# To have project specific config enable override in $GITWEB_CONFIG 327# $feature{'grep'}{'override'} = 1; 328# and in project config gitweb.grep = 0|1; 329'grep'=> { 330'sub'=>sub{ feature_bool('grep',@_) }, 331'override'=>0, 332'default'=> [1]}, 333 334# Enable the pickaxe search, which will list the commits that modified 335# a given string in a file. This can be practical and quite faster 336# alternative to 'blame', but still potentially CPU-intensive. 337 338# To enable system wide have in $GITWEB_CONFIG 339# $feature{'pickaxe'}{'default'} = [1]; 340# To have project specific config enable override in $GITWEB_CONFIG 341# $feature{'pickaxe'}{'override'} = 1; 342# and in project config gitweb.pickaxe = 0|1; 343'pickaxe'=> { 344'sub'=>sub{ feature_bool('pickaxe',@_) }, 345'override'=>0, 346'default'=> [1]}, 347 348# Enable showing size of blobs in a 'tree' view, in a separate 349# column, similar to what 'ls -l' does. This cost a bit of IO. 350 351# To disable system wide have in $GITWEB_CONFIG 352# $feature{'show-sizes'}{'default'} = [0]; 353# To have project specific config enable override in $GITWEB_CONFIG 354# $feature{'show-sizes'}{'override'} = 1; 355# and in project config gitweb.showsizes = 0|1; 356'show-sizes'=> { 357'sub'=>sub{ feature_bool('showsizes',@_) }, 358'override'=>0, 359'default'=> [1]}, 360 361# Make gitweb use an alternative format of the URLs which can be 362# more readable and natural-looking: project name is embedded 363# directly in the path and the query string contains other 364# auxiliary information. All gitweb installations recognize 365# URL in either format; this configures in which formats gitweb 366# generates links. 367 368# To enable system wide have in $GITWEB_CONFIG 369# $feature{'pathinfo'}{'default'} = [1]; 370# Project specific override is not supported. 371 372# Note that you will need to change the default location of CSS, 373# favicon, logo and possibly other files to an absolute URL. Also, 374# if gitweb.cgi serves as your indexfile, you will need to force 375# $my_uri to contain the script name in your $GITWEB_CONFIG. 376'pathinfo'=> { 377'override'=>0, 378'default'=> [0]}, 379 380# Make gitweb consider projects in project root subdirectories 381# to be forks of existing projects. Given project $projname.git, 382# projects matching $projname/*.git will not be shown in the main 383# projects list, instead a '+' mark will be added to $projname 384# there and a 'forks' view will be enabled for the project, listing 385# all the forks. If project list is taken from a file, forks have 386# to be listed after the main project. 387 388# To enable system wide have in $GITWEB_CONFIG 389# $feature{'forks'}{'default'} = [1]; 390# Project specific override is not supported. 391'forks'=> { 392'override'=>0, 393'default'=> [0]}, 394 395# Insert custom links to the action bar of all project pages. 396# This enables you mainly to link to third-party scripts integrating 397# into gitweb; e.g. git-browser for graphical history representation 398# or custom web-based repository administration interface. 399 400# The 'default' value consists of a list of triplets in the form 401# (label, link, position) where position is the label after which 402# to insert the link and link is a format string where %n expands 403# to the project name, %f to the project path within the filesystem, 404# %h to the current hash (h gitweb parameter) and %b to the current 405# hash base (hb gitweb parameter); %% expands to %. 406 407# To enable system wide have in $GITWEB_CONFIG e.g. 408# $feature{'actions'}{'default'} = [('graphiclog', 409# '/git-browser/by-commit.html?r=%n', 'summary')]; 410# Project specific override is not supported. 411'actions'=> { 412'override'=>0, 413'default'=> []}, 414 415# Allow gitweb scan project content tags of project repository, 416# and display the popular Web 2.0-ish "tag cloud" near the projects 417# list. Note that this is something COMPLETELY different from the 418# normal Git tags. 419 420# gitweb by itself can show existing tags, but it does not handle 421# tagging itself; you need to do it externally, outside gitweb. 422# The format is described in git_get_project_ctags() subroutine. 423# You may want to install the HTML::TagCloud Perl module to get 424# a pretty tag cloud instead of just a list of tags. 425 426# To enable system wide have in $GITWEB_CONFIG 427# $feature{'ctags'}{'default'} = [1]; 428# Project specific override is not supported. 429 430# In the future whether ctags editing is enabled might depend 431# on the value, but using 1 should always mean no editing of ctags. 432'ctags'=> { 433'override'=>0, 434'default'=> [0]}, 435 436# The maximum number of patches in a patchset generated in patch 437# view. Set this to 0 or undef to disable patch view, or to a 438# negative number to remove any limit. 439 440# To disable system wide have in $GITWEB_CONFIG 441# $feature{'patches'}{'default'} = [0]; 442# To have project specific config enable override in $GITWEB_CONFIG 443# $feature{'patches'}{'override'} = 1; 444# and in project config gitweb.patches = 0|n; 445# where n is the maximum number of patches allowed in a patchset. 446'patches'=> { 447'sub'=> \&feature_patches, 448'override'=>0, 449'default'=> [16]}, 450 451# Avatar support. When this feature is enabled, views such as 452# shortlog or commit will display an avatar associated with 453# the email of the committer(s) and/or author(s). 454 455# Currently available providers are gravatar and picon. 456# If an unknown provider is specified, the feature is disabled. 457 458# Gravatar depends on Digest::MD5. 459# Picon currently relies on the indiana.edu database. 460 461# To enable system wide have in $GITWEB_CONFIG 462# $feature{'avatar'}{'default'} = ['<provider>']; 463# where <provider> is either gravatar or picon. 464# To have project specific config enable override in $GITWEB_CONFIG 465# $feature{'avatar'}{'override'} = 1; 466# and in project config gitweb.avatar = <provider>; 467'avatar'=> { 468'sub'=> \&feature_avatar, 469'override'=>0, 470'default'=> ['']}, 471 472# Enable displaying how much time and how many git commands 473# it took to generate and display page. Disabled by default. 474# Project specific override is not supported. 475'timed'=> { 476'override'=>0, 477'default'=> [0]}, 478 479# Enable turning some links into links to actions which require 480# JavaScript to run (like 'blame_incremental'). Not enabled by 481# default. Project specific override is currently not supported. 482'javascript-actions'=> { 483'override'=>0, 484'default'=> [0]}, 485 486# Syntax highlighting support. This is based on Daniel Svensson's 487# and Sham Chukoury's work in gitweb-xmms2.git. 488# It requires the 'highlight' program present in $PATH, 489# and therefore is disabled by default. 490 491# To enable system wide have in $GITWEB_CONFIG 492# $feature{'highlight'}{'default'} = [1]; 493 494'highlight'=> { 495'sub'=>sub{ feature_bool('highlight',@_) }, 496'override'=>0, 497'default'=> [0]}, 498 499# Enable displaying of remote heads in the heads list 500 501# To enable system wide have in $GITWEB_CONFIG 502# $feature{'remote_heads'}{'default'} = [1]; 503# To have project specific config enable override in $GITWEB_CONFIG 504# $feature{'remote_heads'}{'override'} = 1; 505# and in project config gitweb.remote_heads = 0|1; 506'remote_heads'=> { 507'sub'=>sub{ feature_bool('remote_heads',@_) }, 508'override'=>0, 509'default'=> [0]}, 510); 511 512sub gitweb_get_feature { 513my($name) =@_; 514return unlessexists$feature{$name}; 515my($sub,$override,@defaults) = ( 516$feature{$name}{'sub'}, 517$feature{$name}{'override'}, 518@{$feature{$name}{'default'}}); 519# project specific override is possible only if we have project 520our$git_dir;# global variable, declared later 521if(!$override|| !defined$git_dir) { 522return@defaults; 523} 524if(!defined$sub) { 525warn"feature$nameis not overridable"; 526return@defaults; 527} 528return$sub->(@defaults); 529} 530 531# A wrapper to check if a given feature is enabled. 532# With this, you can say 533# 534# my $bool_feat = gitweb_check_feature('bool_feat'); 535# gitweb_check_feature('bool_feat') or somecode; 536# 537# instead of 538# 539# my ($bool_feat) = gitweb_get_feature('bool_feat'); 540# (gitweb_get_feature('bool_feat'))[0] or somecode; 541# 542sub gitweb_check_feature { 543return(gitweb_get_feature(@_))[0]; 544} 545 546 547sub feature_bool { 548my$key=shift; 549my($val) = git_get_project_config($key,'--bool'); 550 551if(!defined$val) { 552return($_[0]); 553}elsif($valeq'true') { 554return(1); 555}elsif($valeq'false') { 556return(0); 557} 558} 559 560sub feature_snapshot { 561my(@fmts) =@_; 562 563my($val) = git_get_project_config('snapshot'); 564 565if($val) { 566@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 567} 568 569return@fmts; 570} 571 572sub feature_patches { 573my@val= (git_get_project_config('patches','--int')); 574 575if(@val) { 576return@val; 577} 578 579return($_[0]); 580} 581 582sub feature_avatar { 583my@val= (git_get_project_config('avatar')); 584 585return@val?@val:@_; 586} 587 588# checking HEAD file with -e is fragile if the repository was 589# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 590# and then pruned. 591sub check_head_link { 592my($dir) =@_; 593my$headfile="$dir/HEAD"; 594return((-e $headfile) || 595(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 596} 597 598sub check_export_ok { 599my($dir) =@_; 600return(check_head_link($dir) && 601(!$export_ok|| -e "$dir/$export_ok") && 602(!$export_auth_hook||$export_auth_hook->($dir))); 603} 604 605# process alternate names for backward compatibility 606# filter out unsupported (unknown) snapshot formats 607sub filter_snapshot_fmts { 608my@fmts=@_; 609 610@fmts=map{ 611exists$known_snapshot_format_aliases{$_} ? 612$known_snapshot_format_aliases{$_} :$_}@fmts; 613@fmts=grep{ 614exists$known_snapshot_formats{$_} && 615!$known_snapshot_formats{$_}{'disabled'}}@fmts; 616} 617 618# If it is set to code reference, it is code that it is to be run once per 619# request, allowing updating configurations that change with each request, 620# while running other code in config file only once. 621# 622# Otherwise, if it is false then gitweb would process config file only once; 623# if it is true then gitweb config would be run for each request. 624our$per_request_config=1; 625 626# read and parse gitweb config file given by its parameter. 627# returns true on success, false on recoverable error, allowing 628# to chain this subroutine, using first file that exists. 629# dies on errors during parsing config file, as it is unrecoverable. 630sub read_config_file { 631my$filename=shift; 632return unlessdefined$filename; 633# die if there are errors parsing config file 634if(-e $filename) { 635do$filename; 636die$@if$@; 637return1; 638} 639return; 640} 641 642our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM); 643sub evaluate_gitweb_config { 644our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 645our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 646 647# use first config file that exists 648 read_config_file($GITWEB_CONFIG)or 649 read_config_file($GITWEB_CONFIG_SYSTEM); 650} 651 652# Get loadavg of system, to compare against $maxload. 653# Currently it requires '/proc/loadavg' present to get loadavg; 654# if it is not present it returns 0, which means no load checking. 655sub get_loadavg { 656if( -e '/proc/loadavg'){ 657open my$fd,'<','/proc/loadavg' 658orreturn0; 659my@load=split(/\s+/,scalar<$fd>); 660close$fd; 661 662# The first three columns measure CPU and IO utilization of the last one, 663# five, and 10 minute periods. The fourth column shows the number of 664# currently running processes and the total number of processes in the m/n 665# format. The last column displays the last process ID used. 666return$load[0] ||0; 667} 668# additional checks for load average should go here for things that don't export 669# /proc/loadavg 670 671return0; 672} 673 674# version of the core git binary 675our$git_version; 676sub evaluate_git_version { 677our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 678$number_of_git_cmds++; 679} 680 681sub check_loadavg { 682if(defined$maxload&& get_loadavg() >$maxload) { 683 die_error(503,"The load average on the server is too high"); 684} 685} 686 687# ====================================================================== 688# input validation and dispatch 689 690# input parameters can be collected from a variety of sources (presently, CGI 691# and PATH_INFO), so we define an %input_params hash that collects them all 692# together during validation: this allows subsequent uses (e.g. href()) to be 693# agnostic of the parameter origin 694 695our%input_params= (); 696 697# input parameters are stored with the long parameter name as key. This will 698# also be used in the href subroutine to convert parameters to their CGI 699# equivalent, and since the href() usage is the most frequent one, we store 700# the name -> CGI key mapping here, instead of the reverse. 701# 702# XXX: Warning: If you touch this, check the search form for updating, 703# too. 704 705our@cgi_param_mapping= ( 706 project =>"p", 707 action =>"a", 708 file_name =>"f", 709 file_parent =>"fp", 710 hash =>"h", 711 hash_parent =>"hp", 712 hash_base =>"hb", 713 hash_parent_base =>"hpb", 714 page =>"pg", 715 order =>"o", 716 searchtext =>"s", 717 searchtype =>"st", 718 snapshot_format =>"sf", 719 extra_options =>"opt", 720 search_use_regexp =>"sr", 721 ctag =>"by_tag", 722# this must be last entry (for manipulation from JavaScript) 723 javascript =>"js" 724); 725our%cgi_param_mapping=@cgi_param_mapping; 726 727# we will also need to know the possible actions, for validation 728our%actions= ( 729"blame"=> \&git_blame, 730"blame_incremental"=> \&git_blame_incremental, 731"blame_data"=> \&git_blame_data, 732"blobdiff"=> \&git_blobdiff, 733"blobdiff_plain"=> \&git_blobdiff_plain, 734"blob"=> \&git_blob, 735"blob_plain"=> \&git_blob_plain, 736"commitdiff"=> \&git_commitdiff, 737"commitdiff_plain"=> \&git_commitdiff_plain, 738"commit"=> \&git_commit, 739"forks"=> \&git_forks, 740"heads"=> \&git_heads, 741"history"=> \&git_history, 742"log"=> \&git_log, 743"patch"=> \&git_patch, 744"patches"=> \&git_patches, 745"remotes"=> \&git_remotes, 746"rss"=> \&git_rss, 747"atom"=> \&git_atom, 748"search"=> \&git_search, 749"search_help"=> \&git_search_help, 750"shortlog"=> \&git_shortlog, 751"summary"=> \&git_summary, 752"tag"=> \&git_tag, 753"tags"=> \&git_tags, 754"tree"=> \&git_tree, 755"snapshot"=> \&git_snapshot, 756"object"=> \&git_object, 757# those below don't need $project 758"opml"=> \&git_opml, 759"project_list"=> \&git_project_list, 760"project_index"=> \&git_project_index, 761); 762 763# finally, we have the hash of allowed extra_options for the commands that 764# allow them 765our%allowed_options= ( 766"--no-merges"=> [qw(rss atom log shortlog history)], 767); 768 769# fill %input_params with the CGI parameters. All values except for 'opt' 770# should be single values, but opt can be an array. We should probably 771# build an array of parameters that can be multi-valued, but since for the time 772# being it's only this one, we just single it out 773sub evaluate_query_params { 774our$cgi; 775 776while(my($name,$symbol) =each%cgi_param_mapping) { 777if($symboleq'opt') { 778$input_params{$name} = [$cgi->param($symbol) ]; 779}else{ 780$input_params{$name} =$cgi->param($symbol); 781} 782} 783} 784 785# now read PATH_INFO and update the parameter list for missing parameters 786sub evaluate_path_info { 787return ifdefined$input_params{'project'}; 788return if!$path_info; 789$path_info=~ s,^/+,,; 790return if!$path_info; 791 792# find which part of PATH_INFO is project 793my$project=$path_info; 794$project=~ s,/+$,,; 795while($project&& !check_head_link("$projectroot/$project")) { 796$project=~ s,/*[^/]*$,,; 797} 798return unless$project; 799$input_params{'project'} =$project; 800 801# do not change any parameters if an action is given using the query string 802return if$input_params{'action'}; 803$path_info=~ s,^\Q$project\E/*,,; 804 805# next, check if we have an action 806my$action=$path_info; 807$action=~ s,/.*$,,; 808if(exists$actions{$action}) { 809$path_info=~ s,^$action/*,,; 810$input_params{'action'} =$action; 811} 812 813# list of actions that want hash_base instead of hash, but can have no 814# pathname (f) parameter 815my@wants_base= ( 816'tree', 817'history', 818); 819 820# we want to catch, among others 821# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 822my($parentrefname,$parentpathname,$refname,$pathname) = 823($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/); 824 825# first, analyze the 'current' part 826if(defined$pathname) { 827# we got "branch:filename" or "branch:dir/" 828# we could use git_get_type(branch:pathname), but: 829# - it needs $git_dir 830# - it does a git() call 831# - the convention of terminating directories with a slash 832# makes it superfluous 833# - embedding the action in the PATH_INFO would make it even 834# more superfluous 835$pathname=~ s,^/+,,; 836if(!$pathname||substr($pathname, -1)eq"/") { 837$input_params{'action'} ||="tree"; 838$pathname=~ s,/$,,; 839}else{ 840# the default action depends on whether we had parent info 841# or not 842if($parentrefname) { 843$input_params{'action'} ||="blobdiff_plain"; 844}else{ 845$input_params{'action'} ||="blob_plain"; 846} 847} 848$input_params{'hash_base'} ||=$refname; 849$input_params{'file_name'} ||=$pathname; 850}elsif(defined$refname) { 851# we got "branch". In this case we have to choose if we have to 852# set hash or hash_base. 853# 854# Most of the actions without a pathname only want hash to be 855# set, except for the ones specified in @wants_base that want 856# hash_base instead. It should also be noted that hand-crafted 857# links having 'history' as an action and no pathname or hash 858# set will fail, but that happens regardless of PATH_INFO. 859if(defined$parentrefname) { 860# if there is parent let the default be 'shortlog' action 861# (for http://git.example.com/repo.git/A..B links); if there 862# is no parent, dispatch will detect type of object and set 863# action appropriately if required (if action is not set) 864$input_params{'action'} ||="shortlog"; 865} 866if($input_params{'action'} && 867grep{$_eq$input_params{'action'} }@wants_base) { 868$input_params{'hash_base'} ||=$refname; 869}else{ 870$input_params{'hash'} ||=$refname; 871} 872} 873 874# next, handle the 'parent' part, if present 875if(defined$parentrefname) { 876# a missing pathspec defaults to the 'current' filename, allowing e.g. 877# someproject/blobdiff/oldrev..newrev:/filename 878if($parentpathname) { 879$parentpathname=~ s,^/+,,; 880$parentpathname=~ s,/$,,; 881$input_params{'file_parent'} ||=$parentpathname; 882}else{ 883$input_params{'file_parent'} ||=$input_params{'file_name'}; 884} 885# we assume that hash_parent_base is wanted if a path was specified, 886# or if the action wants hash_base instead of hash 887if(defined$input_params{'file_parent'} || 888grep{$_eq$input_params{'action'} }@wants_base) { 889$input_params{'hash_parent_base'} ||=$parentrefname; 890}else{ 891$input_params{'hash_parent'} ||=$parentrefname; 892} 893} 894 895# for the snapshot action, we allow URLs in the form 896# $project/snapshot/$hash.ext 897# where .ext determines the snapshot and gets removed from the 898# passed $refname to provide the $hash. 899# 900# To be able to tell that $refname includes the format extension, we 901# require the following two conditions to be satisfied: 902# - the hash input parameter MUST have been set from the $refname part 903# of the URL (i.e. they must be equal) 904# - the snapshot format MUST NOT have been defined already (e.g. from 905# CGI parameter sf) 906# It's also useless to try any matching unless $refname has a dot, 907# so we check for that too 908if(defined$input_params{'action'} && 909$input_params{'action'}eq'snapshot'&& 910defined$refname&&index($refname,'.') != -1&& 911$refnameeq$input_params{'hash'} && 912!defined$input_params{'snapshot_format'}) { 913# We loop over the known snapshot formats, checking for 914# extensions. Allowed extensions are both the defined suffix 915# (which includes the initial dot already) and the snapshot 916# format key itself, with a prepended dot 917while(my($fmt,$opt) =each%known_snapshot_formats) { 918my$hash=$refname; 919unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 920next; 921} 922my$sfx=$1; 923# a valid suffix was found, so set the snapshot format 924# and reset the hash parameter 925$input_params{'snapshot_format'} =$fmt; 926$input_params{'hash'} =$hash; 927# we also set the format suffix to the one requested 928# in the URL: this way a request for e.g. .tgz returns 929# a .tgz instead of a .tar.gz 930$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 931last; 932} 933} 934} 935 936our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 937$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 938$searchtext,$search_regexp); 939sub evaluate_and_validate_params { 940our$action=$input_params{'action'}; 941if(defined$action) { 942if(!validate_action($action)) { 943 die_error(400,"Invalid action parameter"); 944} 945} 946 947# parameters which are pathnames 948our$project=$input_params{'project'}; 949if(defined$project) { 950if(!validate_project($project)) { 951undef$project; 952 die_error(404,"No such project"); 953} 954} 955 956our$file_name=$input_params{'file_name'}; 957if(defined$file_name) { 958if(!validate_pathname($file_name)) { 959 die_error(400,"Invalid file parameter"); 960} 961} 962 963our$file_parent=$input_params{'file_parent'}; 964if(defined$file_parent) { 965if(!validate_pathname($file_parent)) { 966 die_error(400,"Invalid file parent parameter"); 967} 968} 969 970# parameters which are refnames 971our$hash=$input_params{'hash'}; 972if(defined$hash) { 973if(!validate_refname($hash)) { 974 die_error(400,"Invalid hash parameter"); 975} 976} 977 978our$hash_parent=$input_params{'hash_parent'}; 979if(defined$hash_parent) { 980if(!validate_refname($hash_parent)) { 981 die_error(400,"Invalid hash parent parameter"); 982} 983} 984 985our$hash_base=$input_params{'hash_base'}; 986if(defined$hash_base) { 987if(!validate_refname($hash_base)) { 988 die_error(400,"Invalid hash base parameter"); 989} 990} 991 992our@extra_options= @{$input_params{'extra_options'}}; 993# @extra_options is always defined, since it can only be (currently) set from 994# CGI, and $cgi->param() returns the empty array in array context if the param 995# is not set 996foreachmy$opt(@extra_options) { 997if(not exists$allowed_options{$opt}) { 998 die_error(400,"Invalid option parameter"); 999}1000if(not grep(/^$action$/, @{$allowed_options{$opt}})) {1001 die_error(400,"Invalid option parameter for this action");1002}1003}10041005our$hash_parent_base=$input_params{'hash_parent_base'};1006if(defined$hash_parent_base) {1007if(!validate_refname($hash_parent_base)) {1008 die_error(400,"Invalid hash parent base parameter");1009}1010}10111012# other parameters1013our$page=$input_params{'page'};1014if(defined$page) {1015if($page=~m/[^0-9]/) {1016 die_error(400,"Invalid page parameter");1017}1018}10191020our$searchtype=$input_params{'searchtype'};1021if(defined$searchtype) {1022if($searchtype=~m/[^a-z]/) {1023 die_error(400,"Invalid searchtype parameter");1024}1025}10261027our$search_use_regexp=$input_params{'search_use_regexp'};10281029our$searchtext=$input_params{'searchtext'};1030our$search_regexp;1031if(defined$searchtext) {1032if(length($searchtext) <2) {1033 die_error(403,"At least two characters are required for search parameter");1034}1035$search_regexp=$search_use_regexp?$searchtext:quotemeta$searchtext;1036}1037}10381039# path to the current git repository1040our$git_dir;1041sub evaluate_git_dir {1042our$git_dir="$projectroot/$project"if$project;1043}10441045our(@snapshot_fmts,$git_avatar);1046sub configure_gitweb_features {1047# list of supported snapshot formats1048our@snapshot_fmts= gitweb_get_feature('snapshot');1049@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);10501051# check that the avatar feature is set to a known provider name,1052# and for each provider check if the dependencies are satisfied.1053# if the provider name is invalid or the dependencies are not met,1054# reset $git_avatar to the empty string.1055our($git_avatar) = gitweb_get_feature('avatar');1056if($git_avatareq'gravatar') {1057$git_avatar=''unless(eval{require Digest::MD5;1; });1058}elsif($git_avatareq'picon') {1059# no dependencies1060}else{1061$git_avatar='';1062}1063}10641065# custom error handler: 'die <message>' is Internal Server Error1066sub handle_errors_html {1067my$msg=shift;# it is already HTML escaped10681069# to avoid infinite loop where error occurs in die_error,1070# change handler to default handler, disabling handle_errors_html1071 set_message("Error occured when inside die_error:\n$msg");10721073# you cannot jump out of die_error when called as error handler;1074# the subroutine set via CGI::Carp::set_message is called _after_1075# HTTP headers are already written, so it cannot write them itself1076 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1077}1078set_message(\&handle_errors_html);10791080# dispatch1081sub dispatch {1082if(!defined$action) {1083if(defined$hash) {1084$action= git_get_type($hash);1085}elsif(defined$hash_base&&defined$file_name) {1086$action= git_get_type("$hash_base:$file_name");1087}elsif(defined$project) {1088$action='summary';1089}else{1090$action='project_list';1091}1092}1093if(!defined($actions{$action})) {1094 die_error(400,"Unknown action");1095}1096if($action!~m/^(?:opml|project_list|project_index)$/&&1097!$project) {1098 die_error(400,"Project needed");1099}1100$actions{$action}->();1101}11021103sub reset_timer {1104our$t0= [ gettimeofday() ]1105ifdefined$t0;1106our$number_of_git_cmds=0;1107}11081109our$first_request=1;1110sub run_request {1111 reset_timer();11121113 evaluate_uri();1114if($first_request) {1115 evaluate_gitweb_config();1116 evaluate_git_version();1117}1118if($per_request_config) {1119if(ref($per_request_config)eq'CODE') {1120$per_request_config->();1121}elsif(!$first_request) {1122 evaluate_gitweb_config();1123}1124}1125 check_loadavg();11261127# $projectroot and $projects_list might be set in gitweb config file1128$projects_list||=$projectroot;11291130 evaluate_query_params();1131 evaluate_path_info();1132 evaluate_and_validate_params();1133 evaluate_git_dir();11341135 configure_gitweb_features();11361137 dispatch();1138}11391140our$is_last_request=sub{1};1141our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1142our$CGI='CGI';1143our$cgi;1144sub configure_as_fcgi {1145require CGI::Fast;1146our$CGI='CGI::Fast';11471148my$request_number=0;1149# let each child service 100 requests1150our$is_last_request=sub{ ++$request_number>100};1151}1152sub evaluate_argv {1153my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1154 configure_as_fcgi()1155if$script_name=~/\.fcgi$/;11561157return unless(@ARGV);11581159require Getopt::Long;1160 Getopt::Long::GetOptions(1161'fastcgi|fcgi|f'=> \&configure_as_fcgi,1162'nproc|n=i'=>sub{1163my($arg,$val) =@_;1164return unlesseval{require FCGI::ProcManager;1; };1165my$proc_manager= FCGI::ProcManager->new({1166 n_processes =>$val,1167});1168our$pre_listen_hook=sub{$proc_manager->pm_manage() };1169our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1170our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1171},1172);1173}11741175sub run {1176 evaluate_argv();11771178$first_request=1;1179$pre_listen_hook->()1180if$pre_listen_hook;11811182 REQUEST:1183while($cgi=$CGI->new()) {1184$pre_dispatch_hook->()1185if$pre_dispatch_hook;11861187 run_request();11881189$post_dispatch_hook->()1190if$post_dispatch_hook;1191$first_request=0;11921193last REQUEST if($is_last_request->());1194}11951196 DONE_GITWEB:11971;1198}11991200run();12011202if(defined caller) {1203# wrapped in a subroutine processing requests,1204# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1205return;1206}else{1207# pure CGI script, serving single request1208exit;1209}12101211## ======================================================================1212## action links12131214# possible values of extra options1215# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1216# -replay => 1 - start from a current view (replay with modifications)1217# -path_info => 0|1 - don't use/use path_info URL (if possible)1218# -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone1219sub href {1220my%params=@_;1221# default is to use -absolute url() i.e. $my_uri1222my$href=$params{-full} ?$my_url:$my_uri;12231224# implicit -replay, must be first of implicit params1225$params{-replay} =1if(keys%params==1&&$params{-anchor});12261227$params{'project'} =$projectunlessexists$params{'project'};12281229if($params{-replay}) {1230while(my($name,$symbol) =each%cgi_param_mapping) {1231if(!exists$params{$name}) {1232$params{$name} =$input_params{$name};1233}1234}1235}12361237my$use_pathinfo= gitweb_check_feature('pathinfo');1238if(defined$params{'project'} &&1239(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1240# try to put as many parameters as possible in PATH_INFO:1241# - project name1242# - action1243# - hash_parent or hash_parent_base:/file_parent1244# - hash or hash_base:/filename1245# - the snapshot_format as an appropriate suffix12461247# When the script is the root DirectoryIndex for the domain,1248# $href here would be something like http://gitweb.example.com/1249# Thus, we strip any trailing / from $href, to spare us double1250# slashes in the final URL1251$href=~ s,/$,,;12521253# Then add the project name, if present1254$href.="/".esc_path_info($params{'project'});1255delete$params{'project'};12561257# since we destructively absorb parameters, we keep this1258# boolean that remembers if we're handling a snapshot1259my$is_snapshot=$params{'action'}eq'snapshot';12601261# Summary just uses the project path URL, any other action is1262# added to the URL1263if(defined$params{'action'}) {1264$href.="/".esc_path_info($params{'action'})1265unless$params{'action'}eq'summary';1266delete$params{'action'};1267}12681269# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1270# stripping nonexistent or useless pieces1271$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1272||$params{'hash_parent'} ||$params{'hash'});1273if(defined$params{'hash_base'}) {1274if(defined$params{'hash_parent_base'}) {1275$href.= esc_path_info($params{'hash_parent_base'});1276# skip the file_parent if it's the same as the file_name1277if(defined$params{'file_parent'}) {1278if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1279delete$params{'file_parent'};1280}elsif($params{'file_parent'} !~/\.\./) {1281$href.=":/".esc_path_info($params{'file_parent'});1282delete$params{'file_parent'};1283}1284}1285$href.="..";1286delete$params{'hash_parent'};1287delete$params{'hash_parent_base'};1288}elsif(defined$params{'hash_parent'}) {1289$href.= esc_path_info($params{'hash_parent'})."..";1290delete$params{'hash_parent'};1291}12921293$href.= esc_path_info($params{'hash_base'});1294if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1295$href.=":/".esc_path_info($params{'file_name'});1296delete$params{'file_name'};1297}1298delete$params{'hash'};1299delete$params{'hash_base'};1300}elsif(defined$params{'hash'}) {1301$href.= esc_path_info($params{'hash'});1302delete$params{'hash'};1303}13041305# If the action was a snapshot, we can absorb the1306# snapshot_format parameter too1307if($is_snapshot) {1308my$fmt=$params{'snapshot_format'};1309# snapshot_format should always be defined when href()1310# is called, but just in case some code forgets, we1311# fall back to the default1312$fmt||=$snapshot_fmts[0];1313$href.=$known_snapshot_formats{$fmt}{'suffix'};1314delete$params{'snapshot_format'};1315}1316}13171318# now encode the parameters explicitly1319my@result= ();1320for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1321my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1322if(defined$params{$name}) {1323if(ref($params{$name})eq"ARRAY") {1324foreachmy$par(@{$params{$name}}) {1325push@result,$symbol."=". esc_param($par);1326}1327}else{1328push@result,$symbol."=". esc_param($params{$name});1329}1330}1331}1332$href.="?".join(';',@result)ifscalar@result;13331334# final transformation: trailing spaces must be escaped (URI-encoded)1335$href=~s/(\s+)$/CGI::escape($1)/e;13361337if($params{-anchor}) {1338$href.="#".esc_param($params{-anchor});1339}13401341return$href;1342}134313441345## ======================================================================1346## validation, quoting/unquoting and escaping13471348sub validate_action {1349my$input=shift||returnundef;1350returnundefunlessexists$actions{$input};1351return$input;1352}13531354sub validate_project {1355my$input=shift||returnundef;1356if(!validate_pathname($input) ||1357!(-d "$projectroot/$input") ||1358!check_export_ok("$projectroot/$input") ||1359($strict_export&& !project_in_list($input))) {1360returnundef;1361}else{1362return$input;1363}1364}13651366sub validate_pathname {1367my$input=shift||returnundef;13681369# no '.' or '..' as elements of path, i.e. no '.' nor '..'1370# at the beginning, at the end, and between slashes.1371# also this catches doubled slashes1372if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1373returnundef;1374}1375# no null characters1376if($input=~m!\0!) {1377returnundef;1378}1379return$input;1380}13811382sub validate_refname {1383my$input=shift||returnundef;13841385# textual hashes are O.K.1386if($input=~m/^[0-9a-fA-F]{40}$/) {1387return$input;1388}1389# it must be correct pathname1390$input= validate_pathname($input)1391orreturnundef;1392# restrictions on ref name according to git-check-ref-format1393if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1394returnundef;1395}1396return$input;1397}13981399# decode sequences of octets in utf8 into Perl's internal form,1400# which is utf-8 with utf8 flag set if needed. gitweb writes out1401# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1402sub to_utf8 {1403my$str=shift;1404returnundefunlessdefined$str;1405if(utf8::valid($str)) {1406 utf8::decode($str);1407return$str;1408}else{1409return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1410}1411}14121413# quote unsafe chars, but keep the slash, even when it's not1414# correct, but quoted slashes look too horrible in bookmarks1415sub esc_param {1416my$str=shift;1417returnundefunlessdefined$str;1418$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1419$str=~s/ /\+/g;1420return$str;1421}14221423# the quoting rules for path_info fragment are slightly different1424sub esc_path_info {1425my$str=shift;1426returnundefunlessdefined$str;14271428# path_info doesn't treat '+' as space (specially), but '?' must be escaped1429$str=~s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;14301431return$str;1432}14331434# quote unsafe chars in whole URL, so some characters cannot be quoted1435sub esc_url {1436my$str=shift;1437returnundefunlessdefined$str;1438$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1439$str=~s/ /\+/g;1440return$str;1441}14421443# quote unsafe characters in HTML attributes1444sub esc_attr {14451446# for XHTML conformance escaping '"' to '"' is not enough1447return esc_html(@_);1448}14491450# replace invalid utf8 character with SUBSTITUTION sequence1451sub esc_html {1452my$str=shift;1453my%opts=@_;14541455returnundefunlessdefined$str;14561457$str= to_utf8($str);1458$str=$cgi->escapeHTML($str);1459if($opts{'-nbsp'}) {1460$str=~s/ / /g;1461}1462$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1463return$str;1464}14651466# quote control characters and escape filename to HTML1467sub esc_path {1468my$str=shift;1469my%opts=@_;14701471returnundefunlessdefined$str;14721473$str= to_utf8($str);1474$str=$cgi->escapeHTML($str);1475if($opts{'-nbsp'}) {1476$str=~s/ / /g;1477}1478$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1479return$str;1480}14811482# Make control characters "printable", using character escape codes (CEC)1483sub quot_cec {1484my$cntrl=shift;1485my%opts=@_;1486my%es= (# character escape codes, aka escape sequences1487"\t"=>'\t',# tab (HT)1488"\n"=>'\n',# line feed (LF)1489"\r"=>'\r',# carrige return (CR)1490"\f"=>'\f',# form feed (FF)1491"\b"=>'\b',# backspace (BS)1492"\a"=>'\a',# alarm (bell) (BEL)1493"\e"=>'\e',# escape (ESC)1494"\013"=>'\v',# vertical tab (VT)1495"\000"=>'\0',# nul character (NUL)1496);1497my$chr= ( (exists$es{$cntrl})1498?$es{$cntrl}1499:sprintf('\%2x',ord($cntrl)) );1500if($opts{-nohtml}) {1501return$chr;1502}else{1503return"<span class=\"cntrl\">$chr</span>";1504}1505}15061507# Alternatively use unicode control pictures codepoints,1508# Unicode "printable representation" (PR)1509sub quot_upr {1510my$cntrl=shift;1511my%opts=@_;15121513my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1514if($opts{-nohtml}) {1515return$chr;1516}else{1517return"<span class=\"cntrl\">$chr</span>";1518}1519}15201521# git may return quoted and escaped filenames1522sub unquote {1523my$str=shift;15241525sub unq {1526my$seq=shift;1527my%es= (# character escape codes, aka escape sequences1528't'=>"\t",# tab (HT, TAB)1529'n'=>"\n",# newline (NL)1530'r'=>"\r",# return (CR)1531'f'=>"\f",# form feed (FF)1532'b'=>"\b",# backspace (BS)1533'a'=>"\a",# alarm (bell) (BEL)1534'e'=>"\e",# escape (ESC)1535'v'=>"\013",# vertical tab (VT)1536);15371538if($seq=~m/^[0-7]{1,3}$/) {1539# octal char sequence1540returnchr(oct($seq));1541}elsif(exists$es{$seq}) {1542# C escape sequence, aka character escape code1543return$es{$seq};1544}1545# quoted ordinary character1546return$seq;1547}15481549if($str=~m/^"(.*)"$/) {1550# needs unquoting1551$str=$1;1552$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1553}1554return$str;1555}15561557# escape tabs (convert tabs to spaces)1558sub untabify {1559my$line=shift;15601561while((my$pos=index($line,"\t")) != -1) {1562if(my$count= (8- ($pos%8))) {1563my$spaces=' ' x $count;1564$line=~s/\t/$spaces/;1565}1566}15671568return$line;1569}15701571sub project_in_list {1572my$project=shift;1573my@list= git_get_projects_list();1574return@list&&scalar(grep{$_->{'path'}eq$project}@list);1575}15761577## ----------------------------------------------------------------------1578## HTML aware string manipulation15791580# Try to chop given string on a word boundary between position1581# $len and $len+$add_len. If there is no word boundary there,1582# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1583# (marking chopped part) would be longer than given string.1584sub chop_str {1585my$str=shift;1586my$len=shift;1587my$add_len=shift||10;1588my$where=shift||'right';# 'left' | 'center' | 'right'15891590# Make sure perl knows it is utf8 encoded so we don't1591# cut in the middle of a utf8 multibyte char.1592$str= to_utf8($str);15931594# allow only $len chars, but don't cut a word if it would fit in $add_len1595# if it doesn't fit, cut it if it's still longer than the dots we would add1596# remove chopped character entities entirely15971598# when chopping in the middle, distribute $len into left and right part1599# return early if chopping wouldn't make string shorter1600if($whereeq'center') {1601return$strif($len+5>=length($str));# filler is length 51602$len=int($len/2);1603}else{1604return$strif($len+4>=length($str));# filler is length 41605}16061607# regexps: ending and beginning with word part up to $add_len1608my$endre=qr/.{$len}\w{0,$add_len}/;1609my$begre=qr/\w{0,$add_len}.{$len}/;16101611if($whereeq'left') {1612$str=~m/^(.*?)($begre)$/;1613my($lead,$body) = ($1,$2);1614if(length($lead) >4) {1615$lead=" ...";1616}1617return"$lead$body";16181619}elsif($whereeq'center') {1620$str=~m/^($endre)(.*)$/;1621my($left,$str) = ($1,$2);1622$str=~m/^(.*?)($begre)$/;1623my($mid,$right) = ($1,$2);1624if(length($mid) >5) {1625$mid=" ... ";1626}1627return"$left$mid$right";16281629}else{1630$str=~m/^($endre)(.*)$/;1631my$body=$1;1632my$tail=$2;1633if(length($tail) >4) {1634$tail="... ";1635}1636return"$body$tail";1637}1638}16391640# takes the same arguments as chop_str, but also wraps a <span> around the1641# result with a title attribute if it does get chopped. Additionally, the1642# string is HTML-escaped.1643sub chop_and_escape_str {1644my($str) =@_;16451646my$chopped= chop_str(@_);1647if($choppedeq$str) {1648return esc_html($chopped);1649}else{1650$str=~s/[[:cntrl:]]/?/g;1651return$cgi->span({-title=>$str}, esc_html($chopped));1652}1653}16541655## ----------------------------------------------------------------------1656## functions returning short strings16571658# CSS class for given age value (in seconds)1659sub age_class {1660my$age=shift;16611662if(!defined$age) {1663return"noage";1664}elsif($age<60*60*2) {1665return"age0";1666}elsif($age<60*60*24*2) {1667return"age1";1668}else{1669return"age2";1670}1671}16721673# convert age in seconds to "nn units ago" string1674sub age_string {1675my$age=shift;1676my$age_str;16771678if($age>60*60*24*365*2) {1679$age_str= (int$age/60/60/24/365);1680$age_str.=" years ago";1681}elsif($age>60*60*24*(365/12)*2) {1682$age_str=int$age/60/60/24/(365/12);1683$age_str.=" months ago";1684}elsif($age>60*60*24*7*2) {1685$age_str=int$age/60/60/24/7;1686$age_str.=" weeks ago";1687}elsif($age>60*60*24*2) {1688$age_str=int$age/60/60/24;1689$age_str.=" days ago";1690}elsif($age>60*60*2) {1691$age_str=int$age/60/60;1692$age_str.=" hours ago";1693}elsif($age>60*2) {1694$age_str=int$age/60;1695$age_str.=" min ago";1696}elsif($age>2) {1697$age_str=int$age;1698$age_str.=" sec ago";1699}else{1700$age_str.=" right now";1701}1702return$age_str;1703}17041705useconstant{1706 S_IFINVALID =>0030000,1707 S_IFGITLINK =>0160000,1708};17091710# submodule/subproject, a commit object reference1711sub S_ISGITLINK {1712my$mode=shift;17131714return(($mode& S_IFMT) == S_IFGITLINK)1715}17161717# convert file mode in octal to symbolic file mode string1718sub mode_str {1719my$mode=oct shift;17201721if(S_ISGITLINK($mode)) {1722return'm---------';1723}elsif(S_ISDIR($mode& S_IFMT)) {1724return'drwxr-xr-x';1725}elsif(S_ISLNK($mode)) {1726return'lrwxrwxrwx';1727}elsif(S_ISREG($mode)) {1728# git cares only about the executable bit1729if($mode& S_IXUSR) {1730return'-rwxr-xr-x';1731}else{1732return'-rw-r--r--';1733};1734}else{1735return'----------';1736}1737}17381739# convert file mode in octal to file type string1740sub file_type {1741my$mode=shift;17421743if($mode!~m/^[0-7]+$/) {1744return$mode;1745}else{1746$mode=oct$mode;1747}17481749if(S_ISGITLINK($mode)) {1750return"submodule";1751}elsif(S_ISDIR($mode& S_IFMT)) {1752return"directory";1753}elsif(S_ISLNK($mode)) {1754return"symlink";1755}elsif(S_ISREG($mode)) {1756return"file";1757}else{1758return"unknown";1759}1760}17611762# convert file mode in octal to file type description string1763sub file_type_long {1764my$mode=shift;17651766if($mode!~m/^[0-7]+$/) {1767return$mode;1768}else{1769$mode=oct$mode;1770}17711772if(S_ISGITLINK($mode)) {1773return"submodule";1774}elsif(S_ISDIR($mode& S_IFMT)) {1775return"directory";1776}elsif(S_ISLNK($mode)) {1777return"symlink";1778}elsif(S_ISREG($mode)) {1779if($mode& S_IXUSR) {1780return"executable";1781}else{1782return"file";1783};1784}else{1785return"unknown";1786}1787}178817891790## ----------------------------------------------------------------------1791## functions returning short HTML fragments, or transforming HTML fragments1792## which don't belong to other sections17931794# format line of commit message.1795sub format_log_line_html {1796my$line=shift;17971798$line= esc_html($line, -nbsp=>1);1799$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1800$cgi->a({-href => href(action=>"object", hash=>$1),1801-class=>"text"},$1);1802}eg;18031804return$line;1805}18061807# format marker of refs pointing to given object18081809# the destination action is chosen based on object type and current context:1810# - for annotated tags, we choose the tag view unless it's the current view1811# already, in which case we go to shortlog view1812# - for other refs, we keep the current view if we're in history, shortlog or1813# log view, and select shortlog otherwise1814sub format_ref_marker {1815my($refs,$id) =@_;1816my$markers='';18171818if(defined$refs->{$id}) {1819foreachmy$ref(@{$refs->{$id}}) {1820# this code exploits the fact that non-lightweight tags are the1821# only indirect objects, and that they are the only objects for which1822# we want to use tag instead of shortlog as action1823my($type,$name) =qw();1824my$indirect= ($ref=~s/\^\{\}$//);1825# e.g. tags/v2.6.11 or heads/next1826if($ref=~m!^(.*?)s?/(.*)$!) {1827$type=$1;1828$name=$2;1829}else{1830$type="ref";1831$name=$ref;1832}18331834my$class=$type;1835$class.=" indirect"if$indirect;18361837my$dest_action="shortlog";18381839if($indirect) {1840$dest_action="tag"unless$actioneq"tag";1841}elsif($action=~/^(history|(short)?log)$/) {1842$dest_action=$action;1843}18441845my$dest="";1846$dest.="refs/"unless$ref=~ m!^refs/!;1847$dest.=$ref;18481849my$link=$cgi->a({1850-href => href(1851 action=>$dest_action,1852 hash=>$dest1853)},$name);18541855$markers.=" <span class=\"".esc_attr($class)."\"title=\"".esc_attr($ref)."\">".1856$link."</span>";1857}1858}18591860if($markers) {1861return' <span class="refs">'.$markers.'</span>';1862}else{1863return"";1864}1865}18661867# format, perhaps shortened and with markers, title line1868sub format_subject_html {1869my($long,$short,$href,$extra) =@_;1870$extra=''unlessdefined($extra);18711872if(length($short) <length($long)) {1873$long=~s/[[:cntrl:]]/?/g;1874return$cgi->a({-href =>$href, -class=>"list subject",1875-title => to_utf8($long)},1876 esc_html($short)) .$extra;1877}else{1878return$cgi->a({-href =>$href, -class=>"list subject"},1879 esc_html($long)) .$extra;1880}1881}18821883# Rather than recomputing the url for an email multiple times, we cache it1884# after the first hit. This gives a visible benefit in views where the avatar1885# for the same email is used repeatedly (e.g. shortlog).1886# The cache is shared by all avatar engines (currently gravatar only), which1887# are free to use it as preferred. Since only one avatar engine is used for any1888# given page, there's no risk for cache conflicts.1889our%avatar_cache= ();18901891# Compute the picon url for a given email, by using the picon search service over at1892# http://www.cs.indiana.edu/picons/search.html1893sub picon_url {1894my$email=lc shift;1895if(!$avatar_cache{$email}) {1896my($user,$domain) =split('@',$email);1897$avatar_cache{$email} =1898"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1899"$domain/$user/".1900"users+domains+unknown/up/single";1901}1902return$avatar_cache{$email};1903}19041905# Compute the gravatar url for a given email, if it's not in the cache already.1906# Gravatar stores only the part of the URL before the size, since that's the1907# one computationally more expensive. This also allows reuse of the cache for1908# different sizes (for this particular engine).1909sub gravatar_url {1910my$email=lc shift;1911my$size=shift;1912$avatar_cache{$email} ||=1913"http://www.gravatar.com/avatar/".1914 Digest::MD5::md5_hex($email) ."?s=";1915return$avatar_cache{$email} .$size;1916}19171918# Insert an avatar for the given $email at the given $size if the feature1919# is enabled.1920sub git_get_avatar {1921my($email,%opts) =@_;1922my$pre_white= ($opts{-pad_before} ?" ":"");1923my$post_white= ($opts{-pad_after} ?" ":"");1924$opts{-size} ||='default';1925my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1926my$url="";1927if($git_avatareq'gravatar') {1928$url= gravatar_url($email,$size);1929}elsif($git_avatareq'picon') {1930$url= picon_url($email);1931}1932# Other providers can be added by extending the if chain, defining $url1933# as needed. If no variant puts something in $url, we assume avatars1934# are completely disabled/unavailable.1935if($url) {1936return$pre_white.1937"<img width=\"$size\"".1938"class=\"avatar\"".1939"src=\"".esc_url($url)."\"".1940"alt=\"\"".1941"/>".$post_white;1942}else{1943return"";1944}1945}19461947sub format_search_author {1948my($author,$searchtype,$displaytext) =@_;1949my$have_search= gitweb_check_feature('search');19501951if($have_search) {1952my$performed="";1953if($searchtypeeq'author') {1954$performed="authored";1955}elsif($searchtypeeq'committer') {1956$performed="committed";1957}19581959return$cgi->a({-href => href(action=>"search", hash=>$hash,1960 searchtext=>$author,1961 searchtype=>$searchtype),class=>"list",1962 title=>"Search for commits$performedby$author"},1963$displaytext);19641965}else{1966return$displaytext;1967}1968}19691970# format the author name of the given commit with the given tag1971# the author name is chopped and escaped according to the other1972# optional parameters (see chop_str).1973sub format_author_html {1974my$tag=shift;1975my$co=shift;1976my$author= chop_and_escape_str($co->{'author_name'},@_);1977return"<$tagclass=\"author\">".1978 format_search_author($co->{'author_name'},"author",1979 git_get_avatar($co->{'author_email'}, -pad_after =>1) .1980$author) .1981"</$tag>";1982}19831984# format git diff header line, i.e. "diff --(git|combined|cc) ..."1985sub format_git_diff_header_line {1986my$line=shift;1987my$diffinfo=shift;1988my($from,$to) =@_;19891990if($diffinfo->{'nparents'}) {1991# combined diff1992$line=~s!^(diff (.*?) )"?.*$!$1!;1993if($to->{'href'}) {1994$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1995 esc_path($to->{'file'}));1996}else{# file was deleted (no href)1997$line.= esc_path($to->{'file'});1998}1999}else{2000# "ordinary" diff2001$line=~s!^(diff (.*?) )"?a/.*$!$1!;2002if($from->{'href'}) {2003$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},2004'a/'. esc_path($from->{'file'}));2005}else{# file was added (no href)2006$line.='a/'. esc_path($from->{'file'});2007}2008$line.=' ';2009if($to->{'href'}) {2010$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2011'b/'. esc_path($to->{'file'}));2012}else{# file was deleted2013$line.='b/'. esc_path($to->{'file'});2014}2015}20162017return"<div class=\"diff header\">$line</div>\n";2018}20192020# format extended diff header line, before patch itself2021sub format_extended_diff_header_line {2022my$line=shift;2023my$diffinfo=shift;2024my($from,$to) =@_;20252026# match <path>2027if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {2028$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},2029 esc_path($from->{'file'}));2030}2031if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {2032$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},2033 esc_path($to->{'file'}));2034}2035# match single <mode>2036if($line=~m/\s(\d{6})$/) {2037$line.='<span class="info"> ('.2038 file_type_long($1) .2039')</span>';2040}2041# match <hash>2042if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {2043# can match only for combined diff2044$line='index ';2045for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2046if($from->{'href'}[$i]) {2047$line.=$cgi->a({-href=>$from->{'href'}[$i],2048-class=>"hash"},2049substr($diffinfo->{'from_id'}[$i],0,7));2050}else{2051$line.='0' x 7;2052}2053# separator2054$line.=','if($i<$diffinfo->{'nparents'} -1);2055}2056$line.='..';2057if($to->{'href'}) {2058$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2059substr($diffinfo->{'to_id'},0,7));2060}else{2061$line.='0' x 7;2062}20632064}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {2065# can match only for ordinary diff2066my($from_link,$to_link);2067if($from->{'href'}) {2068$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},2069substr($diffinfo->{'from_id'},0,7));2070}else{2071$from_link='0' x 7;2072}2073if($to->{'href'}) {2074$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2075substr($diffinfo->{'to_id'},0,7));2076}else{2077$to_link='0' x 7;2078}2079my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});2080$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;2081}20822083return$line."<br/>\n";2084}20852086# format from-file/to-file diff header2087sub format_diff_from_to_header {2088my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2089my$line;2090my$result='';20912092$line=$from_line;2093#assert($line =~ m/^---/) if DEBUG;2094# no extra formatting for "^--- /dev/null"2095if(!$diffinfo->{'nparents'}) {2096# ordinary (single parent) diff2097if($line=~m!^--- "?a/!) {2098if($from->{'href'}) {2099$line='--- a/'.2100$cgi->a({-href=>$from->{'href'}, -class=>"path"},2101 esc_path($from->{'file'}));2102}else{2103$line='--- a/'.2104 esc_path($from->{'file'});2105}2106}2107$result.= qq!<div class="diff from_file">$line</div>\n!;21082109}else{2110# combined diff (merge commit)2111for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2112if($from->{'href'}[$i]) {2113$line='--- '.2114$cgi->a({-href=>href(action=>"blobdiff",2115 hash_parent=>$diffinfo->{'from_id'}[$i],2116 hash_parent_base=>$parents[$i],2117 file_parent=>$from->{'file'}[$i],2118 hash=>$diffinfo->{'to_id'},2119 hash_base=>$hash,2120 file_name=>$to->{'file'}),2121-class=>"path",2122-title=>"diff". ($i+1)},2123$i+1) .2124'/'.2125$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2126 esc_path($from->{'file'}[$i]));2127}else{2128$line='--- /dev/null';2129}2130$result.= qq!<div class="diff from_file">$line</div>\n!;2131}2132}21332134$line=$to_line;2135#assert($line =~ m/^\+\+\+/) if DEBUG;2136# no extra formatting for "^+++ /dev/null"2137if($line=~m!^\+\+\+ "?b/!) {2138if($to->{'href'}) {2139$line='+++ b/'.2140$cgi->a({-href=>$to->{'href'}, -class=>"path"},2141 esc_path($to->{'file'}));2142}else{2143$line='+++ b/'.2144 esc_path($to->{'file'});2145}2146}2147$result.= qq!<div class="diff to_file">$line</div>\n!;21482149return$result;2150}21512152# create note for patch simplified by combined diff2153sub format_diff_cc_simplified {2154my($diffinfo,@parents) =@_;2155my$result='';21562157$result.="<div class=\"diff header\">".2158"diff --cc ";2159if(!is_deleted($diffinfo)) {2160$result.=$cgi->a({-href => href(action=>"blob",2161 hash_base=>$hash,2162 hash=>$diffinfo->{'to_id'},2163 file_name=>$diffinfo->{'to_file'}),2164-class=>"path"},2165 esc_path($diffinfo->{'to_file'}));2166}else{2167$result.= esc_path($diffinfo->{'to_file'});2168}2169$result.="</div>\n".# class="diff header"2170"<div class=\"diff nodifferences\">".2171"Simple merge".2172"</div>\n";# class="diff nodifferences"21732174return$result;2175}21762177# format patch (diff) line (not to be used for diff headers)2178sub format_diff_line {2179my$line=shift;2180my($from,$to) =@_;2181my$diff_class="";21822183chomp$line;21842185if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2186# combined diff2187my$prefix=substr($line,0,scalar@{$from->{'href'}});2188if($line=~m/^\@{3}/) {2189$diff_class=" chunk_header";2190}elsif($line=~m/^\\/) {2191$diff_class=" incomplete";2192}elsif($prefix=~tr/+/+/) {2193$diff_class=" add";2194}elsif($prefix=~tr/-/-/) {2195$diff_class=" rem";2196}2197}else{2198# assume ordinary diff2199my$char=substr($line,0,1);2200if($chareq'+') {2201$diff_class=" add";2202}elsif($chareq'-') {2203$diff_class=" rem";2204}elsif($chareq'@') {2205$diff_class=" chunk_header";2206}elsif($chareq"\\") {2207$diff_class=" incomplete";2208}2209}2210$line= untabify($line);2211if($from&&$to&&$line=~m/^\@{2} /) {2212my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2213$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;22142215$from_lines=0unlessdefined$from_lines;2216$to_lines=0unlessdefined$to_lines;22172218if($from->{'href'}) {2219$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2220-class=>"list"},$from_text);2221}2222if($to->{'href'}) {2223$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2224-class=>"list"},$to_text);2225}2226$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2227"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2228return"<div class=\"diff$diff_class\">$line</div>\n";2229}elsif($from&&$to&&$line=~m/^\@{3}/) {2230my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2231my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);22322233@from_text=split(' ',$ranges);2234for(my$i=0;$i<@from_text; ++$i) {2235($from_start[$i],$from_nlines[$i]) =2236(split(',',substr($from_text[$i],1)),0);2237}22382239$to_text=pop@from_text;2240$to_start=pop@from_start;2241$to_nlines=pop@from_nlines;22422243$line="<span class=\"chunk_info\">$prefix";2244for(my$i=0;$i<@from_text; ++$i) {2245if($from->{'href'}[$i]) {2246$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2247-class=>"list"},$from_text[$i]);2248}else{2249$line.=$from_text[$i];2250}2251$line.=" ";2252}2253if($to->{'href'}) {2254$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2255-class=>"list"},$to_text);2256}else{2257$line.=$to_text;2258}2259$line.="$prefix</span>".2260"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2261return"<div class=\"diff$diff_class\">$line</div>\n";2262}2263return"<div class=\"diff$diff_class\">". esc_html($line, -nbsp=>1) ."</div>\n";2264}22652266# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2267# linked. Pass the hash of the tree/commit to snapshot.2268sub format_snapshot_links {2269my($hash) =@_;2270my$num_fmts=@snapshot_fmts;2271if($num_fmts>1) {2272# A parenthesized list of links bearing format names.2273# e.g. "snapshot (_tar.gz_ _zip_)"2274return"snapshot (".join(' ',map2275$cgi->a({2276-href => href(2277 action=>"snapshot",2278 hash=>$hash,2279 snapshot_format=>$_2280)2281},$known_snapshot_formats{$_}{'display'})2282,@snapshot_fmts) .")";2283}elsif($num_fmts==1) {2284# A single "snapshot" link whose tooltip bears the format name.2285# i.e. "_snapshot_"2286my($fmt) =@snapshot_fmts;2287return2288$cgi->a({2289-href => href(2290 action=>"snapshot",2291 hash=>$hash,2292 snapshot_format=>$fmt2293),2294-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2295},"snapshot");2296}else{# $num_fmts == 02297returnundef;2298}2299}23002301## ......................................................................2302## functions returning values to be passed, perhaps after some2303## transformation, to other functions; e.g. returning arguments to href()23042305# returns hash to be passed to href to generate gitweb URL2306# in -title key it returns description of link2307sub get_feed_info {2308my$format=shift||'Atom';2309my%res= (action =>lc($format));23102311# feed links are possible only for project views2312return unless(defined$project);2313# some views should link to OPML, or to generic project feed,2314# or don't have specific feed yet (so they should use generic)2315return if($action=~/^(?:tags|heads|forks|tag|search)$/x);23162317my$branch;2318# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2319# from tag links; this also makes possible to detect branch links2320if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2321(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2322$branch=$1;2323}2324# find log type for feed description (title)2325my$type='log';2326if(defined$file_name) {2327$type="history of$file_name";2328$type.="/"if($actioneq'tree');2329$type.=" on '$branch'"if(defined$branch);2330}else{2331$type="log of$branch"if(defined$branch);2332}23332334$res{-title} =$type;2335$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2336$res{'file_name'} =$file_name;23372338return%res;2339}23402341## ----------------------------------------------------------------------2342## git utility subroutines, invoking git commands23432344# returns path to the core git executable and the --git-dir parameter as list2345sub git_cmd {2346$number_of_git_cmds++;2347return$GIT,'--git-dir='.$git_dir;2348}23492350# quote the given arguments for passing them to the shell2351# quote_command("command", "arg 1", "arg with ' and ! characters")2352# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2353# Try to avoid using this function wherever possible.2354sub quote_command {2355returnjoin(' ',2356map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2357}23582359# get HEAD ref of given project as hash2360sub git_get_head_hash {2361return git_get_full_hash(shift,'HEAD');2362}23632364sub git_get_full_hash {2365return git_get_hash(@_);2366}23672368sub git_get_short_hash {2369return git_get_hash(@_,'--short=7');2370}23712372sub git_get_hash {2373my($project,$hash,@options) =@_;2374my$o_git_dir=$git_dir;2375my$retval=undef;2376$git_dir="$projectroot/$project";2377if(open my$fd,'-|', git_cmd(),'rev-parse',2378'--verify','-q',@options,$hash) {2379$retval= <$fd>;2380chomp$retvalifdefined$retval;2381close$fd;2382}2383if(defined$o_git_dir) {2384$git_dir=$o_git_dir;2385}2386return$retval;2387}23882389# get type of given object2390sub git_get_type {2391my$hash=shift;23922393open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2394my$type= <$fd>;2395close$fdorreturn;2396chomp$type;2397return$type;2398}23992400# repository configuration2401our$config_file='';2402our%config;24032404# store multiple values for single key as anonymous array reference2405# single values stored directly in the hash, not as [ <value> ]2406sub hash_set_multi {2407my($hash,$key,$value) =@_;24082409if(!exists$hash->{$key}) {2410$hash->{$key} =$value;2411}elsif(!ref$hash->{$key}) {2412$hash->{$key} = [$hash->{$key},$value];2413}else{2414push@{$hash->{$key}},$value;2415}2416}24172418# return hash of git project configuration2419# optionally limited to some section, e.g. 'gitweb'2420sub git_parse_project_config {2421my$section_regexp=shift;2422my%config;24232424local$/="\0";24252426open my$fh,"-|", git_cmd(),"config",'-z','-l',2427orreturn;24282429while(my$keyval= <$fh>) {2430chomp$keyval;2431my($key,$value) =split(/\n/,$keyval,2);24322433 hash_set_multi(\%config,$key,$value)2434if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2435}2436close$fh;24372438return%config;2439}24402441# convert config value to boolean: 'true' or 'false'2442# no value, number > 0, 'true' and 'yes' values are true2443# rest of values are treated as false (never as error)2444sub config_to_bool {2445my$val=shift;24462447return1if!defined$val;# section.key24482449# strip leading and trailing whitespace2450$val=~s/^\s+//;2451$val=~s/\s+$//;24522453return(($val=~/^\d+$/&&$val) ||# section.key = 12454($val=~/^(?:true|yes)$/i));# section.key = true2455}24562457# convert config value to simple decimal number2458# an optional value suffix of 'k', 'm', or 'g' will cause the value2459# to be multiplied by 1024, 1048576, or 10737418242460sub config_to_int {2461my$val=shift;24622463# strip leading and trailing whitespace2464$val=~s/^\s+//;2465$val=~s/\s+$//;24662467if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2468$unit=lc($unit);2469# unknown unit is treated as 12470return$num* ($uniteq'g'?1073741824:2471$uniteq'm'?1048576:2472$uniteq'k'?1024:1);2473}2474return$val;2475}24762477# convert config value to array reference, if needed2478sub config_to_multi {2479my$val=shift;24802481returnref($val) ?$val: (defined($val) ? [$val] : []);2482}24832484sub git_get_project_config {2485my($key,$type) =@_;24862487return unlessdefined$git_dir;24882489# key sanity check2490return unless($key);2491$key=~s/^gitweb\.//;2492return if($key=~m/\W/);24932494# type sanity check2495if(defined$type) {2496$type=~s/^--//;2497$type=undef2498unless($typeeq'bool'||$typeeq'int');2499}25002501# get config2502if(!defined$config_file||2503$config_filene"$git_dir/config") {2504%config= git_parse_project_config('gitweb');2505$config_file="$git_dir/config";2506}25072508# check if config variable (key) exists2509return unlessexists$config{"gitweb.$key"};25102511# ensure given type2512if(!defined$type) {2513return$config{"gitweb.$key"};2514}elsif($typeeq'bool') {2515# backward compatibility: 'git config --bool' returns true/false2516return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2517}elsif($typeeq'int') {2518return config_to_int($config{"gitweb.$key"});2519}2520return$config{"gitweb.$key"};2521}25222523# get hash of given path at given ref2524sub git_get_hash_by_path {2525my$base=shift;2526my$path=shift||returnundef;2527my$type=shift;25282529$path=~ s,/+$,,;25302531open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2532or die_error(500,"Open git-ls-tree failed");2533my$line= <$fd>;2534close$fdorreturnundef;25352536if(!defined$line) {2537# there is no tree or hash given by $path at $base2538returnundef;2539}25402541#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2542$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2543if(defined$type&&$typene$2) {2544# type doesn't match2545returnundef;2546}2547return$3;2548}25492550# get path of entry with given hash at given tree-ish (ref)2551# used to get 'from' filename for combined diff (merge commit) for renames2552sub git_get_path_by_hash {2553my$base=shift||return;2554my$hash=shift||return;25552556local$/="\0";25572558open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2559orreturnundef;2560while(my$line= <$fd>) {2561chomp$line;25622563#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2564#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2565if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2566close$fd;2567return$1;2568}2569}2570close$fd;2571returnundef;2572}25732574## ......................................................................2575## git utility functions, directly accessing git repository25762577sub git_get_project_description {2578my$path=shift;25792580$git_dir="$projectroot/$path";2581open my$fd,'<',"$git_dir/description"2582orreturn git_get_project_config('description');2583my$descr= <$fd>;2584close$fd;2585if(defined$descr) {2586chomp$descr;2587}2588return$descr;2589}25902591# supported formats:2592# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2593# - if its contents is a number, use it as tag weight,2594# - otherwise add a tag with weight 12595# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2596# the same value multiple times increases tag weight2597# * `gitweb.ctag' multi-valued repo config variable2598sub git_get_project_ctags {2599my$project=shift;2600my$ctags= {};26012602$git_dir="$projectroot/$project";2603if(opendir my$dh,"$git_dir/ctags") {2604my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2605foreachmy$tagfile(@files) {2606open my$ct,'<',$tagfile2607ornext;2608my$val= <$ct>;2609chomp$valif$val;2610close$ct;26112612(my$ctag=$tagfile) =~ s#.*/##;2613if($val=~/\d+/) {2614$ctags->{$ctag} =$val;2615}else{2616$ctags->{$ctag} =1;2617}2618}2619closedir$dh;26202621}elsif(open my$fh,'<',"$git_dir/ctags") {2622while(my$line= <$fh>) {2623chomp$line;2624$ctags->{$line}++if$line;2625}2626close$fh;26272628}else{2629my$taglist= config_to_multi(git_get_project_config('ctag'));2630foreachmy$tag(@$taglist) {2631$ctags->{$tag}++;2632}2633}26342635return$ctags;2636}26372638# return hash, where keys are content tags ('ctags'),2639# and values are sum of weights of given tag in every project2640sub git_gather_all_ctags {2641my$projects=shift;2642my$ctags= {};26432644foreachmy$p(@$projects) {2645foreachmy$ct(keys%{$p->{'ctags'}}) {2646$ctags->{$ct} +=$p->{'ctags'}->{$ct};2647}2648}26492650return$ctags;2651}26522653sub git_populate_project_tagcloud {2654my$ctags=shift;26552656# First, merge different-cased tags; tags vote on casing2657my%ctags_lc;2658foreach(keys%$ctags) {2659$ctags_lc{lc$_}->{count} +=$ctags->{$_};2660if(not$ctags_lc{lc$_}->{topcount}2661or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2662$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2663$ctags_lc{lc$_}->{topname} =$_;2664}2665}26662667my$cloud;2668my$matched=$cgi->param('by_tag');2669if(eval{require HTML::TagCloud;1; }) {2670$cloud= HTML::TagCloud->new;2671foreachmy$ctag(sort keys%ctags_lc) {2672# Pad the title with spaces so that the cloud looks2673# less crammed.2674my$title= esc_html($ctags_lc{$ctag}->{topname});2675$title=~s/ / /g;2676$title=~s/^/ /g;2677$title=~s/$/ /g;2678if(defined$matched&&$matchedeq$ctag) {2679$title=qq(<span class="match">$title</span>);2680}2681$cloud->add($title, href(project=>undef, ctag=>$ctag),2682$ctags_lc{$ctag}->{count});2683}2684}else{2685$cloud= {};2686foreachmy$ctag(keys%ctags_lc) {2687my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2688if(defined$matched&&$matchedeq$ctag) {2689$title=qq(<span class="match">$title</span>);2690}2691$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};2692$cloud->{$ctag}{ctag} =2693$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);2694}2695}2696return$cloud;2697}26982699sub git_show_project_tagcloud {2700my($cloud,$count) =@_;2701if(ref$cloudeq'HTML::TagCloud') {2702return$cloud->html_and_css($count);2703}else{2704my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;2705return2706'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.2707join(', ',map{2708$cloud->{$_}->{'ctag'}2709}splice(@tags,0,$count)) .2710'</div>';2711}2712}27132714sub git_get_project_url_list {2715my$path=shift;27162717$git_dir="$projectroot/$path";2718open my$fd,'<',"$git_dir/cloneurl"2719orreturnwantarray?2720@{ config_to_multi(git_get_project_config('url')) } :2721 config_to_multi(git_get_project_config('url'));2722my@git_project_url_list=map{chomp;$_} <$fd>;2723close$fd;27242725returnwantarray?@git_project_url_list: \@git_project_url_list;2726}27272728sub git_get_projects_list {2729my$filter=shift||'';2730my@list;27312732$filter=~s/\.git$//;27332734if(-d $projects_list) {2735# search in directory2736my$dir=$projects_list;2737# remove the trailing "/"2738$dir=~s!/+$!!;2739my$pfxlen=length("$projects_list");2740my$pfxdepth= ($projects_list=~tr!/!!);2741# when filtering, search only given subdirectory2742if($filter) {2743$dir.="/$filter";2744$dir=~s!/+$!!;2745}27462747 File::Find::find({2748 follow_fast =>1,# follow symbolic links2749 follow_skip =>2,# ignore duplicates2750 dangling_symlinks =>0,# ignore dangling symlinks, silently2751 wanted =>sub{2752# global variables2753our$project_maxdepth;2754our$projectroot;2755# skip project-list toplevel, if we get it.2756return if(m!^[/.]$!);2757# only directories can be git repositories2758return unless(-d $_);2759# don't traverse too deep (Find is super slow on os x)2760# $project_maxdepth excludes depth of $projectroot2761if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2762$File::Find::prune =1;2763return;2764}27652766my$path=substr($File::Find::name,$pfxlen+1);2767# we check related file in $projectroot2768if(check_export_ok("$projectroot/$path")) {2769push@list, { path =>$path};2770$File::Find::prune =1;2771}2772},2773},"$dir");27742775}elsif(-f $projects_list) {2776# read from file(url-encoded):2777# 'git%2Fgit.git Linus+Torvalds'2778# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2779# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2780open my$fd,'<',$projects_listorreturn;2781 PROJECT:2782while(my$line= <$fd>) {2783chomp$line;2784my($path,$owner) =split' ',$line;2785$path= unescape($path);2786$owner= unescape($owner);2787if(!defined$path) {2788next;2789}2790# if $filter is rpovided, check if $path begins with $filter2791if($filter&&$path!~m!^\Q$filter\E/!) {2792next;2793}2794if(check_export_ok("$projectroot/$path")) {2795my$pr= {2796 path =>$path,2797 owner => to_utf8($owner),2798};2799push@list,$pr;2800}2801}2802close$fd;2803}2804return@list;2805}28062807# written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)2808# as side effects it sets 'forks' field to list of forks for forked projects2809sub filter_forks_from_projects_list {2810my$projects=shift;28112812my%trie;# prefix tree of directories (path components)2813# generate trie out of those directories that might contain forks2814foreachmy$pr(@$projects) {2815my$path=$pr->{'path'};2816$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory2817next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'2818next unless($path);# skip '.git' repository: tests, git-instaweb2819next unless(-d $path);# containing directory exists2820$pr->{'forks'} = [];# there can be 0 or more forks of project28212822# add to trie2823my@dirs=split('/',$path);2824# walk the trie, until either runs out of components or out of trie2825my$ref= \%trie;2826while(scalar@dirs&&2827exists($ref->{$dirs[0]})) {2828$ref=$ref->{shift@dirs};2829}2830# create rest of trie structure from rest of components2831foreachmy$dir(@dirs) {2832$ref=$ref->{$dir} = {};2833}2834# create end marker, store $pr as a data2835$ref->{''} =$prif(!exists$ref->{''});2836}28372838# filter out forks, by finding shortest prefix match for paths2839my@filtered;2840 PROJECT:2841foreachmy$pr(@$projects) {2842# trie lookup2843my$ref= \%trie;2844 DIR:2845foreachmy$dir(split('/',$pr->{'path'})) {2846if(exists$ref->{''}) {2847# found [shortest] prefix, is a fork - skip it2848push@{$ref->{''}{'forks'}},$pr;2849next PROJECT;2850}2851if(!exists$ref->{$dir}) {2852# not in trie, cannot have prefix, not a fork2853push@filtered,$pr;2854next PROJECT;2855}2856# If the dir is there, we just walk one step down the trie.2857$ref=$ref->{$dir};2858}2859# we ran out of trie2860# (shouldn't happen: it's either no match, or end marker)2861push@filtered,$pr;2862}28632864return@filtered;2865}28662867# note: fill_project_list_info must be run first,2868# for 'descr_long' and 'ctags' to be filled2869sub search_projects_list {2870my($projlist,%opts) =@_;2871my$tagfilter=$opts{'tagfilter'};2872my$searchtext=$opts{'searchtext'};28732874return@$projlist2875unless($tagfilter||$searchtext);28762877my@projects;2878 PROJECT:2879foreachmy$pr(@$projlist) {28802881if($tagfilter) {2882next unlessref($pr->{'ctags'})eq'HASH';2883next unless2884grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};2885}28862887if($searchtext) {2888next unless2889$pr->{'path'} =~/$searchtext/||2890$pr->{'descr_long'} =~/$searchtext/;2891}28922893push@projects,$pr;2894}28952896return@projects;2897}28982899our$gitweb_project_owner=undef;2900sub git_get_project_list_from_file {29012902return if(defined$gitweb_project_owner);29032904$gitweb_project_owner= {};2905# read from file (url-encoded):2906# 'git%2Fgit.git Linus+Torvalds'2907# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2908# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2909if(-f $projects_list) {2910open(my$fd,'<',$projects_list);2911while(my$line= <$fd>) {2912chomp$line;2913my($pr,$ow) =split' ',$line;2914$pr= unescape($pr);2915$ow= unescape($ow);2916$gitweb_project_owner->{$pr} = to_utf8($ow);2917}2918close$fd;2919}2920}29212922sub git_get_project_owner {2923my$project=shift;2924my$owner;29252926returnundefunless$project;2927$git_dir="$projectroot/$project";29282929if(!defined$gitweb_project_owner) {2930 git_get_project_list_from_file();2931}29322933if(exists$gitweb_project_owner->{$project}) {2934$owner=$gitweb_project_owner->{$project};2935}2936if(!defined$owner){2937$owner= git_get_project_config('owner');2938}2939if(!defined$owner) {2940$owner= get_file_owner("$git_dir");2941}29422943return$owner;2944}29452946sub git_get_last_activity {2947my($path) =@_;2948my$fd;29492950$git_dir="$projectroot/$path";2951open($fd,"-|", git_cmd(),'for-each-ref',2952'--format=%(committer)',2953'--sort=-committerdate',2954'--count=1',2955'refs/heads')orreturn;2956my$most_recent= <$fd>;2957close$fdorreturn;2958if(defined$most_recent&&2959$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {2960my$timestamp=$1;2961my$age=time-$timestamp;2962return($age, age_string($age));2963}2964return(undef,undef);2965}29662967# Implementation note: when a single remote is wanted, we cannot use 'git2968# remote show -n' because that command always work (assuming it's a remote URL2969# if it's not defined), and we cannot use 'git remote show' because that would2970# try to make a network roundtrip. So the only way to find if that particular2971# remote is defined is to walk the list provided by 'git remote -v' and stop if2972# and when we find what we want.2973sub git_get_remotes_list {2974my$wanted=shift;2975my%remotes= ();29762977open my$fd,'-|', git_cmd(),'remote','-v';2978return unless$fd;2979while(my$remote= <$fd>) {2980chomp$remote;2981$remote=~s!\t(.*?)\s+\((\w+)\)$!!;2982next if$wantedand not$remoteeq$wanted;2983my($url,$key) = ($1,$2);29842985$remotes{$remote} ||= {'heads'=> () };2986$remotes{$remote}{$key} =$url;2987}2988close$fdorreturn;2989returnwantarray?%remotes: \%remotes;2990}29912992# Takes a hash of remotes as first parameter and fills it by adding the2993# available remote heads for each of the indicated remotes.2994sub fill_remote_heads {2995my$remotes=shift;2996my@heads=map{"remotes/$_"}keys%$remotes;2997my@remoteheads= git_get_heads_list(undef,@heads);2998foreachmy$remote(keys%$remotes) {2999$remotes->{$remote}{'heads'} = [grep{3000$_->{'name'} =~s!^$remote/!!3001}@remoteheads];3002}3003}30043005sub git_get_references {3006my$type=shift||"";3007my%refs;3008# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113009# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3010open my$fd,"-|", git_cmd(),"show-ref","--dereference",3011($type? ("--","refs/$type") : ())# use -- <pattern> if $type3012orreturn;30133014while(my$line= <$fd>) {3015chomp$line;3016if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3017if(defined$refs{$1}) {3018push@{$refs{$1}},$2;3019}else{3020$refs{$1} = [$2];3021}3022}3023}3024close$fdorreturn;3025return \%refs;3026}30273028sub git_get_rev_name_tags {3029my$hash=shift||returnundef;30303031open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3032orreturn;3033my$name_rev= <$fd>;3034close$fd;30353036if($name_rev=~ m|^$hash tags/(.*)$|) {3037return$1;3038}else{3039# catches also '$hash undefined' output3040returnundef;3041}3042}30433044## ----------------------------------------------------------------------3045## parse to hash functions30463047sub parse_date {3048my$epoch=shift;3049my$tz=shift||"-0000";30503051my%date;3052my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3053my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3054my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3055$date{'hour'} =$hour;3056$date{'minute'} =$min;3057$date{'mday'} =$mday;3058$date{'day'} =$days[$wday];3059$date{'month'} =$months[$mon];3060$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3061$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3062$date{'mday-time'} =sprintf"%d%s%02d:%02d",3063$mday,$months[$mon],$hour,$min;3064$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",30651900+$year,1+$mon,$mday,$hour,$min,$sec;30663067my($tz_sign,$tz_hour,$tz_min) =3068($tz=~m/^([-+])(\d\d)(\d\d)$/);3069$tz_sign= ($tz_signeq'-'? -1: +1);3070my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3071($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3072$date{'hour_local'} =$hour;3073$date{'minute_local'} =$min;3074$date{'tz_local'} =$tz;3075$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",30761900+$year,$mon+1,$mday,3077$hour,$min,$sec,$tz);3078return%date;3079}30803081sub parse_tag {3082my$tag_id=shift;3083my%tag;3084my@comment;30853086open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3087$tag{'id'} =$tag_id;3088while(my$line= <$fd>) {3089chomp$line;3090if($line=~m/^object ([0-9a-fA-F]{40})$/) {3091$tag{'object'} =$1;3092}elsif($line=~m/^type (.+)$/) {3093$tag{'type'} =$1;3094}elsif($line=~m/^tag (.+)$/) {3095$tag{'name'} =$1;3096}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3097$tag{'author'} =$1;3098$tag{'author_epoch'} =$2;3099$tag{'author_tz'} =$3;3100if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3101$tag{'author_name'} =$1;3102$tag{'author_email'} =$2;3103}else{3104$tag{'author_name'} =$tag{'author'};3105}3106}elsif($line=~m/--BEGIN/) {3107push@comment,$line;3108last;3109}elsif($lineeq"") {3110last;3111}3112}3113push@comment, <$fd>;3114$tag{'comment'} = \@comment;3115close$fdorreturn;3116if(!defined$tag{'name'}) {3117return3118};3119return%tag3120}31213122sub parse_commit_text {3123my($commit_text,$withparents) =@_;3124my@commit_lines=split'\n',$commit_text;3125my%co;31263127pop@commit_lines;# Remove '\0'31283129if(!@commit_lines) {3130return;3131}31323133my$header=shift@commit_lines;3134if($header!~m/^[0-9a-fA-F]{40}/) {3135return;3136}3137($co{'id'},my@parents) =split' ',$header;3138while(my$line=shift@commit_lines) {3139last if$lineeq"\n";3140if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3141$co{'tree'} =$1;3142}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3143push@parents,$1;3144}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3145$co{'author'} = to_utf8($1);3146$co{'author_epoch'} =$2;3147$co{'author_tz'} =$3;3148if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3149$co{'author_name'} =$1;3150$co{'author_email'} =$2;3151}else{3152$co{'author_name'} =$co{'author'};3153}3154}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3155$co{'committer'} = to_utf8($1);3156$co{'committer_epoch'} =$2;3157$co{'committer_tz'} =$3;3158if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3159$co{'committer_name'} =$1;3160$co{'committer_email'} =$2;3161}else{3162$co{'committer_name'} =$co{'committer'};3163}3164}3165}3166if(!defined$co{'tree'}) {3167return;3168};3169$co{'parents'} = \@parents;3170$co{'parent'} =$parents[0];31713172foreachmy$title(@commit_lines) {3173$title=~s/^ //;3174if($titlene"") {3175$co{'title'} = chop_str($title,80,5);3176# remove leading stuff of merges to make the interesting part visible3177if(length($title) >50) {3178$title=~s/^Automatic //;3179$title=~s/^merge (of|with) /Merge ... /i;3180if(length($title) >50) {3181$title=~s/(http|rsync):\/\///;3182}3183if(length($title) >50) {3184$title=~s/(master|www|rsync)\.//;3185}3186if(length($title) >50) {3187$title=~s/kernel.org:?//;3188}3189if(length($title) >50) {3190$title=~s/\/pub\/scm//;3191}3192}3193$co{'title_short'} = chop_str($title,50,5);3194last;3195}3196}3197if(!defined$co{'title'} ||$co{'title'}eq"") {3198$co{'title'} =$co{'title_short'} ='(no commit message)';3199}3200# remove added spaces3201foreachmy$line(@commit_lines) {3202$line=~s/^ //;3203}3204$co{'comment'} = \@commit_lines;32053206my$age=time-$co{'committer_epoch'};3207$co{'age'} =$age;3208$co{'age_string'} = age_string($age);3209my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3210if($age>60*60*24*7*2) {3211$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3212$co{'age_string_age'} =$co{'age_string'};3213}else{3214$co{'age_string_date'} =$co{'age_string'};3215$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3216}3217return%co;3218}32193220sub parse_commit {3221my($commit_id) =@_;3222my%co;32233224local$/="\0";32253226open my$fd,"-|", git_cmd(),"rev-list",3227"--parents",3228"--header",3229"--max-count=1",3230$commit_id,3231"--",3232or die_error(500,"Open git-rev-list failed");3233%co= parse_commit_text(<$fd>,1);3234close$fd;32353236return%co;3237}32383239sub parse_commits {3240my($commit_id,$maxcount,$skip,$filename,@args) =@_;3241my@cos;32423243$maxcount||=1;3244$skip||=0;32453246local$/="\0";32473248open my$fd,"-|", git_cmd(),"rev-list",3249"--header",3250@args,3251("--max-count=".$maxcount),3252("--skip=".$skip),3253@extra_options,3254$commit_id,3255"--",3256($filename? ($filename) : ())3257or die_error(500,"Open git-rev-list failed");3258while(my$line= <$fd>) {3259my%co= parse_commit_text($line);3260push@cos, \%co;3261}3262close$fd;32633264returnwantarray?@cos: \@cos;3265}32663267# parse line of git-diff-tree "raw" output3268sub parse_difftree_raw_line {3269my$line=shift;3270my%res;32713272# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3273# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3274if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3275$res{'from_mode'} =$1;3276$res{'to_mode'} =$2;3277$res{'from_id'} =$3;3278$res{'to_id'} =$4;3279$res{'status'} =$5;3280$res{'similarity'} =$6;3281if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3282($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3283}else{3284$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3285}3286}3287# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3288# combined diff (for merge commit)3289elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3290$res{'nparents'} =length($1);3291$res{'from_mode'} = [split(' ',$2) ];3292$res{'to_mode'} =pop@{$res{'from_mode'}};3293$res{'from_id'} = [split(' ',$3) ];3294$res{'to_id'} =pop@{$res{'from_id'}};3295$res{'status'} = [split('',$4) ];3296$res{'to_file'} = unquote($5);3297}3298# 'c512b523472485aef4fff9e57b229d9d243c967f'3299elsif($line=~m/^([0-9a-fA-F]{40})$/) {3300$res{'commit'} =$1;3301}33023303returnwantarray?%res: \%res;3304}33053306# wrapper: return parsed line of git-diff-tree "raw" output3307# (the argument might be raw line, or parsed info)3308sub parsed_difftree_line {3309my$line_or_ref=shift;33103311if(ref($line_or_ref)eq"HASH") {3312# pre-parsed (or generated by hand)3313return$line_or_ref;3314}else{3315return parse_difftree_raw_line($line_or_ref);3316}3317}33183319# parse line of git-ls-tree output3320sub parse_ls_tree_line {3321my$line=shift;3322my%opts=@_;3323my%res;33243325if($opts{'-l'}) {3326#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3327$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;33283329$res{'mode'} =$1;3330$res{'type'} =$2;3331$res{'hash'} =$3;3332$res{'size'} =$4;3333if($opts{'-z'}) {3334$res{'name'} =$5;3335}else{3336$res{'name'} = unquote($5);3337}3338}else{3339#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3340$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;33413342$res{'mode'} =$1;3343$res{'type'} =$2;3344$res{'hash'} =$3;3345if($opts{'-z'}) {3346$res{'name'} =$4;3347}else{3348$res{'name'} = unquote($4);3349}3350}33513352returnwantarray?%res: \%res;3353}33543355# generates _two_ hashes, references to which are passed as 2 and 3 argument3356sub parse_from_to_diffinfo {3357my($diffinfo,$from,$to,@parents) =@_;33583359if($diffinfo->{'nparents'}) {3360# combined diff3361$from->{'file'} = [];3362$from->{'href'} = [];3363 fill_from_file_info($diffinfo,@parents)3364unlessexists$diffinfo->{'from_file'};3365for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3366$from->{'file'}[$i] =3367defined$diffinfo->{'from_file'}[$i] ?3368$diffinfo->{'from_file'}[$i] :3369$diffinfo->{'to_file'};3370if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3371$from->{'href'}[$i] = href(action=>"blob",3372 hash_base=>$parents[$i],3373 hash=>$diffinfo->{'from_id'}[$i],3374 file_name=>$from->{'file'}[$i]);3375}else{3376$from->{'href'}[$i] =undef;3377}3378}3379}else{3380# ordinary (not combined) diff3381$from->{'file'} =$diffinfo->{'from_file'};3382if($diffinfo->{'status'}ne"A") {# not new (added) file3383$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3384 hash=>$diffinfo->{'from_id'},3385 file_name=>$from->{'file'});3386}else{3387delete$from->{'href'};3388}3389}33903391$to->{'file'} =$diffinfo->{'to_file'};3392if(!is_deleted($diffinfo)) {# file exists in result3393$to->{'href'} = href(action=>"blob", hash_base=>$hash,3394 hash=>$diffinfo->{'to_id'},3395 file_name=>$to->{'file'});3396}else{3397delete$to->{'href'};3398}3399}34003401## ......................................................................3402## parse to array of hashes functions34033404sub git_get_heads_list {3405my($limit,@classes) =@_;3406@classes= ('heads')unless@classes;3407my@patterns=map{"refs/$_"}@classes;3408my@headslist;34093410open my$fd,'-|', git_cmd(),'for-each-ref',3411($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3412'--format=%(objectname) %(refname) %(subject)%00%(committer)',3413@patterns3414orreturn;3415while(my$line= <$fd>) {3416my%ref_item;34173418chomp$line;3419my($refinfo,$committerinfo) =split(/\0/,$line);3420my($hash,$name,$title) =split(' ',$refinfo,3);3421my($committer,$epoch,$tz) =3422($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3423$ref_item{'fullname'} =$name;3424$name=~s!^refs/(?:head|remote)s/!!;34253426$ref_item{'name'} =$name;3427$ref_item{'id'} =$hash;3428$ref_item{'title'} =$title||'(no commit message)';3429$ref_item{'epoch'} =$epoch;3430if($epoch) {3431$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3432}else{3433$ref_item{'age'} ="unknown";3434}34353436push@headslist, \%ref_item;3437}3438close$fd;34393440returnwantarray?@headslist: \@headslist;3441}34423443sub git_get_tags_list {3444my$limit=shift;3445my@tagslist;34463447open my$fd,'-|', git_cmd(),'for-each-ref',3448($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3449'--format=%(objectname) %(objecttype) %(refname) '.3450'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3451'refs/tags'3452orreturn;3453while(my$line= <$fd>) {3454my%ref_item;34553456chomp$line;3457my($refinfo,$creatorinfo) =split(/\0/,$line);3458my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3459my($creator,$epoch,$tz) =3460($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3461$ref_item{'fullname'} =$name;3462$name=~s!^refs/tags/!!;34633464$ref_item{'type'} =$type;3465$ref_item{'id'} =$id;3466$ref_item{'name'} =$name;3467if($typeeq"tag") {3468$ref_item{'subject'} =$title;3469$ref_item{'reftype'} =$reftype;3470$ref_item{'refid'} =$refid;3471}else{3472$ref_item{'reftype'} =$type;3473$ref_item{'refid'} =$id;3474}34753476if($typeeq"tag"||$typeeq"commit") {3477$ref_item{'epoch'} =$epoch;3478if($epoch) {3479$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3480}else{3481$ref_item{'age'} ="unknown";3482}3483}34843485push@tagslist, \%ref_item;3486}3487close$fd;34883489returnwantarray?@tagslist: \@tagslist;3490}34913492## ----------------------------------------------------------------------3493## filesystem-related functions34943495sub get_file_owner {3496my$path=shift;34973498my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3499my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3500if(!defined$gcos) {3501returnundef;3502}3503my$owner=$gcos;3504$owner=~s/[,;].*$//;3505return to_utf8($owner);3506}35073508# assume that file exists3509sub insert_file {3510my$filename=shift;35113512open my$fd,'<',$filename;3513print map{ to_utf8($_) } <$fd>;3514close$fd;3515}35163517## ......................................................................3518## mimetype related functions35193520sub mimetype_guess_file {3521my$filename=shift;3522my$mimemap=shift;3523-r $mimemaporreturnundef;35243525my%mimemap;3526open(my$mh,'<',$mimemap)orreturnundef;3527while(<$mh>) {3528next ifm/^#/;# skip comments3529my($mimetype,$exts) =split(/\t+/);3530if(defined$exts) {3531my@exts=split(/\s+/,$exts);3532foreachmy$ext(@exts) {3533$mimemap{$ext} =$mimetype;3534}3535}3536}3537close($mh);35383539$filename=~/\.([^.]*)$/;3540return$mimemap{$1};3541}35423543sub mimetype_guess {3544my$filename=shift;3545my$mime;3546$filename=~/\./orreturnundef;35473548if($mimetypes_file) {3549my$file=$mimetypes_file;3550if($file!~m!^/!) {# if it is relative path3551# it is relative to project3552$file="$projectroot/$project/$file";3553}3554$mime= mimetype_guess_file($filename,$file);3555}3556$mime||= mimetype_guess_file($filename,'/etc/mime.types');3557return$mime;3558}35593560sub blob_mimetype {3561my$fd=shift;3562my$filename=shift;35633564if($filename) {3565my$mime= mimetype_guess($filename);3566$mimeandreturn$mime;3567}35683569# just in case3570return$default_blob_plain_mimetypeunless$fd;35713572if(-T $fd) {3573return'text/plain';3574}elsif(!$filename) {3575return'application/octet-stream';3576}elsif($filename=~m/\.png$/i) {3577return'image/png';3578}elsif($filename=~m/\.gif$/i) {3579return'image/gif';3580}elsif($filename=~m/\.jpe?g$/i) {3581return'image/jpeg';3582}else{3583return'application/octet-stream';3584}3585}35863587sub blob_contenttype {3588my($fd,$file_name,$type) =@_;35893590$type||= blob_mimetype($fd,$file_name);3591if($typeeq'text/plain'&&defined$default_text_plain_charset) {3592$type.="; charset=$default_text_plain_charset";3593}35943595return$type;3596}35973598# guess file syntax for syntax highlighting; return undef if no highlighting3599# the name of syntax can (in the future) depend on syntax highlighter used3600sub guess_file_syntax {3601my($highlight,$mimetype,$file_name) =@_;3602returnundefunless($highlight&&defined$file_name);3603my$basename= basename($file_name,'.in');3604return$highlight_basename{$basename}3605ifexists$highlight_basename{$basename};36063607$basename=~/\.([^.]*)$/;3608my$ext=$1orreturnundef;3609return$highlight_ext{$ext}3610ifexists$highlight_ext{$ext};36113612returnundef;3613}36143615# run highlighter and return FD of its output,3616# or return original FD if no highlighting3617sub run_highlighter {3618my($fd,$highlight,$syntax) =@_;3619return$fdunless($highlight&&defined$syntax);36203621close$fd;3622open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3623 quote_command($highlight_bin).3624" --replace-tabs=8 --fragment --syntax$syntax|"3625or die_error(500,"Couldn't open file or run syntax highlighter");3626return$fd;3627}36283629## ======================================================================3630## functions printing HTML: header, footer, error page36313632sub get_page_title {3633my$title= to_utf8($site_name);36343635return$titleunless(defined$project);3636$title.=" - ". to_utf8($project);36373638return$titleunless(defined$action);3639$title.="/$action";# $action is US-ASCII (7bit ASCII)36403641return$titleunless(defined$file_name);3642$title.=" - ". esc_path($file_name);3643if($actioneq"tree"&&$file_name!~ m|/$|) {3644$title.="/";3645}36463647return$title;3648}36493650sub print_feed_meta {3651if(defined$project) {3652my%href_params= get_feed_info();3653if(!exists$href_params{'-title'}) {3654$href_params{'-title'} ='log';3655}36563657foreachmy$format(qw(RSS Atom)) {3658my$type=lc($format);3659my%link_attr= (3660'-rel'=>'alternate',3661'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3662'-type'=>"application/$type+xml"3663);36643665$href_params{'action'} =$type;3666$link_attr{'-href'} = href(%href_params);3667print"<link ".3668"rel=\"$link_attr{'-rel'}\"".3669"title=\"$link_attr{'-title'}\"".3670"href=\"$link_attr{'-href'}\"".3671"type=\"$link_attr{'-type'}\"".3672"/>\n";36733674$href_params{'extra_options'} ='--no-merges';3675$link_attr{'-href'} = href(%href_params);3676$link_attr{'-title'} .=' (no merges)';3677print"<link ".3678"rel=\"$link_attr{'-rel'}\"".3679"title=\"$link_attr{'-title'}\"".3680"href=\"$link_attr{'-href'}\"".3681"type=\"$link_attr{'-type'}\"".3682"/>\n";3683}36843685}else{3686printf('<link rel="alternate" title="%sprojects list" '.3687'href="%s" type="text/plain; charset=utf-8" />'."\n",3688 esc_attr($site_name), href(project=>undef, action=>"project_index"));3689printf('<link rel="alternate" title="%sprojects feeds" '.3690'href="%s" type="text/x-opml" />'."\n",3691 esc_attr($site_name), href(project=>undef, action=>"opml"));3692}3693}36943695sub git_header_html {3696my$status=shift||"200 OK";3697my$expires=shift;3698my%opts=@_;36993700my$title= get_page_title();3701my$content_type;3702# require explicit support from the UA if we are to send the page as3703# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3704# we have to do this because MSIE sometimes globs '*/*', pretending to3705# support xhtml+xml but choking when it gets what it asked for.3706if(defined$cgi->http('HTTP_ACCEPT') &&3707$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3708$cgi->Accept('application/xhtml+xml') !=0) {3709$content_type='application/xhtml+xml';3710}else{3711$content_type='text/html';3712}3713print$cgi->header(-type=>$content_type, -charset =>'utf-8',3714-status=>$status, -expires =>$expires)3715unless($opts{'-no_http_header'});3716my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3717print<<EOF;3718<?xml version="1.0" encoding="utf-8"?>3719<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3720<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3721<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3722<!-- git core binaries version$git_version-->3723<head>3724<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3725<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3726<meta name="robots" content="index, nofollow"/>3727<title>$title</title>3728EOF3729# the stylesheet, favicon etc urls won't work correctly with path_info3730# unless we set the appropriate base URL3731if($ENV{'PATH_INFO'}) {3732print"<base href=\"".esc_url($base_url)."\"/>\n";3733}3734# print out each stylesheet that exist, providing backwards capability3735# for those people who defined $stylesheet in a config file3736if(defined$stylesheet) {3737print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3738}else{3739foreachmy$stylesheet(@stylesheets) {3740next unless$stylesheet;3741print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3742}3743}3744 print_feed_meta()3745if($statuseq'200 OK');3746if(defined$favicon) {3747printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);3748}37493750print"</head>\n".3751"<body>\n";37523753if(defined$site_header&& -f $site_header) {3754 insert_file($site_header);3755}37563757print"<div class=\"page_header\">\n";3758if(defined$logo) {3759print$cgi->a({-href => esc_url($logo_url),3760-title =>$logo_label},3761$cgi->img({-src => esc_url($logo),3762-width =>72, -height =>27,3763-alt =>"git",3764-class=>"logo"}));3765}3766print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3767if(defined$project) {3768print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3769if(defined$action) {3770my$action_print=$action;3771if(defined$opts{-action_extra}) {3772$action_print=$cgi->a({-href => href(action=>$action)},3773$action);3774}3775print" /$action_print";3776}3777if(defined$opts{-action_extra}) {3778print" /$opts{-action_extra}";3779}3780print"\n";3781}3782print"</div>\n";37833784my$have_search= gitweb_check_feature('search');3785if(defined$project&&$have_search) {3786if(!defined$searchtext) {3787$searchtext="";3788}3789my$search_hash;3790if(defined$hash_base) {3791$search_hash=$hash_base;3792}elsif(defined$hash) {3793$search_hash=$hash;3794}else{3795$search_hash="HEAD";3796}3797my$action=$my_uri;3798my$use_pathinfo= gitweb_check_feature('pathinfo');3799if($use_pathinfo) {3800$action.="/".esc_url($project);3801}3802print$cgi->startform(-method=>"get", -action =>$action) .3803"<div class=\"search\">\n".3804(!$use_pathinfo&&3805$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3806$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3807$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3808$cgi->popup_menu(-name =>'st', -default=>'commit',3809-values=> ['commit','grep','author','committer','pickaxe']) .3810$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3811" search:\n",3812$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3813"<span title=\"Extended regular expression\">".3814$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3815-checked =>$search_use_regexp) .3816"</span>".3817"</div>".3818$cgi->end_form() ."\n";3819}3820}38213822sub git_footer_html {3823my$feed_class='rss_logo';38243825print"<div class=\"page_footer\">\n";3826if(defined$project) {3827my$descr= git_get_project_description($project);3828if(defined$descr) {3829print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3830}38313832my%href_params= get_feed_info();3833if(!%href_params) {3834$feed_class.=' generic';3835}3836$href_params{'-title'} ||='log';38373838foreachmy$format(qw(RSS Atom)) {3839$href_params{'action'} =lc($format);3840print$cgi->a({-href => href(%href_params),3841-title =>"$href_params{'-title'}$formatfeed",3842-class=>$feed_class},$format)."\n";3843}38443845}else{3846print$cgi->a({-href => href(project=>undef, action=>"opml"),3847-class=>$feed_class},"OPML") ." ";3848print$cgi->a({-href => href(project=>undef, action=>"project_index"),3849-class=>$feed_class},"TXT") ."\n";3850}3851print"</div>\n";# class="page_footer"38523853if(defined$t0&& gitweb_check_feature('timed')) {3854print"<div id=\"generating_info\">\n";3855print'This page took '.3856'<span id="generating_time" class="time_span">'.3857 tv_interval($t0, [ gettimeofday() ]).3858' seconds </span>'.3859' and '.3860'<span id="generating_cmd">'.3861$number_of_git_cmds.3862'</span> git commands '.3863" to generate.\n";3864print"</div>\n";# class="page_footer"3865}38663867if(defined$site_footer&& -f $site_footer) {3868 insert_file($site_footer);3869}38703871print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;3872if(defined$action&&3873$actioneq'blame_incremental') {3874print qq!<script type="text/javascript">\n!.3875 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.3876 qq!"!. href() .qq!");\n!.3877 qq!</script>\n!;3878}elsif(gitweb_check_feature('javascript-actions')) {3879print qq!<script type="text/javascript">\n!.3880 qq!window.onload = fixLinks;\n!.3881 qq!</script>\n!;3882}38833884print"</body>\n".3885"</html>";3886}38873888# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])3889# Example: die_error(404, 'Hash not found')3890# By convention, use the following status codes (as defined in RFC 2616):3891# 400: Invalid or missing CGI parameters, or3892# requested object exists but has wrong type.3893# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3894# this server or project.3895# 404: Requested object/revision/project doesn't exist.3896# 500: The server isn't configured properly, or3897# an internal error occurred (e.g. failed assertions caused by bugs), or3898# an unknown error occurred (e.g. the git binary died unexpectedly).3899# 503: The server is currently unavailable (because it is overloaded,3900# or down for maintenance). Generally, this is a temporary state.3901sub die_error {3902my$status=shift||500;3903my$error= esc_html(shift) ||"Internal Server Error";3904my$extra=shift;3905my%opts=@_;39063907my%http_responses= (3908400=>'400 Bad Request',3909403=>'403 Forbidden',3910404=>'404 Not Found',3911500=>'500 Internal Server Error',3912503=>'503 Service Unavailable',3913);3914 git_header_html($http_responses{$status},undef,%opts);3915print<<EOF;3916<div class="page_body">3917<br /><br />3918$status-$error3919<br />3920EOF3921if(defined$extra) {3922print"<hr />\n".3923"$extra\n";3924}3925print"</div>\n";39263927 git_footer_html();3928goto DONE_GITWEB3929unless($opts{'-error_handler'});3930}39313932## ----------------------------------------------------------------------3933## functions printing or outputting HTML: navigation39343935sub git_print_page_nav {3936my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;3937$extra=''if!defined$extra;# pager or formats39383939my@navs=qw(summary shortlog log commit commitdiff tree);3940if($suppress) {3941@navs=grep{$_ne$suppress}@navs;3942}39433944my%arg=map{$_=> {action=>$_} }@navs;3945if(defined$head) {3946for(qw(commit commitdiff)) {3947$arg{$_}{'hash'} =$head;3948}3949if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {3950for(qw(shortlog log)) {3951$arg{$_}{'hash'} =$head;3952}3953}3954}39553956$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;3957$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;39583959my@actions= gitweb_get_feature('actions');3960my%repl= (3961'%'=>'%',3962'n'=>$project,# project name3963'f'=>$git_dir,# project path within filesystem3964'h'=>$treehead||'',# current hash ('h' parameter)3965'b'=>$treebase||'',# hash base ('hb' parameter)3966);3967while(@actions) {3968my($label,$link,$pos) =splice(@actions,0,3);3969# insert3970@navs=map{$_eq$pos? ($_,$label) :$_}@navs;3971# munch munch3972$link=~s/%([%nfhb])/$repl{$1}/g;3973$arg{$label}{'_href'} =$link;3974}39753976print"<div class=\"page_nav\">\n".3977(join" | ",3978map{$_eq$current?3979$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")3980}@navs);3981print"<br/>\n$extra<br/>\n".3982"</div>\n";3983}39843985# returns a submenu for the nagivation of the refs views (tags, heads,3986# remotes) with the current view disabled and the remotes view only3987# available if the feature is enabled3988sub format_ref_views {3989my($current) =@_;3990my@ref_views=qw{tags heads};3991push@ref_views,'remotes'if gitweb_check_feature('remote_heads');3992returnjoin" | ",map{3993$_eq$current?$_:3994$cgi->a({-href => href(action=>$_)},$_)3995}@ref_views3996}39973998sub format_paging_nav {3999my($action,$page,$has_next_link) =@_;4000my$paging_nav;400140024003if($page>0) {4004$paging_nav.=4005$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4006" ⋅ ".4007$cgi->a({-href => href(-replay=>1, page=>$page-1),4008-accesskey =>"p", -title =>"Alt-p"},"prev");4009}else{4010$paging_nav.="first ⋅ prev";4011}40124013if($has_next_link) {4014$paging_nav.=" ⋅ ".4015$cgi->a({-href => href(-replay=>1, page=>$page+1),4016-accesskey =>"n", -title =>"Alt-n"},"next");4017}else{4018$paging_nav.=" ⋅ next";4019}40204021return$paging_nav;4022}40234024## ......................................................................4025## functions printing or outputting HTML: div40264027sub git_print_header_div {4028my($action,$title,$hash,$hash_base) =@_;4029my%args= ();40304031$args{'action'} =$action;4032$args{'hash'} =$hashif$hash;4033$args{'hash_base'} =$hash_baseif$hash_base;40344035print"<div class=\"header\">\n".4036$cgi->a({-href => href(%args), -class=>"title"},4037$title?$title:$action) .4038"\n</div>\n";4039}40404041sub format_repo_url {4042my($name,$url) =@_;4043return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4044}40454046# Group output by placing it in a DIV element and adding a header.4047# Options for start_div() can be provided by passing a hash reference as the4048# first parameter to the function.4049# Options to git_print_header_div() can be provided by passing an array4050# reference. This must follow the options to start_div if they are present.4051# The content can be a scalar, which is output as-is, a scalar reference, which4052# is output after html escaping, an IO handle passed either as *handle or4053# *handle{IO}, or a function reference. In the latter case all following4054# parameters will be taken as argument to the content function call.4055sub git_print_section {4056my($div_args,$header_args,$content);4057my$arg=shift;4058if(ref($arg)eq'HASH') {4059$div_args=$arg;4060$arg=shift;4061}4062if(ref($arg)eq'ARRAY') {4063$header_args=$arg;4064$arg=shift;4065}4066$content=$arg;40674068print$cgi->start_div($div_args);4069 git_print_header_div(@$header_args);40704071if(ref($content)eq'CODE') {4072$content->(@_);4073}elsif(ref($content)eq'SCALAR') {4074print esc_html($$content);4075}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4076print<$content>;4077}elsif(!ref($content) &&defined($content)) {4078print$content;4079}40804081print$cgi->end_div;4082}40834084sub print_local_time {4085print format_local_time(@_);4086}40874088sub format_local_time {4089my$localtime='';4090my%date=@_;4091if($date{'hour_local'} <6) {4092$localtime.=sprintf(" (<span class=\"atnight\">%02d:%02d</span>%s)",4093$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});4094}else{4095$localtime.=sprintf(" (%02d:%02d%s)",4096$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});4097}40984099return$localtime;4100}41014102# Outputs the author name and date in long form4103sub git_print_authorship {4104my$co=shift;4105my%opts=@_;4106my$tag=$opts{-tag} ||'div';4107my$author=$co->{'author_name'};41084109my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4110print"<$tagclass=\"author_date\">".4111 format_search_author($author,"author", esc_html($author)) .4112" [$ad{'rfc2822'}";4113 print_local_time(%ad)if($opts{-localtime});4114print"]". git_get_avatar($co->{'author_email'}, -pad_before =>1)4115."</$tag>\n";4116}41174118# Outputs table rows containing the full author or committer information,4119# in the format expected for 'commit' view (& similar).4120# Parameters are a commit hash reference, followed by the list of people4121# to output information for. If the list is empty it defaults to both4122# author and committer.4123sub git_print_authorship_rows {4124my$co=shift;4125# too bad we can't use @people = @_ || ('author', 'committer')4126my@people=@_;4127@people= ('author','committer')unless@people;4128foreachmy$who(@people) {4129my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4130print"<tr><td>$who</td><td>".4131 format_search_author($co->{"${who}_name"},$who,4132 esc_html($co->{"${who}_name"})) ." ".4133 format_search_author($co->{"${who}_email"},$who,4134 esc_html("<".$co->{"${who}_email"} .">")) .4135"</td><td rowspan=\"2\">".4136 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4137"</td></tr>\n".4138"<tr>".4139"<td></td><td>$wd{'rfc2822'}";4140 print_local_time(%wd);4141print"</td>".4142"</tr>\n";4143}4144}41454146sub git_print_page_path {4147my$name=shift;4148my$type=shift;4149my$hb=shift;415041514152print"<div class=\"page_path\">";4153print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4154-title =>'tree root'}, to_utf8("[$project]"));4155print" / ";4156if(defined$name) {4157my@dirname=split'/',$name;4158my$basename=pop@dirname;4159my$fullname='';41604161foreachmy$dir(@dirname) {4162$fullname.= ($fullname?'/':'') .$dir;4163print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4164 hash_base=>$hb),4165-title =>$fullname}, esc_path($dir));4166print" / ";4167}4168if(defined$type&&$typeeq'blob') {4169print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4170 hash_base=>$hb),4171-title =>$name}, esc_path($basename));4172}elsif(defined$type&&$typeeq'tree') {4173print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4174 hash_base=>$hb),4175-title =>$name}, esc_path($basename));4176print" / ";4177}else{4178print esc_path($basename);4179}4180}4181print"<br/></div>\n";4182}41834184sub git_print_log {4185my$log=shift;4186my%opts=@_;41874188if($opts{'-remove_title'}) {4189# remove title, i.e. first line of log4190shift@$log;4191}4192# remove leading empty lines4193while(defined$log->[0] &&$log->[0]eq"") {4194shift@$log;4195}41964197# print log4198my$signoff=0;4199my$empty=0;4200foreachmy$line(@$log) {4201if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {4202$signoff=1;4203$empty=0;4204if(!$opts{'-remove_signoff'}) {4205print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4206next;4207}else{4208# remove signoff lines4209next;4210}4211}else{4212$signoff=0;4213}42144215# print only one empty line4216# do not print empty line after signoff4217if($lineeq"") {4218next if($empty||$signoff);4219$empty=1;4220}else{4221$empty=0;4222}42234224print format_log_line_html($line) ."<br/>\n";4225}42264227if($opts{'-final_empty_line'}) {4228# end with single empty line4229print"<br/>\n"unless$empty;4230}4231}42324233# return link target (what link points to)4234sub git_get_link_target {4235my$hash=shift;4236my$link_target;42374238# read link4239open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4240orreturn;4241{4242local$/=undef;4243$link_target= <$fd>;4244}4245close$fd4246orreturn;42474248return$link_target;4249}42504251# given link target, and the directory (basedir) the link is in,4252# return target of link relative to top directory (top tree);4253# return undef if it is not possible (including absolute links).4254sub normalize_link_target {4255my($link_target,$basedir) =@_;42564257# absolute symlinks (beginning with '/') cannot be normalized4258return if(substr($link_target,0,1)eq'/');42594260# normalize link target to path from top (root) tree (dir)4261my$path;4262if($basedir) {4263$path=$basedir.'/'.$link_target;4264}else{4265# we are in top (root) tree (dir)4266$path=$link_target;4267}42684269# remove //, /./, and /../4270my@path_parts;4271foreachmy$part(split('/',$path)) {4272# discard '.' and ''4273next if(!$part||$parteq'.');4274# handle '..'4275if($parteq'..') {4276if(@path_parts) {4277pop@path_parts;4278}else{4279# link leads outside repository (outside top dir)4280return;4281}4282}else{4283push@path_parts,$part;4284}4285}4286$path=join('/',@path_parts);42874288return$path;4289}42904291# print tree entry (row of git_tree), but without encompassing <tr> element4292sub git_print_tree_entry {4293my($t,$basedir,$hash_base,$have_blame) =@_;42944295my%base_key= ();4296$base_key{'hash_base'} =$hash_baseifdefined$hash_base;42974298# The format of a table row is: mode list link. Where mode is4299# the mode of the entry, list is the name of the entry, an href,4300# and link is the action links of the entry.43014302print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4303if(exists$t->{'size'}) {4304print"<td class=\"size\">$t->{'size'}</td>\n";4305}4306if($t->{'type'}eq"blob") {4307print"<td class=\"list\">".4308$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4309 file_name=>"$basedir$t->{'name'}",%base_key),4310-class=>"list"}, esc_path($t->{'name'}));4311if(S_ISLNK(oct$t->{'mode'})) {4312my$link_target= git_get_link_target($t->{'hash'});4313if($link_target) {4314my$norm_target= normalize_link_target($link_target,$basedir);4315if(defined$norm_target) {4316print" -> ".4317$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4318 file_name=>$norm_target),4319-title =>$norm_target}, esc_path($link_target));4320}else{4321print" -> ". esc_path($link_target);4322}4323}4324}4325print"</td>\n";4326print"<td class=\"link\">";4327print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4328 file_name=>"$basedir$t->{'name'}",%base_key)},4329"blob");4330if($have_blame) {4331print" | ".4332$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4333 file_name=>"$basedir$t->{'name'}",%base_key)},4334"blame");4335}4336if(defined$hash_base) {4337print" | ".4338$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4339 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4340"history");4341}4342print" | ".4343$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4344 file_name=>"$basedir$t->{'name'}")},4345"raw");4346print"</td>\n";43474348}elsif($t->{'type'}eq"tree") {4349print"<td class=\"list\">";4350print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4351 file_name=>"$basedir$t->{'name'}",4352%base_key)},4353 esc_path($t->{'name'}));4354print"</td>\n";4355print"<td class=\"link\">";4356print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4357 file_name=>"$basedir$t->{'name'}",4358%base_key)},4359"tree");4360if(defined$hash_base) {4361print" | ".4362$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4363 file_name=>"$basedir$t->{'name'}")},4364"history");4365}4366print"</td>\n";4367}else{4368# unknown object: we can only present history for it4369# (this includes 'commit' object, i.e. submodule support)4370print"<td class=\"list\">".4371 esc_path($t->{'name'}) .4372"</td>\n";4373print"<td class=\"link\">";4374if(defined$hash_base) {4375print$cgi->a({-href => href(action=>"history",4376 hash_base=>$hash_base,4377 file_name=>"$basedir$t->{'name'}")},4378"history");4379}4380print"</td>\n";4381}4382}43834384## ......................................................................4385## functions printing large fragments of HTML43864387# get pre-image filenames for merge (combined) diff4388sub fill_from_file_info {4389my($diff,@parents) =@_;43904391$diff->{'from_file'} = [ ];4392$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4393for(my$i=0;$i<$diff->{'nparents'};$i++) {4394if($diff->{'status'}[$i]eq'R'||4395$diff->{'status'}[$i]eq'C') {4396$diff->{'from_file'}[$i] =4397 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4398}4399}44004401return$diff;4402}44034404# is current raw difftree line of file deletion4405sub is_deleted {4406my$diffinfo=shift;44074408return$diffinfo->{'to_id'}eq('0' x 40);4409}44104411# does patch correspond to [previous] difftree raw line4412# $diffinfo - hashref of parsed raw diff format4413# $patchinfo - hashref of parsed patch diff format4414# (the same keys as in $diffinfo)4415sub is_patch_split {4416my($diffinfo,$patchinfo) =@_;44174418returndefined$diffinfo&&defined$patchinfo4419&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4420}442144224423sub git_difftree_body {4424my($difftree,$hash,@parents) =@_;4425my($parent) =$parents[0];4426my$have_blame= gitweb_check_feature('blame');4427print"<div class=\"list_head\">\n";4428if($#{$difftree} >10) {4429print(($#{$difftree} +1) ." files changed:\n");4430}4431print"</div>\n";44324433print"<table class=\"".4434(@parents>1?"combined ":"") .4435"diff_tree\">\n";44364437# header only for combined diff in 'commitdiff' view4438my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4439if($has_header) {4440# table header4441print"<thead><tr>\n".4442"<th></th><th></th>\n";# filename, patchN link4443for(my$i=0;$i<@parents;$i++) {4444my$par=$parents[$i];4445print"<th>".4446$cgi->a({-href => href(action=>"commitdiff",4447 hash=>$hash, hash_parent=>$par),4448-title =>'commitdiff to parent number '.4449($i+1) .': '.substr($par,0,7)},4450$i+1) .4451" </th>\n";4452}4453print"</tr></thead>\n<tbody>\n";4454}44554456my$alternate=1;4457my$patchno=0;4458foreachmy$line(@{$difftree}) {4459my$diff= parsed_difftree_line($line);44604461if($alternate) {4462print"<tr class=\"dark\">\n";4463}else{4464print"<tr class=\"light\">\n";4465}4466$alternate^=1;44674468if(exists$diff->{'nparents'}) {# combined diff44694470 fill_from_file_info($diff,@parents)4471unlessexists$diff->{'from_file'};44724473if(!is_deleted($diff)) {4474# file exists in the result (child) commit4475print"<td>".4476$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4477 file_name=>$diff->{'to_file'},4478 hash_base=>$hash),4479-class=>"list"}, esc_path($diff->{'to_file'})) .4480"</td>\n";4481}else{4482print"<td>".4483 esc_path($diff->{'to_file'}) .4484"</td>\n";4485}44864487if($actioneq'commitdiff') {4488# link to patch4489$patchno++;4490print"<td class=\"link\">".4491$cgi->a({-href => href(-anchor=>"patch$patchno")},4492"patch") .4493" | ".4494"</td>\n";4495}44964497my$has_history=0;4498my$not_deleted=0;4499for(my$i=0;$i<$diff->{'nparents'};$i++) {4500my$hash_parent=$parents[$i];4501my$from_hash=$diff->{'from_id'}[$i];4502my$from_path=$diff->{'from_file'}[$i];4503my$status=$diff->{'status'}[$i];45044505$has_history||= ($statusne'A');4506$not_deleted||= ($statusne'D');45074508if($statuseq'A') {4509print"<td class=\"link\"align=\"right\"> | </td>\n";4510}elsif($statuseq'D') {4511print"<td class=\"link\">".4512$cgi->a({-href => href(action=>"blob",4513 hash_base=>$hash,4514 hash=>$from_hash,4515 file_name=>$from_path)},4516"blob". ($i+1)) .4517" | </td>\n";4518}else{4519if($diff->{'to_id'}eq$from_hash) {4520print"<td class=\"link nochange\">";4521}else{4522print"<td class=\"link\">";4523}4524print$cgi->a({-href => href(action=>"blobdiff",4525 hash=>$diff->{'to_id'},4526 hash_parent=>$from_hash,4527 hash_base=>$hash,4528 hash_parent_base=>$hash_parent,4529 file_name=>$diff->{'to_file'},4530 file_parent=>$from_path)},4531"diff". ($i+1)) .4532" | </td>\n";4533}4534}45354536print"<td class=\"link\">";4537if($not_deleted) {4538print$cgi->a({-href => href(action=>"blob",4539 hash=>$diff->{'to_id'},4540 file_name=>$diff->{'to_file'},4541 hash_base=>$hash)},4542"blob");4543print" | "if($has_history);4544}4545if($has_history) {4546print$cgi->a({-href => href(action=>"history",4547 file_name=>$diff->{'to_file'},4548 hash_base=>$hash)},4549"history");4550}4551print"</td>\n";45524553print"</tr>\n";4554next;# instead of 'else' clause, to avoid extra indent4555}4556# else ordinary diff45574558my($to_mode_oct,$to_mode_str,$to_file_type);4559my($from_mode_oct,$from_mode_str,$from_file_type);4560if($diff->{'to_mode'}ne('0' x 6)) {4561$to_mode_oct=oct$diff->{'to_mode'};4562if(S_ISREG($to_mode_oct)) {# only for regular file4563$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4564}4565$to_file_type= file_type($diff->{'to_mode'});4566}4567if($diff->{'from_mode'}ne('0' x 6)) {4568$from_mode_oct=oct$diff->{'from_mode'};4569if(S_ISREG($from_mode_oct)) {# only for regular file4570$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4571}4572$from_file_type= file_type($diff->{'from_mode'});4573}45744575if($diff->{'status'}eq"A") {# created4576my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4577$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4578$mode_chng.="]</span>";4579print"<td>";4580print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4581 hash_base=>$hash, file_name=>$diff->{'file'}),4582-class=>"list"}, esc_path($diff->{'file'}));4583print"</td>\n";4584print"<td>$mode_chng</td>\n";4585print"<td class=\"link\">";4586if($actioneq'commitdiff') {4587# link to patch4588$patchno++;4589print$cgi->a({-href => href(-anchor=>"patch$patchno")},4590"patch") .4591" | ";4592}4593print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4594 hash_base=>$hash, file_name=>$diff->{'file'})},4595"blob");4596print"</td>\n";45974598}elsif($diff->{'status'}eq"D") {# deleted4599my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4600print"<td>";4601print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4602 hash_base=>$parent, file_name=>$diff->{'file'}),4603-class=>"list"}, esc_path($diff->{'file'}));4604print"</td>\n";4605print"<td>$mode_chng</td>\n";4606print"<td class=\"link\">";4607if($actioneq'commitdiff') {4608# link to patch4609$patchno++;4610print$cgi->a({-href => href(-anchor=>"patch$patchno")},4611"patch") .4612" | ";4613}4614print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4615 hash_base=>$parent, file_name=>$diff->{'file'})},4616"blob") ." | ";4617if($have_blame) {4618print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4619 file_name=>$diff->{'file'})},4620"blame") ." | ";4621}4622print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4623 file_name=>$diff->{'file'})},4624"history");4625print"</td>\n";46264627}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4628my$mode_chnge="";4629if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4630$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4631if($from_file_typene$to_file_type) {4632$mode_chnge.=" from$from_file_typeto$to_file_type";4633}4634if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4635if($from_mode_str&&$to_mode_str) {4636$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4637}elsif($to_mode_str) {4638$mode_chnge.=" mode:$to_mode_str";4639}4640}4641$mode_chnge.="]</span>\n";4642}4643print"<td>";4644print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4645 hash_base=>$hash, file_name=>$diff->{'file'}),4646-class=>"list"}, esc_path($diff->{'file'}));4647print"</td>\n";4648print"<td>$mode_chnge</td>\n";4649print"<td class=\"link\">";4650if($actioneq'commitdiff') {4651# link to patch4652$patchno++;4653print$cgi->a({-href => href(-anchor=>"patch$patchno")},4654"patch") .4655" | ";4656}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4657# "commit" view and modified file (not onlu mode changed)4658print$cgi->a({-href => href(action=>"blobdiff",4659 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4660 hash_base=>$hash, hash_parent_base=>$parent,4661 file_name=>$diff->{'file'})},4662"diff") .4663" | ";4664}4665print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4666 hash_base=>$hash, file_name=>$diff->{'file'})},4667"blob") ." | ";4668if($have_blame) {4669print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4670 file_name=>$diff->{'file'})},4671"blame") ." | ";4672}4673print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4674 file_name=>$diff->{'file'})},4675"history");4676print"</td>\n";46774678}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4679my%status_name= ('R'=>'moved','C'=>'copied');4680my$nstatus=$status_name{$diff->{'status'}};4681my$mode_chng="";4682if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4683# mode also for directories, so we cannot use $to_mode_str4684$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4685}4686print"<td>".4687$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4688 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4689-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4690"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4691$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4692 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4693-class=>"list"}, esc_path($diff->{'from_file'})) .4694" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4695"<td class=\"link\">";4696if($actioneq'commitdiff') {4697# link to patch4698$patchno++;4699print$cgi->a({-href => href(-anchor=>"patch$patchno")},4700"patch") .4701" | ";4702}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4703# "commit" view and modified file (not only pure rename or copy)4704print$cgi->a({-href => href(action=>"blobdiff",4705 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4706 hash_base=>$hash, hash_parent_base=>$parent,4707 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4708"diff") .4709" | ";4710}4711print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4712 hash_base=>$parent, file_name=>$diff->{'to_file'})},4713"blob") ." | ";4714if($have_blame) {4715print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4716 file_name=>$diff->{'to_file'})},4717"blame") ." | ";4718}4719print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4720 file_name=>$diff->{'to_file'})},4721"history");4722print"</td>\n";47234724}# we should not encounter Unmerged (U) or Unknown (X) status4725print"</tr>\n";4726}4727print"</tbody>"if$has_header;4728print"</table>\n";4729}47304731sub git_patchset_body {4732my($fd,$difftree,$hash,@hash_parents) =@_;4733my($hash_parent) =$hash_parents[0];47344735my$is_combined= (@hash_parents>1);4736my$patch_idx=0;4737my$patch_number=0;4738my$patch_line;4739my$diffinfo;4740my$to_name;4741my(%from,%to);47424743print"<div class=\"patchset\">\n";47444745# skip to first patch4746while($patch_line= <$fd>) {4747chomp$patch_line;47484749last if($patch_line=~m/^diff /);4750}47514752 PATCH:4753while($patch_line) {47544755# parse "git diff" header line4756if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4757# $1 is from_name, which we do not use4758$to_name= unquote($2);4759$to_name=~s!^b/!!;4760}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4761# $1 is 'cc' or 'combined', which we do not use4762$to_name= unquote($2);4763}else{4764$to_name=undef;4765}47664767# check if current patch belong to current raw line4768# and parse raw git-diff line if needed4769if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4770# this is continuation of a split patch4771print"<div class=\"patch cont\">\n";4772}else{4773# advance raw git-diff output if needed4774$patch_idx++ifdefined$diffinfo;47754776# read and prepare patch information4777$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);47784779# compact combined diff output can have some patches skipped4780# find which patch (using pathname of result) we are at now;4781if($is_combined) {4782while($to_namene$diffinfo->{'to_file'}) {4783print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4784 format_diff_cc_simplified($diffinfo,@hash_parents) .4785"</div>\n";# class="patch"47864787$patch_idx++;4788$patch_number++;47894790last if$patch_idx>$#$difftree;4791$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4792}4793}47944795# modifies %from, %to hashes4796 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);47974798# this is first patch for raw difftree line with $patch_idx index4799# we index @$difftree array from 0, but number patches from 14800print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4801}48024803# git diff header4804#assert($patch_line =~ m/^diff /) if DEBUG;4805#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4806$patch_number++;4807# print "git diff" header4808print format_git_diff_header_line($patch_line,$diffinfo,4809 \%from, \%to);48104811# print extended diff header4812print"<div class=\"diff extended_header\">\n";4813 EXTENDED_HEADER:4814while($patch_line= <$fd>) {4815chomp$patch_line;48164817last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);48184819print format_extended_diff_header_line($patch_line,$diffinfo,4820 \%from, \%to);4821}4822print"</div>\n";# class="diff extended_header"48234824# from-file/to-file diff header4825if(!$patch_line) {4826print"</div>\n";# class="patch"4827last PATCH;4828}4829next PATCH if($patch_line=~m/^diff /);4830#assert($patch_line =~ m/^---/) if DEBUG;48314832my$last_patch_line=$patch_line;4833$patch_line= <$fd>;4834chomp$patch_line;4835#assert($patch_line =~ m/^\+\+\+/) if DEBUG;48364837print format_diff_from_to_header($last_patch_line,$patch_line,4838$diffinfo, \%from, \%to,4839@hash_parents);48404841# the patch itself4842 LINE:4843while($patch_line= <$fd>) {4844chomp$patch_line;48454846next PATCH if($patch_line=~m/^diff /);48474848print format_diff_line($patch_line, \%from, \%to);4849}48504851}continue{4852print"</div>\n";# class="patch"4853}48544855# for compact combined (--cc) format, with chunk and patch simplification4856# the patchset might be empty, but there might be unprocessed raw lines4857for(++$patch_idxif$patch_number>0;4858$patch_idx<@$difftree;4859++$patch_idx) {4860# read and prepare patch information4861$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);48624863# generate anchor for "patch" links in difftree / whatchanged part4864print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4865 format_diff_cc_simplified($diffinfo,@hash_parents) .4866"</div>\n";# class="patch"48674868$patch_number++;4869}48704871if($patch_number==0) {4872if(@hash_parents>1) {4873print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4874}else{4875print"<div class=\"diff nodifferences\">No differences found</div>\n";4876}4877}48784879print"</div>\n";# class="patchset"4880}48814882# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .48834884# fills project list info (age, description, owner, forks) for each4885# project in the list, removing invalid projects from returned list4886# NOTE: modifies $projlist, but does not remove entries from it4887sub fill_project_list_info {4888my$projlist=shift;4889my@projects;48904891my$show_ctags= gitweb_check_feature('ctags');4892 PROJECT:4893foreachmy$pr(@$projlist) {4894my(@activity) = git_get_last_activity($pr->{'path'});4895unless(@activity) {4896next PROJECT;4897}4898($pr->{'age'},$pr->{'age_string'}) =@activity;4899if(!defined$pr->{'descr'}) {4900my$descr= git_get_project_description($pr->{'path'}) ||"";4901$descr= to_utf8($descr);4902$pr->{'descr_long'} =$descr;4903$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);4904}4905if(!defined$pr->{'owner'}) {4906$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";4907}4908if($show_ctags) {4909$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});4910}4911push@projects,$pr;4912}49134914return@projects;4915}49164917sub sort_projects_list {4918my($projlist,$order) =@_;4919my@projects;49204921my%order_info= (4922 project => { key =>'path', type =>'str'},4923 descr => { key =>'descr_long', type =>'str'},4924 owner => { key =>'owner', type =>'str'},4925 age => { key =>'age', type =>'num'}4926);4927my$oi=$order_info{$order};4928return@$projlistunlessdefined$oi;4929if($oi->{'type'}eq'str') {4930@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@$projlist;4931}else{4932@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@$projlist;4933}49344935return@projects;4936}49374938# print 'sort by' <th> element, generating 'sort by $name' replay link4939# if that order is not selected4940sub print_sort_th {4941print format_sort_th(@_);4942}49434944sub format_sort_th {4945my($name,$order,$header) =@_;4946my$sort_th="";4947$header||=ucfirst($name);49484949if($ordereq$name) {4950$sort_th.="<th>$header</th>\n";4951}else{4952$sort_th.="<th>".4953$cgi->a({-href => href(-replay=>1, order=>$name),4954-class=>"header"},$header) .4955"</th>\n";4956}49574958return$sort_th;4959}49604961sub git_project_list_body {4962# actually uses global variable $project4963my($projlist,$order,$from,$to,$extra,$no_header) =@_;4964my@projects=@$projlist;49654966my$check_forks= gitweb_check_feature('forks');4967my$show_ctags= gitweb_check_feature('ctags');4968my$tagfilter=$show_ctags?$cgi->param('by_tag') :undef;4969$check_forks=undef4970if($tagfilter||$searchtext);49714972# filtering out forks before filling info allows to do less work4973@projects= filter_forks_from_projects_list(\@projects)4974if($check_forks);4975@projects= fill_project_list_info(\@projects);4976# searching projects require filling to be run before it4977@projects= search_projects_list(\@projects,4978'searchtext'=>$searchtext,4979'tagfilter'=>$tagfilter)4980if($tagfilter||$searchtext);49814982$order||=$default_projects_order;4983$from=0unlessdefined$from;4984$to=$#projectsif(!defined$to||$#projects<$to);49854986# short circuit4987if($from>$to) {4988print"<center>\n".4989"<b>No such projects found</b><br />\n".4990"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".4991"</center>\n<br />\n";4992return;4993}49944995@projects= sort_projects_list(\@projects,$order);49964997if($show_ctags) {4998my$ctags= git_gather_all_ctags(\@projects);4999my$cloud= git_populate_project_tagcloud($ctags);5000print git_show_project_tagcloud($cloud,64);5001}50025003print"<table class=\"project_list\">\n";5004unless($no_header) {5005print"<tr>\n";5006if($check_forks) {5007print"<th></th>\n";5008}5009 print_sort_th('project',$order,'Project');5010 print_sort_th('descr',$order,'Description');5011 print_sort_th('owner',$order,'Owner');5012 print_sort_th('age',$order,'Last Change');5013print"<th></th>\n".# for links5014"</tr>\n";5015}5016my$alternate=1;5017for(my$i=$from;$i<=$to;$i++) {5018my$pr=$projects[$i];50195020if($alternate) {5021print"<tr class=\"dark\">\n";5022}else{5023print"<tr class=\"light\">\n";5024}5025$alternate^=1;50265027if($check_forks) {5028print"<td>";5029if($pr->{'forks'}) {5030my$nforks=scalar@{$pr->{'forks'}};5031if($nforks>0) {5032print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5033-title =>"$nforksforks"},"+");5034}else{5035print$cgi->span({-title =>"$nforksforks"},"+");5036}5037}5038print"</td>\n";5039}5040print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5041-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".5042"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5043-class=>"list", -title =>$pr->{'descr_long'}},5044 esc_html($pr->{'descr'})) ."</td>\n".5045"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5046print"<td class=\"". age_class($pr->{'age'}) ."\">".5047(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".5048"<td class=\"link\">".5049$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5050$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5051$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5052$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5053($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5054"</td>\n".5055"</tr>\n";5056}5057if(defined$extra) {5058print"<tr>\n";5059if($check_forks) {5060print"<td></td>\n";5061}5062print"<td colspan=\"5\">$extra</td>\n".5063"</tr>\n";5064}5065print"</table>\n";5066}50675068sub git_log_body {5069# uses global variable $project5070my($commitlist,$from,$to,$refs,$extra) =@_;50715072$from=0unlessdefined$from;5073$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);50745075for(my$i=0;$i<=$to;$i++) {5076my%co= %{$commitlist->[$i]};5077next if!%co;5078my$commit=$co{'id'};5079my$ref= format_ref_marker($refs,$commit);5080 git_print_header_div('commit',5081"<span class=\"age\">$co{'age_string'}</span>".5082 esc_html($co{'title'}) .$ref,5083$commit);5084print"<div class=\"title_text\">\n".5085"<div class=\"log_link\">\n".5086$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5087" | ".5088$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5089" | ".5090$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5091"<br/>\n".5092"</div>\n";5093 git_print_authorship(\%co, -tag =>'span');5094print"<br/>\n</div>\n";50955096print"<div class=\"log_body\">\n";5097 git_print_log($co{'comment'}, -final_empty_line=>1);5098print"</div>\n";5099}5100if($extra) {5101print"<div class=\"page_nav\">\n";5102print"$extra\n";5103print"</div>\n";5104}5105}51065107sub git_shortlog_body {5108# uses global variable $project5109my($commitlist,$from,$to,$refs,$extra) =@_;51105111$from=0unlessdefined$from;5112$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);51135114print"<table class=\"shortlog\">\n";5115my$alternate=1;5116for(my$i=$from;$i<=$to;$i++) {5117my%co= %{$commitlist->[$i]};5118my$commit=$co{'id'};5119my$ref= format_ref_marker($refs,$commit);5120if($alternate) {5121print"<tr class=\"dark\">\n";5122}else{5123print"<tr class=\"light\">\n";5124}5125$alternate^=1;5126# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5127print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5128 format_author_html('td', \%co,10) ."<td>";5129print format_subject_html($co{'title'},$co{'title_short'},5130 href(action=>"commit", hash=>$commit),$ref);5131print"</td>\n".5132"<td class=\"link\">".5133$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5134$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5135$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5136my$snapshot_links= format_snapshot_links($commit);5137if(defined$snapshot_links) {5138print" | ".$snapshot_links;5139}5140print"</td>\n".5141"</tr>\n";5142}5143if(defined$extra) {5144print"<tr>\n".5145"<td colspan=\"4\">$extra</td>\n".5146"</tr>\n";5147}5148print"</table>\n";5149}51505151sub git_history_body {5152# Warning: assumes constant type (blob or tree) during history5153my($commitlist,$from,$to,$refs,$extra,5154$file_name,$file_hash,$ftype) =@_;51555156$from=0unlessdefined$from;5157$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});51585159print"<table class=\"history\">\n";5160my$alternate=1;5161for(my$i=$from;$i<=$to;$i++) {5162my%co= %{$commitlist->[$i]};5163if(!%co) {5164next;5165}5166my$commit=$co{'id'};51675168my$ref= format_ref_marker($refs,$commit);51695170if($alternate) {5171print"<tr class=\"dark\">\n";5172}else{5173print"<tr class=\"light\">\n";5174}5175$alternate^=1;5176print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5177# shortlog: format_author_html('td', \%co, 10)5178 format_author_html('td', \%co,15,3) ."<td>";5179# originally git_history used chop_str($co{'title'}, 50)5180print format_subject_html($co{'title'},$co{'title_short'},5181 href(action=>"commit", hash=>$commit),$ref);5182print"</td>\n".5183"<td class=\"link\">".5184$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5185$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");51865187if($ftypeeq'blob') {5188my$blob_current=$file_hash;5189my$blob_parent= git_get_hash_by_path($commit,$file_name);5190if(defined$blob_current&&defined$blob_parent&&5191$blob_currentne$blob_parent) {5192print" | ".5193$cgi->a({-href => href(action=>"blobdiff",5194 hash=>$blob_current, hash_parent=>$blob_parent,5195 hash_base=>$hash_base, hash_parent_base=>$commit,5196 file_name=>$file_name)},5197"diff to current");5198}5199}5200print"</td>\n".5201"</tr>\n";5202}5203if(defined$extra) {5204print"<tr>\n".5205"<td colspan=\"4\">$extra</td>\n".5206"</tr>\n";5207}5208print"</table>\n";5209}52105211sub git_tags_body {5212# uses global variable $project5213my($taglist,$from,$to,$extra) =@_;5214$from=0unlessdefined$from;5215$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);52165217print"<table class=\"tags\">\n";5218my$alternate=1;5219for(my$i=$from;$i<=$to;$i++) {5220my$entry=$taglist->[$i];5221my%tag=%$entry;5222my$comment=$tag{'subject'};5223my$comment_short;5224if(defined$comment) {5225$comment_short= chop_str($comment,30,5);5226}5227if($alternate) {5228print"<tr class=\"dark\">\n";5229}else{5230print"<tr class=\"light\">\n";5231}5232$alternate^=1;5233if(defined$tag{'age'}) {5234print"<td><i>$tag{'age'}</i></td>\n";5235}else{5236print"<td></td>\n";5237}5238print"<td>".5239$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5240-class=>"list name"}, esc_html($tag{'name'})) .5241"</td>\n".5242"<td>";5243if(defined$comment) {5244print format_subject_html($comment,$comment_short,5245 href(action=>"tag", hash=>$tag{'id'}));5246}5247print"</td>\n".5248"<td class=\"selflink\">";5249if($tag{'type'}eq"tag") {5250print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");5251}else{5252print" ";5253}5254print"</td>\n".5255"<td class=\"link\">"." | ".5256$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});5257if($tag{'reftype'}eq"commit") {5258print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .5259" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");5260}elsif($tag{'reftype'}eq"blob") {5261print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");5262}5263print"</td>\n".5264"</tr>";5265}5266if(defined$extra) {5267print"<tr>\n".5268"<td colspan=\"5\">$extra</td>\n".5269"</tr>\n";5270}5271print"</table>\n";5272}52735274sub git_heads_body {5275# uses global variable $project5276my($headlist,$head,$from,$to,$extra) =@_;5277$from=0unlessdefined$from;5278$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);52795280print"<table class=\"heads\">\n";5281my$alternate=1;5282for(my$i=$from;$i<=$to;$i++) {5283my$entry=$headlist->[$i];5284my%ref=%$entry;5285my$curr=$ref{'id'}eq$head;5286if($alternate) {5287print"<tr class=\"dark\">\n";5288}else{5289print"<tr class=\"light\">\n";5290}5291$alternate^=1;5292print"<td><i>$ref{'age'}</i></td>\n".5293($curr?"<td class=\"current_head\">":"<td>") .5294$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),5295-class=>"list name"},esc_html($ref{'name'})) .5296"</td>\n".5297"<td class=\"link\">".5298$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".5299$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".5300$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .5301"</td>\n".5302"</tr>";5303}5304if(defined$extra) {5305print"<tr>\n".5306"<td colspan=\"3\">$extra</td>\n".5307"</tr>\n";5308}5309print"</table>\n";5310}53115312# Display a single remote block5313sub git_remote_block {5314my($remote,$rdata,$limit,$head) =@_;53155316my$heads=$rdata->{'heads'};5317my$fetch=$rdata->{'fetch'};5318my$push=$rdata->{'push'};53195320my$urls_table="<table class=\"projects_list\">\n";53215322if(defined$fetch) {5323if($fetcheq$push) {5324$urls_table.= format_repo_url("URL",$fetch);5325}else{5326$urls_table.= format_repo_url("Fetch URL",$fetch);5327$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;5328}5329}elsif(defined$push) {5330$urls_table.= format_repo_url("Push URL",$push);5331}else{5332$urls_table.= format_repo_url("","No remote URL");5333}53345335$urls_table.="</table>\n";53365337my$dots;5338if(defined$limit&&$limit<@$heads) {5339$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");5340}53415342print$urls_table;5343 git_heads_body($heads,$head,0,$limit,$dots);5344}53455346# Display a list of remote names with the respective fetch and push URLs5347sub git_remotes_list {5348my($remotedata,$limit) =@_;5349print"<table class=\"heads\">\n";5350my$alternate=1;5351my@remotes=sort keys%$remotedata;53525353my$limited=$limit&&$limit<@remotes;53545355$#remotes=$limit-1if$limited;53565357while(my$remote=shift@remotes) {5358my$rdata=$remotedata->{$remote};5359my$fetch=$rdata->{'fetch'};5360my$push=$rdata->{'push'};5361if($alternate) {5362print"<tr class=\"dark\">\n";5363}else{5364print"<tr class=\"light\">\n";5365}5366$alternate^=1;5367print"<td>".5368$cgi->a({-href=> href(action=>'remotes', hash=>$remote),5369-class=>"list name"},esc_html($remote)) .5370"</td>";5371print"<td class=\"link\">".5372(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .5373" | ".5374(defined$push?$cgi->a({-href=>$push},"push") :"push") .5375"</td>";53765377print"</tr>\n";5378}53795380if($limited) {5381print"<tr>\n".5382"<td colspan=\"3\">".5383$cgi->a({-href => href(action=>"remotes")},"...") .5384"</td>\n"."</tr>\n";5385}53865387print"</table>";5388}53895390# Display remote heads grouped by remote, unless there are too many5391# remotes, in which case we only display the remote names5392sub git_remotes_body {5393my($remotedata,$limit,$head) =@_;5394if($limitand$limit<keys%$remotedata) {5395 git_remotes_list($remotedata,$limit);5396}else{5397 fill_remote_heads($remotedata);5398while(my($remote,$rdata) =each%$remotedata) {5399 git_print_section({-class=>"remote", -id=>$remote},5400["remotes",$remote,$remote],sub{5401 git_remote_block($remote,$rdata,$limit,$head);5402});5403}5404}5405}54065407sub git_search_grep_body {5408my($commitlist,$from,$to,$extra) =@_;5409$from=0unlessdefined$from;5410$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);54115412print"<table class=\"commit_search\">\n";5413my$alternate=1;5414for(my$i=$from;$i<=$to;$i++) {5415my%co= %{$commitlist->[$i]};5416if(!%co) {5417next;5418}5419my$commit=$co{'id'};5420if($alternate) {5421print"<tr class=\"dark\">\n";5422}else{5423print"<tr class=\"light\">\n";5424}5425$alternate^=1;5426print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5427 format_author_html('td', \%co,15,5) .5428"<td>".5429$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5430-class=>"list subject"},5431 chop_and_escape_str($co{'title'},50) ."<br/>");5432my$comment=$co{'comment'};5433foreachmy$line(@$comment) {5434if($line=~m/^(.*?)($search_regexp)(.*)$/i) {5435my($lead,$match,$trail) = ($1,$2,$3);5436$match= chop_str($match,70,5,'center');5437my$contextlen=int((80-length($match))/2);5438$contextlen=30if($contextlen>30);5439$lead= chop_str($lead,$contextlen,10,'left');5440$trail= chop_str($trail,$contextlen,10,'right');54415442$lead= esc_html($lead);5443$match= esc_html($match);5444$trail= esc_html($trail);54455446print"$lead<span class=\"match\">$match</span>$trail<br />";5447}5448}5449print"</td>\n".5450"<td class=\"link\">".5451$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .5452" | ".5453$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .5454" | ".5455$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");5456print"</td>\n".5457"</tr>\n";5458}5459if(defined$extra) {5460print"<tr>\n".5461"<td colspan=\"3\">$extra</td>\n".5462"</tr>\n";5463}5464print"</table>\n";5465}54665467## ======================================================================5468## ======================================================================5469## actions54705471sub git_project_list {5472my$order=$input_params{'order'};5473if(defined$order&&$order!~m/none|project|descr|owner|age/) {5474 die_error(400,"Unknown order parameter");5475}54765477my@list= git_get_projects_list();5478if(!@list) {5479 die_error(404,"No projects found");5480}54815482 git_header_html();5483if(defined$home_text&& -f $home_text) {5484print"<div class=\"index_include\">\n";5485 insert_file($home_text);5486print"</div>\n";5487}5488print$cgi->startform(-method=>"get") .5489"<p class=\"projsearch\">Search:\n".5490$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".5491"</p>".5492$cgi->end_form() ."\n";5493 git_project_list_body(\@list,$order);5494 git_footer_html();5495}54965497sub git_forks {5498my$order=$input_params{'order'};5499if(defined$order&&$order!~m/none|project|descr|owner|age/) {5500 die_error(400,"Unknown order parameter");5501}55025503my@list= git_get_projects_list($project);5504if(!@list) {5505 die_error(404,"No forks found");5506}55075508 git_header_html();5509 git_print_page_nav('','');5510 git_print_header_div('summary',"$projectforks");5511 git_project_list_body(\@list,$order);5512 git_footer_html();5513}55145515sub git_project_index {5516my@projects= git_get_projects_list();5517if(!@projects) {5518 die_error(404,"No projects found");5519}55205521print$cgi->header(5522-type =>'text/plain',5523-charset =>'utf-8',5524-content_disposition =>'inline; filename="index.aux"');55255526foreachmy$pr(@projects) {5527if(!exists$pr->{'owner'}) {5528$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");5529}55305531my($path,$owner) = ($pr->{'path'},$pr->{'owner'});5532# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '5533$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5534$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5535$path=~s/ /\+/g;5536$owner=~s/ /\+/g;55375538print"$path$owner\n";5539}5540}55415542sub git_summary {5543my$descr= git_get_project_description($project) ||"none";5544my%co= parse_commit("HEAD");5545my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();5546my$head=$co{'id'};5547my$remote_heads= gitweb_check_feature('remote_heads');55485549my$owner= git_get_project_owner($project);55505551my$refs= git_get_references();5552# These get_*_list functions return one more to allow us to see if5553# there are more ...5554my@taglist= git_get_tags_list(16);5555my@headlist= git_get_heads_list(16);5556my%remotedata=$remote_heads? git_get_remotes_list() : ();5557my@forklist;5558my$check_forks= gitweb_check_feature('forks');55595560if($check_forks) {5561# find forks of a project5562@forklist= git_get_projects_list($project);5563# filter out forks of forks5564@forklist= filter_forks_from_projects_list(\@forklist)5565if(@forklist);5566}55675568 git_header_html();5569 git_print_page_nav('summary','',$head);55705571print"<div class=\"title\"> </div>\n";5572print"<table class=\"projects_list\">\n".5573"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".5574"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";5575if(defined$cd{'rfc2822'}) {5576print"<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";5577}55785579# use per project git URL list in $projectroot/$project/cloneurl5580# or make project git URL from git base URL and project name5581my$url_tag="URL";5582my@url_list= git_get_project_url_list($project);5583@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;5584foreachmy$git_url(@url_list) {5585next unless$git_url;5586print format_repo_url($url_tag,$git_url);5587$url_tag="";5588}55895590# Tag cloud5591my$show_ctags= gitweb_check_feature('ctags');5592if($show_ctags) {5593my$ctags= git_get_project_ctags($project);5594if(%$ctags) {5595# without ability to add tags, don't show if there are none5596my$cloud= git_populate_project_tagcloud($ctags);5597print"<tr id=\"metadata_ctags\">".5598"<td>content tags</td>".5599"<td>".git_show_project_tagcloud($cloud,48)."</td>".5600"</tr>\n";5601}5602}56035604print"</table>\n";56055606# If XSS prevention is on, we don't include README.html.5607# TODO: Allow a readme in some safe format.5608if(!$prevent_xss&& -s "$projectroot/$project/README.html") {5609print"<div class=\"title\">readme</div>\n".5610"<div class=\"readme\">\n";5611 insert_file("$projectroot/$project/README.html");5612print"\n</div>\n";# class="readme"5613}56145615# we need to request one more than 16 (0..15) to check if5616# those 16 are all5617my@commitlist=$head? parse_commits($head,17) : ();5618if(@commitlist) {5619 git_print_header_div('shortlog');5620 git_shortlog_body(\@commitlist,0,15,$refs,5621$#commitlist<=15?undef:5622$cgi->a({-href => href(action=>"shortlog")},"..."));5623}56245625if(@taglist) {5626 git_print_header_div('tags');5627 git_tags_body(\@taglist,0,15,5628$#taglist<=15?undef:5629$cgi->a({-href => href(action=>"tags")},"..."));5630}56315632if(@headlist) {5633 git_print_header_div('heads');5634 git_heads_body(\@headlist,$head,0,15,5635$#headlist<=15?undef:5636$cgi->a({-href => href(action=>"heads")},"..."));5637}56385639if(%remotedata) {5640 git_print_header_div('remotes');5641 git_remotes_body(\%remotedata,15,$head);5642}56435644if(@forklist) {5645 git_print_header_div('forks');5646 git_project_list_body(\@forklist,'age',0,15,5647$#forklist<=15?undef:5648$cgi->a({-href => href(action=>"forks")},"..."),5649'no_header');5650}56515652 git_footer_html();5653}56545655sub git_tag {5656my%tag= parse_tag($hash);56575658if(!%tag) {5659 die_error(404,"Unknown tag object");5660}56615662my$head= git_get_head_hash($project);5663 git_header_html();5664 git_print_page_nav('','',$head,undef,$head);5665 git_print_header_div('commit', esc_html($tag{'name'}),$hash);5666print"<div class=\"title_text\">\n".5667"<table class=\"object_header\">\n".5668"<tr>\n".5669"<td>object</td>\n".5670"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5671$tag{'object'}) ."</td>\n".5672"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5673$tag{'type'}) ."</td>\n".5674"</tr>\n";5675if(defined($tag{'author'})) {5676 git_print_authorship_rows(\%tag,'author');5677}5678print"</table>\n\n".5679"</div>\n";5680print"<div class=\"page_body\">";5681my$comment=$tag{'comment'};5682foreachmy$line(@$comment) {5683chomp$line;5684print esc_html($line, -nbsp=>1) ."<br/>\n";5685}5686print"</div>\n";5687 git_footer_html();5688}56895690sub git_blame_common {5691my$format=shift||'porcelain';5692if($formateq'porcelain'&&$cgi->param('js')) {5693$format='incremental';5694$action='blame_incremental';# for page title etc5695}56965697# permissions5698 gitweb_check_feature('blame')5699or die_error(403,"Blame view not allowed");57005701# error checking5702 die_error(400,"No file name given")unless$file_name;5703$hash_base||= git_get_head_hash($project);5704 die_error(404,"Couldn't find base commit")unless$hash_base;5705my%co= parse_commit($hash_base)5706or die_error(404,"Commit not found");5707my$ftype="blob";5708if(!defined$hash) {5709$hash= git_get_hash_by_path($hash_base,$file_name,"blob")5710or die_error(404,"Error looking up file");5711}else{5712$ftype= git_get_type($hash);5713if($ftype!~"blob") {5714 die_error(400,"Object is not a blob");5715}5716}57175718my$fd;5719if($formateq'incremental') {5720# get file contents (as base)5721open$fd,"-|", git_cmd(),'cat-file','blob',$hash5722or die_error(500,"Open git-cat-file failed");5723}elsif($formateq'data') {5724# run git-blame --incremental5725open$fd,"-|", git_cmd(),"blame","--incremental",5726$hash_base,"--",$file_name5727or die_error(500,"Open git-blame --incremental failed");5728}else{5729# run git-blame --porcelain5730open$fd,"-|", git_cmd(),"blame",'-p',5731$hash_base,'--',$file_name5732or die_error(500,"Open git-blame --porcelain failed");5733}57345735# incremental blame data returns early5736if($formateq'data') {5737print$cgi->header(5738-type=>"text/plain", -charset =>"utf-8",5739-status=>"200 OK");5740local$| =1;# output autoflush5741printwhile<$fd>;5742close$fd5743or print"ERROR$!\n";57445745print'END';5746if(defined$t0&& gitweb_check_feature('timed')) {5747print' '.5748 tv_interval($t0, [ gettimeofday() ]).5749' '.$number_of_git_cmds;5750}5751print"\n";57525753return;5754}57555756# page header5757 git_header_html();5758my$formats_nav=5759$cgi->a({-href => href(action=>"blob", -replay=>1)},5760"blob") .5761" | ";5762if($formateq'incremental') {5763$formats_nav.=5764$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},5765"blame") ." (non-incremental)";5766}else{5767$formats_nav.=5768$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},5769"blame") ." (incremental)";5770}5771$formats_nav.=5772" | ".5773$cgi->a({-href => href(action=>"history", -replay=>1)},5774"history") .5775" | ".5776$cgi->a({-href => href(action=>$action, file_name=>$file_name)},5777"HEAD");5778 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5779 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5780 git_print_page_path($file_name,$ftype,$hash_base);57815782# page body5783if($formateq'incremental') {5784print"<noscript>\n<div class=\"error\"><center><b>\n".5785"This page requires JavaScript to run.\nUse ".5786$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},5787'this page').5788" instead.\n".5789"</b></center></div>\n</noscript>\n";57905791print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;5792}57935794print qq!<div class="page_body">\n!;5795print qq!<div id="progress_info">.../ ...</div>\n!5796if($formateq'incremental');5797print qq!<table id="blame_table"class="blame" width="100%">\n!.5798#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.5799 qq!<thead>\n!.5800 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.5801 qq!</thead>\n!.5802 qq!<tbody>\n!;58035804my@rev_color=qw(light dark);5805my$num_colors=scalar(@rev_color);5806my$current_color=0;58075808if($formateq'incremental') {5809my$color_class=$rev_color[$current_color];58105811#contents of a file5812my$linenr=0;5813 LINE:5814while(my$line= <$fd>) {5815chomp$line;5816$linenr++;58175818print qq!<tr id="l$linenr"class="$color_class">!.5819 qq!<td class="sha1"><a href=""> </a></td>!.5820 qq!<td class="linenr">!.5821 qq!<a class="linenr" href="">$linenr</a></td>!;5822print qq!<td class="pre">! . esc_html($line) ."</td>\n";5823print qq!</tr>\n!;5824}58255826}else{# porcelain, i.e. ordinary blame5827my%metainfo= ();# saves information about commits58285829# blame data5830 LINE:5831while(my$line= <$fd>) {5832chomp$line;5833# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]5834# no <lines in group> for subsequent lines in group of lines5835my($full_rev,$orig_lineno,$lineno,$group_size) =5836($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);5837if(!exists$metainfo{$full_rev}) {5838$metainfo{$full_rev} = {'nprevious'=>0};5839}5840my$meta=$metainfo{$full_rev};5841my$data;5842while($data= <$fd>) {5843chomp$data;5844last if($data=~s/^\t//);# contents of line5845if($data=~/^(\S+)(?: (.*))?$/) {5846$meta->{$1} =$2unlessexists$meta->{$1};5847}5848if($data=~/^previous /) {5849$meta->{'nprevious'}++;5850}5851}5852my$short_rev=substr($full_rev,0,8);5853my$author=$meta->{'author'};5854my%date=5855 parse_date($meta->{'author-time'},$meta->{'author-tz'});5856my$date=$date{'iso-tz'};5857if($group_size) {5858$current_color= ($current_color+1) %$num_colors;5859}5860my$tr_class=$rev_color[$current_color];5861$tr_class.=' boundary'if(exists$meta->{'boundary'});5862$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);5863$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);5864print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";5865if($group_size) {5866print"<td class=\"sha1\"";5867print" title=\"". esc_html($author) .",$date\"";5868print" rowspan=\"$group_size\""if($group_size>1);5869print">";5870print$cgi->a({-href => href(action=>"commit",5871 hash=>$full_rev,5872 file_name=>$file_name)},5873 esc_html($short_rev));5874if($group_size>=2) {5875my@author_initials= ($author=~/\b([[:upper:]])\B/g);5876if(@author_initials) {5877print"<br />".5878 esc_html(join('',@author_initials));5879# or join('.', ...)5880}5881}5882print"</td>\n";5883}5884# 'previous' <sha1 of parent commit> <filename at commit>5885if(exists$meta->{'previous'} &&5886$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {5887$meta->{'parent'} =$1;5888$meta->{'file_parent'} = unquote($2);5889}5890my$linenr_commit=5891exists($meta->{'parent'}) ?5892$meta->{'parent'} :$full_rev;5893my$linenr_filename=5894exists($meta->{'file_parent'}) ?5895$meta->{'file_parent'} : unquote($meta->{'filename'});5896my$blamed= href(action =>'blame',5897 file_name =>$linenr_filename,5898 hash_base =>$linenr_commit);5899print"<td class=\"linenr\">";5900print$cgi->a({ -href =>"$blamed#l$orig_lineno",5901-class=>"linenr"},5902 esc_html($lineno));5903print"</td>";5904print"<td class=\"pre\">". esc_html($data) ."</td>\n";5905print"</tr>\n";5906}# end while59075908}59095910# footer5911print"</tbody>\n".5912"</table>\n";# class="blame"5913print"</div>\n";# class="blame_body"5914close$fd5915or print"Reading blob failed\n";59165917 git_footer_html();5918}59195920sub git_blame {5921 git_blame_common();5922}59235924sub git_blame_incremental {5925 git_blame_common('incremental');5926}59275928sub git_blame_data {5929 git_blame_common('data');5930}59315932sub git_tags {5933my$head= git_get_head_hash($project);5934 git_header_html();5935 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));5936 git_print_header_div('summary',$project);59375938my@tagslist= git_get_tags_list();5939if(@tagslist) {5940 git_tags_body(\@tagslist);5941}5942 git_footer_html();5943}59445945sub git_heads {5946my$head= git_get_head_hash($project);5947 git_header_html();5948 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));5949 git_print_header_div('summary',$project);59505951my@headslist= git_get_heads_list();5952if(@headslist) {5953 git_heads_body(\@headslist,$head);5954}5955 git_footer_html();5956}59575958# used both for single remote view and for list of all the remotes5959sub git_remotes {5960 gitweb_check_feature('remote_heads')5961or die_error(403,"Remote heads view is disabled");59625963my$head= git_get_head_hash($project);5964my$remote=$input_params{'hash'};59655966my$remotedata= git_get_remotes_list($remote);5967 die_error(500,"Unable to get remote information")unlessdefined$remotedata;59685969unless(%$remotedata) {5970 die_error(404,defined$remote?5971"Remote$remotenot found":5972"No remotes found");5973}59745975 git_header_html(undef,undef, -action_extra =>$remote);5976 git_print_page_nav('','',$head,undef,$head,5977 format_ref_views($remote?'':'remotes'));59785979 fill_remote_heads($remotedata);5980if(defined$remote) {5981 git_print_header_div('remotes',"$remoteremote for$project");5982 git_remote_block($remote,$remotedata->{$remote},undef,$head);5983}else{5984 git_print_header_div('summary',"$projectremotes");5985 git_remotes_body($remotedata,undef,$head);5986}59875988 git_footer_html();5989}59905991sub git_blob_plain {5992my$type=shift;5993my$expires;59945995if(!defined$hash) {5996if(defined$file_name) {5997my$base=$hash_base|| git_get_head_hash($project);5998$hash= git_get_hash_by_path($base,$file_name,"blob")5999or die_error(404,"Cannot find file");6000}else{6001 die_error(400,"No file name defined");6002}6003}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6004# blobs defined by non-textual hash id's can be cached6005$expires="+1d";6006}60076008open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6009or die_error(500,"Open git-cat-file blob '$hash' failed");60106011# content-type (can include charset)6012$type= blob_contenttype($fd,$file_name,$type);60136014# "save as" filename, even when no $file_name is given6015my$save_as="$hash";6016if(defined$file_name) {6017$save_as=$file_name;6018}elsif($type=~m/^text\//) {6019$save_as.='.txt';6020}60216022# With XSS prevention on, blobs of all types except a few known safe6023# ones are served with "Content-Disposition: attachment" to make sure6024# they don't run in our security domain. For certain image types,6025# blob view writes an <img> tag referring to blob_plain view, and we6026# want to be sure not to break that by serving the image as an6027# attachment (though Firefox 3 doesn't seem to care).6028my$sandbox=$prevent_xss&&6029$type!~m!^(?:text/plain|image/(?:gif|png|jpeg))$!;60306031print$cgi->header(6032-type =>$type,6033-expires =>$expires,6034-content_disposition =>6035($sandbox?'attachment':'inline')6036.'; filename="'.$save_as.'"');6037local$/=undef;6038binmode STDOUT,':raw';6039print<$fd>;6040binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6041close$fd;6042}60436044sub git_blob {6045my$expires;60466047if(!defined$hash) {6048if(defined$file_name) {6049my$base=$hash_base|| git_get_head_hash($project);6050$hash= git_get_hash_by_path($base,$file_name,"blob")6051or die_error(404,"Cannot find file");6052}else{6053 die_error(400,"No file name defined");6054}6055}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6056# blobs defined by non-textual hash id's can be cached6057$expires="+1d";6058}60596060my$have_blame= gitweb_check_feature('blame');6061open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6062or die_error(500,"Couldn't cat$file_name,$hash");6063my$mimetype= blob_mimetype($fd,$file_name);6064# use 'blob_plain' (aka 'raw') view for files that cannot be displayed6065if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {6066close$fd;6067return git_blob_plain($mimetype);6068}6069# we can have blame only for text/* mimetype6070$have_blame&&= ($mimetype=~m!^text/!);60716072my$highlight= gitweb_check_feature('highlight');6073my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);6074$fd= run_highlighter($fd,$highlight,$syntax)6075if$syntax;60766077 git_header_html(undef,$expires);6078my$formats_nav='';6079if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6080if(defined$file_name) {6081if($have_blame) {6082$formats_nav.=6083$cgi->a({-href => href(action=>"blame", -replay=>1)},6084"blame") .6085" | ";6086}6087$formats_nav.=6088$cgi->a({-href => href(action=>"history", -replay=>1)},6089"history") .6090" | ".6091$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6092"raw") .6093" | ".6094$cgi->a({-href => href(action=>"blob",6095 hash_base=>"HEAD", file_name=>$file_name)},6096"HEAD");6097}else{6098$formats_nav.=6099$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6100"raw");6101}6102 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6103 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6104}else{6105print"<div class=\"page_nav\">\n".6106"<br/><br/></div>\n".6107"<div class=\"title\">".esc_html($hash)."</div>\n";6108}6109 git_print_page_path($file_name,"blob",$hash_base);6110print"<div class=\"page_body\">\n";6111if($mimetype=~m!^image/!) {6112print qq!<img type="!.esc_attr($mimetype).qq!"!;6113if($file_name) {6114print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;6115}6116print qq! src="! .6117 href(action=>"blob_plain", hash=>$hash,6118 hash_base=>$hash_base, file_name=>$file_name) .6119 qq!"/>\n!;6120}else{6121my$nr;6122while(my$line= <$fd>) {6123chomp$line;6124$nr++;6125$line= untabify($line);6126printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,6127$nr, esc_attr(href(-replay =>1)),$nr,$nr,$syntax?$line: esc_html($line, -nbsp=>1);6128}6129}6130close$fd6131or print"Reading blob failed.\n";6132print"</div>";6133 git_footer_html();6134}61356136sub git_tree {6137if(!defined$hash_base) {6138$hash_base="HEAD";6139}6140if(!defined$hash) {6141if(defined$file_name) {6142$hash= git_get_hash_by_path($hash_base,$file_name,"tree");6143}else{6144$hash=$hash_base;6145}6146}6147 die_error(404,"No such tree")unlessdefined($hash);61486149my$show_sizes= gitweb_check_feature('show-sizes');6150my$have_blame= gitweb_check_feature('blame');61516152my@entries= ();6153{6154local$/="\0";6155open my$fd,"-|", git_cmd(),"ls-tree",'-z',6156($show_sizes?'-l': ()),@extra_options,$hash6157or die_error(500,"Open git-ls-tree failed");6158@entries=map{chomp;$_} <$fd>;6159close$fd6160or die_error(404,"Reading tree failed");6161}61626163my$refs= git_get_references();6164my$ref= format_ref_marker($refs,$hash_base);6165 git_header_html();6166my$basedir='';6167if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6168my@views_nav= ();6169if(defined$file_name) {6170push@views_nav,6171$cgi->a({-href => href(action=>"history", -replay=>1)},6172"history"),6173$cgi->a({-href => href(action=>"tree",6174 hash_base=>"HEAD", file_name=>$file_name)},6175"HEAD"),6176}6177my$snapshot_links= format_snapshot_links($hash);6178if(defined$snapshot_links) {6179# FIXME: Should be available when we have no hash base as well.6180push@views_nav,$snapshot_links;6181}6182 git_print_page_nav('tree','',$hash_base,undef,undef,6183join(' | ',@views_nav));6184 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);6185}else{6186undef$hash_base;6187print"<div class=\"page_nav\">\n";6188print"<br/><br/></div>\n";6189print"<div class=\"title\">".esc_html($hash)."</div>\n";6190}6191if(defined$file_name) {6192$basedir=$file_name;6193if($basedirne''&&substr($basedir, -1)ne'/') {6194$basedir.='/';6195}6196 git_print_page_path($file_name,'tree',$hash_base);6197}6198print"<div class=\"page_body\">\n";6199print"<table class=\"tree\">\n";6200my$alternate=1;6201# '..' (top directory) link if possible6202if(defined$hash_base&&6203defined$file_name&&$file_name=~m![^/]+$!) {6204if($alternate) {6205print"<tr class=\"dark\">\n";6206}else{6207print"<tr class=\"light\">\n";6208}6209$alternate^=1;62106211my$up=$file_name;6212$up=~s!/?[^/]+$!!;6213undef$upunless$up;6214# based on git_print_tree_entry6215print'<td class="mode">'. mode_str('040000') ."</td>\n";6216print'<td class="size"> </td>'."\n"if$show_sizes;6217print'<td class="list">';6218print$cgi->a({-href => href(action=>"tree",6219 hash_base=>$hash_base,6220 file_name=>$up)},6221"..");6222print"</td>\n";6223print"<td class=\"link\"></td>\n";62246225print"</tr>\n";6226}6227foreachmy$line(@entries) {6228my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);62296230if($alternate) {6231print"<tr class=\"dark\">\n";6232}else{6233print"<tr class=\"light\">\n";6234}6235$alternate^=1;62366237 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);62386239print"</tr>\n";6240}6241print"</table>\n".6242"</div>";6243 git_footer_html();6244}62456246sub snapshot_name {6247my($project,$hash) =@_;62486249# path/to/project.git -> project6250# path/to/project/.git -> project6251my$name= to_utf8($project);6252$name=~ s,([^/])/*\.git$,$1,;6253$name= basename($name);6254# sanitize name6255$name=~s/[[:cntrl:]]/?/g;62566257my$ver=$hash;6258if($hash=~/^[0-9a-fA-F]+$/) {6259# shorten SHA-1 hash6260my$full_hash= git_get_full_hash($project,$hash);6261if($full_hash=~/^$hash/&&length($hash) >7) {6262$ver= git_get_short_hash($project,$hash);6263}6264}elsif($hash=~m!^refs/tags/(.*)$!) {6265# tags don't need shortened SHA-1 hash6266$ver=$1;6267}else{6268# branches and other need shortened SHA-1 hash6269if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {6270$ver=$1;6271}6272$ver.='-'. git_get_short_hash($project,$hash);6273}6274# in case of hierarchical branch names6275$ver=~s!/!.!g;62766277# name = project-version_string6278$name="$name-$ver";62796280returnwantarray? ($name,$name) :$name;6281}62826283sub git_snapshot {6284my$format=$input_params{'snapshot_format'};6285if(!@snapshot_fmts) {6286 die_error(403,"Snapshots not allowed");6287}6288# default to first supported snapshot format6289$format||=$snapshot_fmts[0];6290if($format!~m/^[a-z0-9]+$/) {6291 die_error(400,"Invalid snapshot format parameter");6292}elsif(!exists($known_snapshot_formats{$format})) {6293 die_error(400,"Unknown snapshot format");6294}elsif($known_snapshot_formats{$format}{'disabled'}) {6295 die_error(403,"Snapshot format not allowed");6296}elsif(!grep($_eq$format,@snapshot_fmts)) {6297 die_error(403,"Unsupported snapshot format");6298}62996300my$type= git_get_type("$hash^{}");6301if(!$type) {6302 die_error(404,'Object does not exist');6303}elsif($typeeq'blob') {6304 die_error(400,'Object is not a tree-ish');6305}63066307my($name,$prefix) = snapshot_name($project,$hash);6308my$filename="$name$known_snapshot_formats{$format}{'suffix'}";6309my$cmd= quote_command(6310 git_cmd(),'archive',6311"--format=$known_snapshot_formats{$format}{'format'}",6312"--prefix=$prefix/",$hash);6313if(exists$known_snapshot_formats{$format}{'compressor'}) {6314$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});6315}63166317$filename=~s/(["\\])/\\$1/g;6318print$cgi->header(6319-type =>$known_snapshot_formats{$format}{'type'},6320-content_disposition =>'inline; filename="'.$filename.'"',6321-status =>'200 OK');63226323open my$fd,"-|",$cmd6324or die_error(500,"Execute git-archive failed");6325binmode STDOUT,':raw';6326print<$fd>;6327binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6328close$fd;6329}63306331sub git_log_generic {6332my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;63336334my$head= git_get_head_hash($project);6335if(!defined$base) {6336$base=$head;6337}6338if(!defined$page) {6339$page=0;6340}6341my$refs= git_get_references();63426343my$commit_hash=$base;6344if(defined$parent) {6345$commit_hash="$parent..$base";6346}6347my@commitlist=6348 parse_commits($commit_hash,101, (100*$page),6349defined$file_name? ($file_name,"--full-history") : ());63506351my$ftype;6352if(!defined$file_hash&&defined$file_name) {6353# some commits could have deleted file in question,6354# and not have it in tree, but one of them has to have it6355for(my$i=0;$i<@commitlist;$i++) {6356$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);6357last ifdefined$file_hash;6358}6359}6360if(defined$file_hash) {6361$ftype= git_get_type($file_hash);6362}6363if(defined$file_name&& !defined$ftype) {6364 die_error(500,"Unknown type of object");6365}6366my%co;6367if(defined$file_name) {6368%co= parse_commit($base)6369or die_error(404,"Unknown commit object");6370}637163726373my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);6374my$next_link='';6375if($#commitlist>=100) {6376$next_link=6377$cgi->a({-href => href(-replay=>1, page=>$page+1),6378-accesskey =>"n", -title =>"Alt-n"},"next");6379}6380my$patch_max= gitweb_get_feature('patches');6381if($patch_max&& !defined$file_name) {6382if($patch_max<0||@commitlist<=$patch_max) {6383$paging_nav.=" ⋅ ".6384$cgi->a({-href => href(action=>"patches", -replay=>1)},6385"patches");6386}6387}63886389 git_header_html();6390 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);6391if(defined$file_name) {6392 git_print_header_div('commit', esc_html($co{'title'}),$base);6393}else{6394 git_print_header_div('summary',$project)6395}6396 git_print_page_path($file_name,$ftype,$hash_base)6397if(defined$file_name);63986399$body_subr->(\@commitlist,0,99,$refs,$next_link,6400$file_name,$file_hash,$ftype);64016402 git_footer_html();6403}64046405sub git_log {6406 git_log_generic('log', \&git_log_body,6407$hash,$hash_parent);6408}64096410sub git_commit {6411$hash||=$hash_base||"HEAD";6412my%co= parse_commit($hash)6413or die_error(404,"Unknown commit object");64146415my$parent=$co{'parent'};6416my$parents=$co{'parents'};# listref64176418# we need to prepare $formats_nav before any parameter munging6419my$formats_nav;6420if(!defined$parent) {6421# --root commitdiff6422$formats_nav.='(initial)';6423}elsif(@$parents==1) {6424# single parent commit6425$formats_nav.=6426'(parent: '.6427$cgi->a({-href => href(action=>"commit",6428 hash=>$parent)},6429 esc_html(substr($parent,0,7))) .6430')';6431}else{6432# merge commit6433$formats_nav.=6434'(merge: '.6435join(' ',map{6436$cgi->a({-href => href(action=>"commit",6437 hash=>$_)},6438 esc_html(substr($_,0,7)));6439}@$parents) .6440')';6441}6442if(gitweb_check_feature('patches') &&@$parents<=1) {6443$formats_nav.=" | ".6444$cgi->a({-href => href(action=>"patch", -replay=>1)},6445"patch");6446}64476448if(!defined$parent) {6449$parent="--root";6450}6451my@difftree;6452open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",6453@diff_opts,6454(@$parents<=1?$parent:'-c'),6455$hash,"--"6456or die_error(500,"Open git-diff-tree failed");6457@difftree=map{chomp;$_} <$fd>;6458close$fdor die_error(404,"Reading git-diff-tree failed");64596460# non-textual hash id's can be cached6461my$expires;6462if($hash=~m/^[0-9a-fA-F]{40}$/) {6463$expires="+1d";6464}6465my$refs= git_get_references();6466my$ref= format_ref_marker($refs,$co{'id'});64676468 git_header_html(undef,$expires);6469 git_print_page_nav('commit','',6470$hash,$co{'tree'},$hash,6471$formats_nav);64726473if(defined$co{'parent'}) {6474 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);6475}else{6476 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);6477}6478print"<div class=\"title_text\">\n".6479"<table class=\"object_header\">\n";6480 git_print_authorship_rows(\%co);6481print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";6482print"<tr>".6483"<td>tree</td>".6484"<td class=\"sha1\">".6485$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),6486class=>"list"},$co{'tree'}) .6487"</td>".6488"<td class=\"link\">".6489$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},6490"tree");6491my$snapshot_links= format_snapshot_links($hash);6492if(defined$snapshot_links) {6493print" | ".$snapshot_links;6494}6495print"</td>".6496"</tr>\n";64976498foreachmy$par(@$parents) {6499print"<tr>".6500"<td>parent</td>".6501"<td class=\"sha1\">".6502$cgi->a({-href => href(action=>"commit", hash=>$par),6503class=>"list"},$par) .6504"</td>".6505"<td class=\"link\">".6506$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .6507" | ".6508$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .6509"</td>".6510"</tr>\n";6511}6512print"</table>".6513"</div>\n";65146515print"<div class=\"page_body\">\n";6516 git_print_log($co{'comment'});6517print"</div>\n";65186519 git_difftree_body(\@difftree,$hash,@$parents);65206521 git_footer_html();6522}65236524sub git_object {6525# object is defined by:6526# - hash or hash_base alone6527# - hash_base and file_name6528my$type;65296530# - hash or hash_base alone6531if($hash|| ($hash_base&& !defined$file_name)) {6532my$object_id=$hash||$hash_base;65336534open my$fd,"-|", quote_command(6535 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'6536or die_error(404,"Object does not exist");6537$type= <$fd>;6538chomp$type;6539close$fd6540or die_error(404,"Object does not exist");65416542# - hash_base and file_name6543}elsif($hash_base&&defined$file_name) {6544$file_name=~ s,/+$,,;65456546system(git_cmd(),"cat-file",'-e',$hash_base) ==06547or die_error(404,"Base object does not exist");65486549# here errors should not hapen6550open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name6551or die_error(500,"Open git-ls-tree failed");6552my$line= <$fd>;6553close$fd;65546555#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'6556unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {6557 die_error(404,"File or directory for given base does not exist");6558}6559$type=$2;6560$hash=$3;6561}else{6562 die_error(400,"Not enough information to find object");6563}65646565print$cgi->redirect(-uri => href(action=>$type, -full=>1,6566 hash=>$hash, hash_base=>$hash_base,6567 file_name=>$file_name),6568-status =>'302 Found');6569}65706571sub git_blobdiff {6572my$format=shift||'html';65736574my$fd;6575my@difftree;6576my%diffinfo;6577my$expires;65786579# preparing $fd and %diffinfo for git_patchset_body6580# new style URI6581if(defined$hash_base&&defined$hash_parent_base) {6582if(defined$file_name) {6583# read raw output6584open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6585$hash_parent_base,$hash_base,6586"--", (defined$file_parent?$file_parent: ()),$file_name6587or die_error(500,"Open git-diff-tree failed");6588@difftree=map{chomp;$_} <$fd>;6589close$fd6590or die_error(404,"Reading git-diff-tree failed");6591@difftree6592or die_error(404,"Blob diff not found");65936594}elsif(defined$hash&&6595$hash=~/[0-9a-fA-F]{40}/) {6596# try to find filename from $hash65976598# read filtered raw output6599open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6600$hash_parent_base,$hash_base,"--"6601or die_error(500,"Open git-diff-tree failed");6602@difftree=6603# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'6604# $hash == to_id6605grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}6606map{chomp;$_} <$fd>;6607close$fd6608or die_error(404,"Reading git-diff-tree failed");6609@difftree6610or die_error(404,"Blob diff not found");66116612}else{6613 die_error(400,"Missing one of the blob diff parameters");6614}66156616if(@difftree>1) {6617 die_error(400,"Ambiguous blob diff specification");6618}66196620%diffinfo= parse_difftree_raw_line($difftree[0]);6621$file_parent||=$diffinfo{'from_file'} ||$file_name;6622$file_name||=$diffinfo{'to_file'};66236624$hash_parent||=$diffinfo{'from_id'};6625$hash||=$diffinfo{'to_id'};66266627# non-textual hash id's can be cached6628if($hash_base=~m/^[0-9a-fA-F]{40}$/&&6629$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {6630$expires='+1d';6631}66326633# open patch output6634open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6635'-p', ($formateq'html'?"--full-index": ()),6636$hash_parent_base,$hash_base,6637"--", (defined$file_parent?$file_parent: ()),$file_name6638or die_error(500,"Open git-diff-tree failed");6639}66406641# old/legacy style URI -- not generated anymore since 1.4.3.6642if(!%diffinfo) {6643 die_error('404 Not Found',"Missing one of the blob diff parameters")6644}66456646# header6647if($formateq'html') {6648my$formats_nav=6649$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},6650"raw");6651 git_header_html(undef,$expires);6652if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6653 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6654 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6655}else{6656print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";6657print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";6658}6659if(defined$file_name) {6660 git_print_page_path($file_name,"blob",$hash_base);6661}else{6662print"<div class=\"page_path\"></div>\n";6663}66646665}elsif($formateq'plain') {6666print$cgi->header(6667-type =>'text/plain',6668-charset =>'utf-8',6669-expires =>$expires,6670-content_disposition =>'inline; filename="'."$file_name".'.patch"');66716672print"X-Git-Url: ".$cgi->self_url() ."\n\n";66736674}else{6675 die_error(400,"Unknown blobdiff format");6676}66776678# patch6679if($formateq'html') {6680print"<div class=\"page_body\">\n";66816682 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);6683close$fd;66846685print"</div>\n";# class="page_body"6686 git_footer_html();66876688}else{6689while(my$line= <$fd>) {6690$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;6691$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;66926693print$line;66946695last if$line=~m!^\+\+\+!;6696}6697local$/=undef;6698print<$fd>;6699close$fd;6700}6701}67026703sub git_blobdiff_plain {6704 git_blobdiff('plain');6705}67066707sub git_commitdiff {6708my%params=@_;6709my$format=$params{-format} ||'html';67106711my($patch_max) = gitweb_get_feature('patches');6712if($formateq'patch') {6713 die_error(403,"Patch view not allowed")unless$patch_max;6714}67156716$hash||=$hash_base||"HEAD";6717my%co= parse_commit($hash)6718or die_error(404,"Unknown commit object");67196720# choose format for commitdiff for merge6721if(!defined$hash_parent&& @{$co{'parents'}} >1) {6722$hash_parent='--cc';6723}6724# we need to prepare $formats_nav before almost any parameter munging6725my$formats_nav;6726if($formateq'html') {6727$formats_nav=6728$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},6729"raw");6730if($patch_max&& @{$co{'parents'}} <=1) {6731$formats_nav.=" | ".6732$cgi->a({-href => href(action=>"patch", -replay=>1)},6733"patch");6734}67356736if(defined$hash_parent&&6737$hash_parentne'-c'&&$hash_parentne'--cc') {6738# commitdiff with two commits given6739my$hash_parent_short=$hash_parent;6740if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {6741$hash_parent_short=substr($hash_parent,0,7);6742}6743$formats_nav.=6744' (from';6745for(my$i=0;$i< @{$co{'parents'}};$i++) {6746if($co{'parents'}[$i]eq$hash_parent) {6747$formats_nav.=' parent '. ($i+1);6748last;6749}6750}6751$formats_nav.=': '.6752$cgi->a({-href => href(action=>"commitdiff",6753 hash=>$hash_parent)},6754 esc_html($hash_parent_short)) .6755')';6756}elsif(!$co{'parent'}) {6757# --root commitdiff6758$formats_nav.=' (initial)';6759}elsif(scalar@{$co{'parents'}} ==1) {6760# single parent commit6761$formats_nav.=6762' (parent: '.6763$cgi->a({-href => href(action=>"commitdiff",6764 hash=>$co{'parent'})},6765 esc_html(substr($co{'parent'},0,7))) .6766')';6767}else{6768# merge commit6769if($hash_parenteq'--cc') {6770$formats_nav.=' | '.6771$cgi->a({-href => href(action=>"commitdiff",6772 hash=>$hash, hash_parent=>'-c')},6773'combined');6774}else{# $hash_parent eq '-c'6775$formats_nav.=' | '.6776$cgi->a({-href => href(action=>"commitdiff",6777 hash=>$hash, hash_parent=>'--cc')},6778'compact');6779}6780$formats_nav.=6781' (merge: '.6782join(' ',map{6783$cgi->a({-href => href(action=>"commitdiff",6784 hash=>$_)},6785 esc_html(substr($_,0,7)));6786} @{$co{'parents'}} ) .6787')';6788}6789}67906791my$hash_parent_param=$hash_parent;6792if(!defined$hash_parent_param) {6793# --cc for multiple parents, --root for parentless6794$hash_parent_param=6795@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';6796}67976798# read commitdiff6799my$fd;6800my@difftree;6801if($formateq'html') {6802open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6803"--no-commit-id","--patch-with-raw","--full-index",6804$hash_parent_param,$hash,"--"6805or die_error(500,"Open git-diff-tree failed");68066807while(my$line= <$fd>) {6808chomp$line;6809# empty line ends raw part of diff-tree output6810last unless$line;6811push@difftree,scalar parse_difftree_raw_line($line);6812}68136814}elsif($formateq'plain') {6815open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6816'-p',$hash_parent_param,$hash,"--"6817or die_error(500,"Open git-diff-tree failed");6818}elsif($formateq'patch') {6819# For commit ranges, we limit the output to the number of6820# patches specified in the 'patches' feature.6821# For single commits, we limit the output to a single patch,6822# diverging from the git-format-patch default.6823my@commit_spec= ();6824if($hash_parent) {6825if($patch_max>0) {6826push@commit_spec,"-$patch_max";6827}6828push@commit_spec,'-n',"$hash_parent..$hash";6829}else{6830if($params{-single}) {6831push@commit_spec,'-1';6832}else{6833if($patch_max>0) {6834push@commit_spec,"-$patch_max";6835}6836push@commit_spec,"-n";6837}6838push@commit_spec,'--root',$hash;6839}6840open$fd,"-|", git_cmd(),"format-patch",@diff_opts,6841'--encoding=utf8','--stdout',@commit_spec6842or die_error(500,"Open git-format-patch failed");6843}else{6844 die_error(400,"Unknown commitdiff format");6845}68466847# non-textual hash id's can be cached6848my$expires;6849if($hash=~m/^[0-9a-fA-F]{40}$/) {6850$expires="+1d";6851}68526853# write commit message6854if($formateq'html') {6855my$refs= git_get_references();6856my$ref= format_ref_marker($refs,$co{'id'});68576858 git_header_html(undef,$expires);6859 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);6860 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);6861print"<div class=\"title_text\">\n".6862"<table class=\"object_header\">\n";6863 git_print_authorship_rows(\%co);6864print"</table>".6865"</div>\n";6866print"<div class=\"page_body\">\n";6867if(@{$co{'comment'}} >1) {6868print"<div class=\"log\">\n";6869 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);6870print"</div>\n";# class="log"6871}68726873}elsif($formateq'plain') {6874my$refs= git_get_references("tags");6875my$tagname= git_get_rev_name_tags($hash);6876my$filename= basename($project) ."-$hash.patch";68776878print$cgi->header(6879-type =>'text/plain',6880-charset =>'utf-8',6881-expires =>$expires,6882-content_disposition =>'inline; filename="'."$filename".'"');6883my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});6884print"From: ". to_utf8($co{'author'}) ."\n";6885print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";6886print"Subject: ". to_utf8($co{'title'}) ."\n";68876888print"X-Git-Tag:$tagname\n"if$tagname;6889print"X-Git-Url: ".$cgi->self_url() ."\n\n";68906891foreachmy$line(@{$co{'comment'}}) {6892print to_utf8($line) ."\n";6893}6894print"---\n\n";6895}elsif($formateq'patch') {6896my$filename= basename($project) ."-$hash.patch";68976898print$cgi->header(6899-type =>'text/plain',6900-charset =>'utf-8',6901-expires =>$expires,6902-content_disposition =>'inline; filename="'."$filename".'"');6903}69046905# write patch6906if($formateq'html') {6907my$use_parents= !defined$hash_parent||6908$hash_parenteq'-c'||$hash_parenteq'--cc';6909 git_difftree_body(\@difftree,$hash,6910$use_parents? @{$co{'parents'}} :$hash_parent);6911print"<br/>\n";69126913 git_patchset_body($fd, \@difftree,$hash,6914$use_parents? @{$co{'parents'}} :$hash_parent);6915close$fd;6916print"</div>\n";# class="page_body"6917 git_footer_html();69186919}elsif($formateq'plain') {6920local$/=undef;6921print<$fd>;6922close$fd6923or print"Reading git-diff-tree failed\n";6924}elsif($formateq'patch') {6925local$/=undef;6926print<$fd>;6927close$fd6928or print"Reading git-format-patch failed\n";6929}6930}69316932sub git_commitdiff_plain {6933 git_commitdiff(-format =>'plain');6934}69356936# format-patch-style patches6937sub git_patch {6938 git_commitdiff(-format =>'patch', -single =>1);6939}69406941sub git_patches {6942 git_commitdiff(-format =>'patch');6943}69446945sub git_history {6946 git_log_generic('history', \&git_history_body,6947$hash_base,$hash_parent_base,6948$file_name,$hash);6949}69506951sub git_search {6952 gitweb_check_feature('search')or die_error(403,"Search is disabled");6953if(!defined$searchtext) {6954 die_error(400,"Text field is empty");6955}6956if(!defined$hash) {6957$hash= git_get_head_hash($project);6958}6959my%co= parse_commit($hash);6960if(!%co) {6961 die_error(404,"Unknown commit object");6962}6963if(!defined$page) {6964$page=0;6965}69666967$searchtype||='commit';6968if($searchtypeeq'pickaxe') {6969# pickaxe may take all resources of your box and run for several minutes6970# with every query - so decide by yourself how public you make this feature6971 gitweb_check_feature('pickaxe')6972or die_error(403,"Pickaxe is disabled");6973}6974if($searchtypeeq'grep') {6975 gitweb_check_feature('grep')6976or die_error(403,"Grep is disabled");6977}69786979 git_header_html();69806981if($searchtypeeq'commit'or$searchtypeeq'author'or$searchtypeeq'committer') {6982my$greptype;6983if($searchtypeeq'commit') {6984$greptype="--grep=";6985}elsif($searchtypeeq'author') {6986$greptype="--author=";6987}elsif($searchtypeeq'committer') {6988$greptype="--committer=";6989}6990$greptype.=$searchtext;6991my@commitlist= parse_commits($hash,101, (100*$page),undef,6992$greptype,'--regexp-ignore-case',6993$search_use_regexp?'--extended-regexp':'--fixed-strings');69946995my$paging_nav='';6996if($page>0) {6997$paging_nav.=6998$cgi->a({-href => href(action=>"search", hash=>$hash,6999 searchtext=>$searchtext,7000 searchtype=>$searchtype)},7001"first");7002$paging_nav.=" ⋅ ".7003$cgi->a({-href => href(-replay=>1, page=>$page-1),7004-accesskey =>"p", -title =>"Alt-p"},"prev");7005}else{7006$paging_nav.="first";7007$paging_nav.=" ⋅ prev";7008}7009my$next_link='';7010if($#commitlist>=100) {7011$next_link=7012$cgi->a({-href => href(-replay=>1, page=>$page+1),7013-accesskey =>"n", -title =>"Alt-n"},"next");7014$paging_nav.=" ⋅$next_link";7015}else{7016$paging_nav.=" ⋅ next";7017}70187019 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);7020 git_print_header_div('commit', esc_html($co{'title'}),$hash);7021if($page==0&& !@commitlist) {7022print"<p>No match.</p>\n";7023}else{7024 git_search_grep_body(\@commitlist,0,99,$next_link);7025}7026}70277028if($searchtypeeq'pickaxe') {7029 git_print_page_nav('','',$hash,$co{'tree'},$hash);7030 git_print_header_div('commit', esc_html($co{'title'}),$hash);70317032print"<table class=\"pickaxe search\">\n";7033my$alternate=1;7034local$/="\n";7035open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,7036'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",7037($search_use_regexp?'--pickaxe-regex': ());7038undef%co;7039my@files;7040while(my$line= <$fd>) {7041chomp$line;7042next unless$line;70437044my%set= parse_difftree_raw_line($line);7045if(defined$set{'commit'}) {7046# finish previous commit7047if(%co) {7048print"</td>\n".7049"<td class=\"link\">".7050$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .7051" | ".7052$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");7053print"</td>\n".7054"</tr>\n";7055}70567057if($alternate) {7058print"<tr class=\"dark\">\n";7059}else{7060print"<tr class=\"light\">\n";7061}7062$alternate^=1;7063%co= parse_commit($set{'commit'});7064my$author= chop_and_escape_str($co{'author_name'},15,5);7065print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".7066"<td><i>$author</i></td>\n".7067"<td>".7068$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),7069-class=>"list subject"},7070 chop_and_escape_str($co{'title'},50) ."<br/>");7071}elsif(defined$set{'to_id'}) {7072next if($set{'to_id'} =~m/^0{40}$/);70737074print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},7075 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),7076-class=>"list"},7077"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .7078"<br/>\n";7079}7080}7081close$fd;70827083# finish last commit (warning: repetition!)7084if(%co) {7085print"</td>\n".7086"<td class=\"link\">".7087$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .7088" | ".7089$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");7090print"</td>\n".7091"</tr>\n";7092}70937094print"</table>\n";7095}70967097if($searchtypeeq'grep') {7098 git_print_page_nav('','',$hash,$co{'tree'},$hash);7099 git_print_header_div('commit', esc_html($co{'title'}),$hash);71007101print"<table class=\"grep_search\">\n";7102my$alternate=1;7103my$matches=0;7104local$/="\n";7105open my$fd,"-|", git_cmd(),'grep','-n',7106$search_use_regexp? ('-E','-i') :'-F',7107$searchtext,$co{'tree'};7108my$lastfile='';7109while(my$line= <$fd>) {7110chomp$line;7111my($file,$lno,$ltext,$binary);7112last if($matches++>1000);7113if($line=~/^Binary file (.+) matches$/) {7114$file=$1;7115$binary=1;7116}else{7117(undef,$file,$lno,$ltext) =split(/:/,$line,4);7118}7119if($filene$lastfile) {7120$lastfileand print"</td></tr>\n";7121if($alternate++) {7122print"<tr class=\"dark\">\n";7123}else{7124print"<tr class=\"light\">\n";7125}7126print"<td class=\"list\">".7127$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},7128 file_name=>"$file"),7129-class=>"list"}, esc_path($file));7130print"</td><td>\n";7131$lastfile=$file;7132}7133if($binary) {7134print"<div class=\"binary\">Binary file</div>\n";7135}else{7136$ltext= untabify($ltext);7137if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {7138$ltext= esc_html($1, -nbsp=>1);7139$ltext.='<span class="match">';7140$ltext.= esc_html($2, -nbsp=>1);7141$ltext.='</span>';7142$ltext.= esc_html($3, -nbsp=>1);7143}else{7144$ltext= esc_html($ltext, -nbsp=>1);7145}7146print"<div class=\"pre\">".7147$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},7148 file_name=>"$file").'#l'.$lno,7149-class=>"linenr"},sprintf('%4i',$lno))7150.' '.$ltext."</div>\n";7151}7152}7153if($lastfile) {7154print"</td></tr>\n";7155if($matches>1000) {7156print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";7157}7158}else{7159print"<div class=\"diff nodifferences\">No matches found</div>\n";7160}7161close$fd;71627163print"</table>\n";7164}7165 git_footer_html();7166}71677168sub git_search_help {7169 git_header_html();7170 git_print_page_nav('','',$hash,$hash,$hash);7171print<<EOT;7172<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without7173regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,7174the pattern entered is recognized as the POSIX extended7175<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case7176insensitive).</p>7177<dl>7178<dt><b>commit</b></dt>7179<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>7180EOT7181my$have_grep= gitweb_check_feature('grep');7182if($have_grep) {7183print<<EOT;7184<dt><b>grep</b></dt>7185<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing7186 a different one) are searched for the given pattern. On large trees, this search can take7187a while and put some strain on the server, so please use it with some consideration. Note that7188due to git-grep peculiarity, currently if regexp mode is turned off, the matches are7189case-sensitive.</dd>7190EOT7191}7192print<<EOT;7193<dt><b>author</b></dt>7194<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>7195<dt><b>committer</b></dt>7196<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>7197EOT7198my$have_pickaxe= gitweb_check_feature('pickaxe');7199if($have_pickaxe) {7200print<<EOT;7201<dt><b>pickaxe</b></dt>7202<dd>All commits that caused the string to appear or disappear from any file (changes that7203added, removed or "modified" the string) will be listed. This search can take a while and7204takes a lot of strain on the server, so please use it wisely. Note that since you may be7205interested even in changes just changing the case as well, this search is case sensitive.</dd>7206EOT7207}7208print"</dl>\n";7209 git_footer_html();7210}72117212sub git_shortlog {7213 git_log_generic('shortlog', \&git_shortlog_body,7214$hash,$hash_parent);7215}72167217## ......................................................................7218## feeds (RSS, Atom; OPML)72197220sub git_feed {7221my$format=shift||'atom';7222my$have_blame= gitweb_check_feature('blame');72237224# Atom: http://www.atomenabled.org/developers/syndication/7225# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ7226if($formatne'rss'&&$formatne'atom') {7227 die_error(400,"Unknown web feed format");7228}72297230# log/feed of current (HEAD) branch, log of given branch, history of file/directory7231my$head=$hash||'HEAD';7232my@commitlist= parse_commits($head,150,0,$file_name);72337234my%latest_commit;7235my%latest_date;7236my$content_type="application/$format+xml";7237if(defined$cgi->http('HTTP_ACCEPT') &&7238$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {7239# browser (feed reader) prefers text/xml7240$content_type='text/xml';7241}7242if(defined($commitlist[0])) {7243%latest_commit= %{$commitlist[0]};7244my$latest_epoch=$latest_commit{'committer_epoch'};7245%latest_date= parse_date($latest_epoch,$latest_commit{'comitter_tz'});7246my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7247if(defined$if_modified) {7248my$since;7249if(eval{require HTTP::Date;1; }) {7250$since= HTTP::Date::str2time($if_modified);7251}elsif(eval{require Time::ParseDate;1; }) {7252$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7253}7254if(defined$since&&$latest_epoch<=$since) {7255print$cgi->header(7256-type =>$content_type,7257-charset =>'utf-8',7258-last_modified =>$latest_date{'rfc2822'},7259-status =>'304 Not Modified');7260return;7261}7262}7263print$cgi->header(7264-type =>$content_type,7265-charset =>'utf-8',7266-last_modified =>$latest_date{'rfc2822'});7267}else{7268print$cgi->header(7269-type =>$content_type,7270-charset =>'utf-8');7271}72727273# Optimization: skip generating the body if client asks only7274# for Last-Modified date.7275return if($cgi->request_method()eq'HEAD');72767277# header variables7278my$title="$site_name-$project/$action";7279my$feed_type='log';7280if(defined$hash) {7281$title.=" - '$hash'";7282$feed_type='branch log';7283if(defined$file_name) {7284$title.=" ::$file_name";7285$feed_type='history';7286}7287}elsif(defined$file_name) {7288$title.=" -$file_name";7289$feed_type='history';7290}7291$title.="$feed_type";7292my$descr= git_get_project_description($project);7293if(defined$descr) {7294$descr= esc_html($descr);7295}else{7296$descr="$project".7297($formateq'rss'?'RSS':'Atom') .7298" feed";7299}7300my$owner= git_get_project_owner($project);7301$owner= esc_html($owner);73027303#header7304my$alt_url;7305if(defined$file_name) {7306$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);7307}elsif(defined$hash) {7308$alt_url= href(-full=>1, action=>"log", hash=>$hash);7309}else{7310$alt_url= href(-full=>1, action=>"summary");7311}7312print qq!<?xml version="1.0" encoding="utf-8"?>\n!;7313if($formateq'rss') {7314print<<XML;7315<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">7316<channel>7317XML7318print"<title>$title</title>\n".7319"<link>$alt_url</link>\n".7320"<description>$descr</description>\n".7321"<language>en</language>\n".7322# project owner is responsible for 'editorial' content7323"<managingEditor>$owner</managingEditor>\n";7324if(defined$logo||defined$favicon) {7325# prefer the logo to the favicon, since RSS7326# doesn't allow both7327my$img= esc_url($logo||$favicon);7328print"<image>\n".7329"<url>$img</url>\n".7330"<title>$title</title>\n".7331"<link>$alt_url</link>\n".7332"</image>\n";7333}7334if(%latest_date) {7335print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";7336print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";7337}7338print"<generator>gitweb v.$version/$git_version</generator>\n";7339}elsif($formateq'atom') {7340print<<XML;7341<feed xmlns="http://www.w3.org/2005/Atom">7342XML7343print"<title>$title</title>\n".7344"<subtitle>$descr</subtitle>\n".7345'<link rel="alternate" type="text/html" href="'.7346$alt_url.'" />'."\n".7347'<link rel="self" type="'.$content_type.'" href="'.7348$cgi->self_url() .'" />'."\n".7349"<id>". href(-full=>1) ."</id>\n".7350# use project owner for feed author7351"<author><name>$owner</name></author>\n";7352if(defined$favicon) {7353print"<icon>". esc_url($favicon) ."</icon>\n";7354}7355if(defined$logo) {7356# not twice as wide as tall: 72 x 27 pixels7357print"<logo>". esc_url($logo) ."</logo>\n";7358}7359if(!%latest_date) {7360# dummy date to keep the feed valid until commits trickle in:7361print"<updated>1970-01-01T00:00:00Z</updated>\n";7362}else{7363print"<updated>$latest_date{'iso-8601'}</updated>\n";7364}7365print"<generator version='$version/$git_version'>gitweb</generator>\n";7366}73677368# contents7369for(my$i=0;$i<=$#commitlist;$i++) {7370my%co= %{$commitlist[$i]};7371my$commit=$co{'id'};7372# we read 150, we always show 30 and the ones more recent than 48 hours7373if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {7374last;7375}7376my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});73777378# get list of changed files7379open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7380$co{'parent'} ||"--root",7381$co{'id'},"--", (defined$file_name?$file_name: ())7382ornext;7383my@difftree=map{chomp;$_} <$fd>;7384close$fd7385ornext;73867387# print element (entry, item)7388my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);7389if($formateq'rss') {7390print"<item>\n".7391"<title>". esc_html($co{'title'}) ."</title>\n".7392"<author>". esc_html($co{'author'}) ."</author>\n".7393"<pubDate>$cd{'rfc2822'}</pubDate>\n".7394"<guid isPermaLink=\"true\">$co_url</guid>\n".7395"<link>$co_url</link>\n".7396"<description>". esc_html($co{'title'}) ."</description>\n".7397"<content:encoded>".7398"<![CDATA[\n";7399}elsif($formateq'atom') {7400print"<entry>\n".7401"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".7402"<updated>$cd{'iso-8601'}</updated>\n".7403"<author>\n".7404" <name>". esc_html($co{'author_name'}) ."</name>\n";7405if($co{'author_email'}) {7406print" <email>". esc_html($co{'author_email'}) ."</email>\n";7407}7408print"</author>\n".7409# use committer for contributor7410"<contributor>\n".7411" <name>". esc_html($co{'committer_name'}) ."</name>\n";7412if($co{'committer_email'}) {7413print" <email>". esc_html($co{'committer_email'}) ."</email>\n";7414}7415print"</contributor>\n".7416"<published>$cd{'iso-8601'}</published>\n".7417"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".7418"<id>$co_url</id>\n".7419"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".7420"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";7421}7422my$comment=$co{'comment'};7423print"<pre>\n";7424foreachmy$line(@$comment) {7425$line= esc_html($line);7426print"$line\n";7427}7428print"</pre><ul>\n";7429foreachmy$difftree_line(@difftree) {7430my%difftree= parse_difftree_raw_line($difftree_line);7431next if!$difftree{'from_id'};74327433my$file=$difftree{'file'} ||$difftree{'to_file'};74347435print"<li>".7436"[".7437$cgi->a({-href => href(-full=>1, action=>"blobdiff",7438 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},7439 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},7440 file_name=>$file, file_parent=>$difftree{'from_file'}),7441-title =>"diff"},'D');7442if($have_blame) {7443print$cgi->a({-href => href(-full=>1, action=>"blame",7444 file_name=>$file, hash_base=>$commit),7445-title =>"blame"},'B');7446}7447# if this is not a feed of a file history7448if(!defined$file_name||$file_namene$file) {7449print$cgi->a({-href => href(-full=>1, action=>"history",7450 file_name=>$file, hash=>$commit),7451-title =>"history"},'H');7452}7453$file= esc_path($file);7454print"] ".7455"$file</li>\n";7456}7457if($formateq'rss') {7458print"</ul>]]>\n".7459"</content:encoded>\n".7460"</item>\n";7461}elsif($formateq'atom') {7462print"</ul>\n</div>\n".7463"</content>\n".7464"</entry>\n";7465}7466}74677468# end of feed7469if($formateq'rss') {7470print"</channel>\n</rss>\n";7471}elsif($formateq'atom') {7472print"</feed>\n";7473}7474}74757476sub git_rss {7477 git_feed('rss');7478}74797480sub git_atom {7481 git_feed('atom');7482}74837484sub git_opml {7485my@list= git_get_projects_list();7486if(!@list) {7487 die_error(404,"No projects found");7488}74897490print$cgi->header(7491-type =>'text/xml',7492-charset =>'utf-8',7493-content_disposition =>'inline; filename="opml.xml"');74947495print<<XML;7496<?xml version="1.0" encoding="utf-8"?>7497<opml version="1.0">7498<head>7499 <title>$site_nameOPML Export</title>7500</head>7501<body>7502<outline text="git RSS feeds">7503XML75047505foreachmy$pr(@list) {7506my%proj=%$pr;7507my$head= git_get_head_hash($proj{'path'});7508if(!defined$head) {7509next;7510}7511$git_dir="$projectroot/$proj{'path'}";7512my%co= parse_commit($head);7513if(!%co) {7514next;7515}75167517my$path= esc_html(chop_str($proj{'path'},25,5));7518my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);7519my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);7520print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";7521}7522print<<XML;7523</outline>7524</body>7525</opml>7526XML7527}