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); 20binmode STDOUT,':utf8'; 21 22our$t0; 23if(eval{require Time::HiRes;1; }) { 24$t0= [Time::HiRes::gettimeofday()]; 25} 26our$number_of_git_cmds=0; 27 28BEGIN{ 29 CGI->compile()if$ENV{'MOD_PERL'}; 30} 31 32our$version="++GIT_VERSION++"; 33 34our($my_url,$my_uri,$base_url,$path_info,$home_link); 35sub evaluate_uri { 36our$cgi; 37 38our$my_url=$cgi->url(); 39our$my_uri=$cgi->url(-absolute =>1); 40 41# Base URL for relative URLs in gitweb ($logo, $favicon, ...), 42# needed and used only for URLs with nonempty PATH_INFO 43our$base_url=$my_url; 44 45# When the script is used as DirectoryIndex, the URL does not contain the name 46# of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we 47# have to do it ourselves. We make $path_info global because it's also used 48# later on. 49# 50# Another issue with the script being the DirectoryIndex is that the resulting 51# $my_url data is not the full script URL: this is good, because we want 52# generated links to keep implying the script name if it wasn't explicitly 53# indicated in the URL we're handling, but it means that $my_url cannot be used 54# as base URL. 55# Therefore, if we needed to strip PATH_INFO, then we know that we have 56# to build the base URL ourselves: 57our$path_info=$ENV{"PATH_INFO"}; 58if($path_info) { 59if($my_url=~ s,\Q$path_info\E$,, && 60$my_uri=~ s,\Q$path_info\E$,, && 61defined$ENV{'SCRIPT_NAME'}) { 62$base_url=$cgi->url(-base =>1) .$ENV{'SCRIPT_NAME'}; 63} 64} 65 66# target of the home link on top of all pages 67our$home_link=$my_uri||"/"; 68} 69 70# core git executable to use 71# this can just be "git" if your webserver has a sensible PATH 72our$GIT="++GIT_BINDIR++/git"; 73 74# absolute fs-path which will be prepended to the project path 75#our $projectroot = "/pub/scm"; 76our$projectroot="++GITWEB_PROJECTROOT++"; 77 78# fs traversing limit for getting project list 79# the number is relative to the projectroot 80our$project_maxdepth="++GITWEB_PROJECT_MAXDEPTH++"; 81 82# string of the home link on top of all pages 83our$home_link_str="++GITWEB_HOME_LINK_STR++"; 84 85# name of your site or organization to appear in page titles 86# replace this with something more descriptive for clearer bookmarks 87our$site_name="++GITWEB_SITENAME++" 88|| ($ENV{'SERVER_NAME'} ||"Untitled") ." Git"; 89 90# filename of html text to include at top of each page 91our$site_header="++GITWEB_SITE_HEADER++"; 92# html text to include at home page 93our$home_text="++GITWEB_HOMETEXT++"; 94# filename of html text to include at bottom of each page 95our$site_footer="++GITWEB_SITE_FOOTER++"; 96 97# URI of stylesheets 98our@stylesheets= ("++GITWEB_CSS++"); 99# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG. 100our$stylesheet=undef; 101# URI of GIT logo (72x27 size) 102our$logo="++GITWEB_LOGO++"; 103# URI of GIT favicon, assumed to be image/png type 104our$favicon="++GITWEB_FAVICON++"; 105# URI of gitweb.js (JavaScript code for gitweb) 106our$javascript="++GITWEB_JS++"; 107 108# URI and label (title) of GIT logo link 109#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/"; 110#our $logo_label = "git documentation"; 111our$logo_url="http://git-scm.com/"; 112our$logo_label="git homepage"; 113 114# source of projects list 115our$projects_list="++GITWEB_LIST++"; 116 117# the width (in characters) of the projects list "Description" column 118our$projects_list_description_width=25; 119 120# default order of projects list 121# valid values are none, project, descr, owner, and age 122our$default_projects_order="project"; 123 124# show repository only if this file exists 125# (only effective if this variable evaluates to true) 126our$export_ok="++GITWEB_EXPORT_OK++"; 127 128# show repository only if this subroutine returns true 129# when given the path to the project, for example: 130# sub { return -e "$_[0]/git-daemon-export-ok"; } 131our$export_auth_hook=undef; 132 133# only allow viewing of repositories also shown on the overview page 134our$strict_export="++GITWEB_STRICT_EXPORT++"; 135 136# list of git base URLs used for URL to where fetch project from, 137# i.e. full URL is "$git_base_url/$project" 138our@git_base_url_list=grep{$_ne''} ("++GITWEB_BASE_URL++"); 139 140# default blob_plain mimetype and default charset for text/plain blob 141our$default_blob_plain_mimetype='text/plain'; 142our$default_text_plain_charset=undef; 143 144# file to use for guessing MIME types before trying /etc/mime.types 145# (relative to the current git repository) 146our$mimetypes_file=undef; 147 148# assume this charset if line contains non-UTF-8 characters; 149# it should be valid encoding (see Encoding::Supported(3pm) for list), 150# for which encoding all byte sequences are valid, for example 151# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it 152# could be even 'utf-8' for the old behavior) 153our$fallback_encoding='latin1'; 154 155# rename detection options for git-diff and git-diff-tree 156# - default is '-M', with the cost proportional to 157# (number of removed files) * (number of new files). 158# - more costly is '-C' (which implies '-M'), with the cost proportional to 159# (number of changed files + number of removed files) * (number of new files) 160# - even more costly is '-C', '--find-copies-harder' with cost 161# (number of files in the original tree) * (number of new files) 162# - one might want to include '-B' option, e.g. '-B', '-M' 163our@diff_opts= ('-M');# taken from git_commit 164 165# Disables features that would allow repository owners to inject script into 166# the gitweb domain. 167our$prevent_xss=0; 168 169# Path to the highlight executable to use (must be the one from 170# http://www.andre-simon.de due to assumptions about parameters and output). 171# Useful if highlight is not installed on your webserver's PATH. 172# [Default: highlight] 173our$highlight_bin="++HIGHLIGHT_BIN++"; 174 175# information about snapshot formats that gitweb is capable of serving 176our%known_snapshot_formats= ( 177# name => { 178# 'display' => display name, 179# 'type' => mime type, 180# 'suffix' => filename suffix, 181# 'format' => --format for git-archive, 182# 'compressor' => [compressor command and arguments] 183# (array reference, optional) 184# 'disabled' => boolean (optional)} 185# 186'tgz'=> { 187'display'=>'tar.gz', 188'type'=>'application/x-gzip', 189'suffix'=>'.tar.gz', 190'format'=>'tar', 191'compressor'=> ['gzip']}, 192 193'tbz2'=> { 194'display'=>'tar.bz2', 195'type'=>'application/x-bzip2', 196'suffix'=>'.tar.bz2', 197'format'=>'tar', 198'compressor'=> ['bzip2']}, 199 200'txz'=> { 201'display'=>'tar.xz', 202'type'=>'application/x-xz', 203'suffix'=>'.tar.xz', 204'format'=>'tar', 205'compressor'=> ['xz'], 206'disabled'=>1}, 207 208'zip'=> { 209'display'=>'zip', 210'type'=>'application/x-zip', 211'suffix'=>'.zip', 212'format'=>'zip'}, 213); 214 215# Aliases so we understand old gitweb.snapshot values in repository 216# configuration. 217our%known_snapshot_format_aliases= ( 218'gzip'=>'tgz', 219'bzip2'=>'tbz2', 220'xz'=>'txz', 221 222# backward compatibility: legacy gitweb config support 223'x-gzip'=>undef,'gz'=>undef, 224'x-bzip2'=>undef,'bz2'=>undef, 225'x-zip'=>undef,''=>undef, 226); 227 228# Pixel sizes for icons and avatars. If the default font sizes or lineheights 229# are changed, it may be appropriate to change these values too via 230# $GITWEB_CONFIG. 231our%avatar_size= ( 232'default'=>16, 233'double'=>32 234); 235 236# Used to set the maximum load that we will still respond to gitweb queries. 237# If server load exceed this value then return "503 server busy" error. 238# If gitweb cannot determined server load, it is taken to be 0. 239# Leave it undefined (or set to 'undef') to turn off load checking. 240our$maxload=300; 241 242# configuration for 'highlight' (http://www.andre-simon.de/) 243# match by basename 244our%highlight_basename= ( 245#'Program' => 'py', 246#'Library' => 'py', 247'SConstruct'=>'py',# SCons equivalent of Makefile 248'Makefile'=>'make', 249); 250# match by extension 251our%highlight_ext= ( 252# main extensions, defining name of syntax; 253# see files in /usr/share/highlight/langDefs/ directory 254map{$_=>$_} 255qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl), 256# alternate extensions, see /etc/highlight/filetypes.conf 257'h'=>'c', 258map{$_=>'cpp'}qw(cxx c++ cc), 259map{$_=>'php'}qw(php3 php4), 260map{$_=>'pl'}qw(perl pm),# perhaps also 'cgi' 261'mak'=>'make', 262map{$_=>'xml'}qw(xhtml html htm), 263); 264 265# You define site-wide feature defaults here; override them with 266# $GITWEB_CONFIG as necessary. 267our%feature= ( 268# feature => { 269# 'sub' => feature-sub (subroutine), 270# 'override' => allow-override (boolean), 271# 'default' => [ default options...] (array reference)} 272# 273# if feature is overridable (it means that allow-override has true value), 274# then feature-sub will be called with default options as parameters; 275# return value of feature-sub indicates if to enable specified feature 276# 277# if there is no 'sub' key (no feature-sub), then feature cannot be 278# overridden 279# 280# use gitweb_get_feature(<feature>) to retrieve the <feature> value 281# (an array) or gitweb_check_feature(<feature>) to check if <feature> 282# is enabled 283 284# Enable the 'blame' blob view, showing the last commit that modified 285# each line in the file. This can be very CPU-intensive. 286 287# To enable system wide have in $GITWEB_CONFIG 288# $feature{'blame'}{'default'} = [1]; 289# To have project specific config enable override in $GITWEB_CONFIG 290# $feature{'blame'}{'override'} = 1; 291# and in project config gitweb.blame = 0|1; 292'blame'=> { 293'sub'=>sub{ feature_bool('blame',@_) }, 294'override'=>0, 295'default'=> [0]}, 296 297# Enable the 'snapshot' link, providing a compressed archive of any 298# tree. This can potentially generate high traffic if you have large 299# project. 300 301# Value is a list of formats defined in %known_snapshot_formats that 302# you wish to offer. 303# To disable system wide have in $GITWEB_CONFIG 304# $feature{'snapshot'}{'default'} = []; 305# To have project specific config enable override in $GITWEB_CONFIG 306# $feature{'snapshot'}{'override'} = 1; 307# and in project config, a comma-separated list of formats or "none" 308# to disable. Example: gitweb.snapshot = tbz2,zip; 309'snapshot'=> { 310'sub'=> \&feature_snapshot, 311'override'=>0, 312'default'=> ['tgz']}, 313 314# Enable text search, which will list the commits which match author, 315# committer or commit text to a given string. Enabled by default. 316# Project specific override is not supported. 317'search'=> { 318'override'=>0, 319'default'=> [1]}, 320 321# Enable grep search, which will list the files in currently selected 322# tree containing the given string. Enabled by default. This can be 323# potentially CPU-intensive, of course. 324 325# To enable system wide have in $GITWEB_CONFIG 326# $feature{'grep'}{'default'} = [1]; 327# To have project specific config enable override in $GITWEB_CONFIG 328# $feature{'grep'}{'override'} = 1; 329# and in project config gitweb.grep = 0|1; 330'grep'=> { 331'sub'=>sub{ feature_bool('grep',@_) }, 332'override'=>0, 333'default'=> [1]}, 334 335# Enable the pickaxe search, which will list the commits that modified 336# a given string in a file. This can be practical and quite faster 337# alternative to 'blame', but still potentially CPU-intensive. 338 339# To enable system wide have in $GITWEB_CONFIG 340# $feature{'pickaxe'}{'default'} = [1]; 341# To have project specific config enable override in $GITWEB_CONFIG 342# $feature{'pickaxe'}{'override'} = 1; 343# and in project config gitweb.pickaxe = 0|1; 344'pickaxe'=> { 345'sub'=>sub{ feature_bool('pickaxe',@_) }, 346'override'=>0, 347'default'=> [1]}, 348 349# Enable showing size of blobs in a 'tree' view, in a separate 350# column, similar to what 'ls -l' does. This cost a bit of IO. 351 352# To disable system wide have in $GITWEB_CONFIG 353# $feature{'show-sizes'}{'default'} = [0]; 354# To have project specific config enable override in $GITWEB_CONFIG 355# $feature{'show-sizes'}{'override'} = 1; 356# and in project config gitweb.showsizes = 0|1; 357'show-sizes'=> { 358'sub'=>sub{ feature_bool('showsizes',@_) }, 359'override'=>0, 360'default'=> [1]}, 361 362# Make gitweb use an alternative format of the URLs which can be 363# more readable and natural-looking: project name is embedded 364# directly in the path and the query string contains other 365# auxiliary information. All gitweb installations recognize 366# URL in either format; this configures in which formats gitweb 367# generates links. 368 369# To enable system wide have in $GITWEB_CONFIG 370# $feature{'pathinfo'}{'default'} = [1]; 371# Project specific override is not supported. 372 373# Note that you will need to change the default location of CSS, 374# favicon, logo and possibly other files to an absolute URL. Also, 375# if gitweb.cgi serves as your indexfile, you will need to force 376# $my_uri to contain the script name in your $GITWEB_CONFIG. 377'pathinfo'=> { 378'override'=>0, 379'default'=> [0]}, 380 381# Make gitweb consider projects in project root subdirectories 382# to be forks of existing projects. Given project $projname.git, 383# projects matching $projname/*.git will not be shown in the main 384# projects list, instead a '+' mark will be added to $projname 385# there and a 'forks' view will be enabled for the project, listing 386# all the forks. If project list is taken from a file, forks have 387# to be listed after the main project. 388 389# To enable system wide have in $GITWEB_CONFIG 390# $feature{'forks'}{'default'} = [1]; 391# Project specific override is not supported. 392'forks'=> { 393'override'=>0, 394'default'=> [0]}, 395 396# Insert custom links to the action bar of all project pages. 397# This enables you mainly to link to third-party scripts integrating 398# into gitweb; e.g. git-browser for graphical history representation 399# or custom web-based repository administration interface. 400 401# The 'default' value consists of a list of triplets in the form 402# (label, link, position) where position is the label after which 403# to insert the link and link is a format string where %n expands 404# to the project name, %f to the project path within the filesystem, 405# %h to the current hash (h gitweb parameter) and %b to the current 406# hash base (hb gitweb parameter); %% expands to %. 407 408# To enable system wide have in $GITWEB_CONFIG e.g. 409# $feature{'actions'}{'default'} = [('graphiclog', 410# '/git-browser/by-commit.html?r=%n', 'summary')]; 411# Project specific override is not supported. 412'actions'=> { 413'override'=>0, 414'default'=> []}, 415 416# Allow gitweb scan project content tags described in ctags/ 417# of project repository, and display the popular Web 2.0-ish 418# "tag cloud" near the project list. Note that this is something 419# COMPLETELY different from the normal Git tags. 420 421# gitweb by itself can show existing tags, but it does not handle 422# tagging itself; you need an external application for that. 423# For an example script, check Girocco's cgi/tagproj.cgi. 424# You may want to install the HTML::TagCloud Perl module to get 425# a pretty tag cloud instead of just a list of tags. 426 427# To enable system wide have in $GITWEB_CONFIG 428# $feature{'ctags'}{'default'} = ['path_to_tag_script']; 429# Project specific override is not supported. 430'ctags'=> { 431'override'=>0, 432'default'=> [0]}, 433 434# The maximum number of patches in a patchset generated in patch 435# view. Set this to 0 or undef to disable patch view, or to a 436# negative number to remove any limit. 437 438# To disable system wide have in $GITWEB_CONFIG 439# $feature{'patches'}{'default'} = [0]; 440# To have project specific config enable override in $GITWEB_CONFIG 441# $feature{'patches'}{'override'} = 1; 442# and in project config gitweb.patches = 0|n; 443# where n is the maximum number of patches allowed in a patchset. 444'patches'=> { 445'sub'=> \&feature_patches, 446'override'=>0, 447'default'=> [16]}, 448 449# Avatar support. When this feature is enabled, views such as 450# shortlog or commit will display an avatar associated with 451# the email of the committer(s) and/or author(s). 452 453# Currently available providers are gravatar and picon. 454# If an unknown provider is specified, the feature is disabled. 455 456# Gravatar depends on Digest::MD5. 457# Picon currently relies on the indiana.edu database. 458 459# To enable system wide have in $GITWEB_CONFIG 460# $feature{'avatar'}{'default'} = ['<provider>']; 461# where <provider> is either gravatar or picon. 462# To have project specific config enable override in $GITWEB_CONFIG 463# $feature{'avatar'}{'override'} = 1; 464# and in project config gitweb.avatar = <provider>; 465'avatar'=> { 466'sub'=> \&feature_avatar, 467'override'=>0, 468'default'=> ['']}, 469 470# Enable displaying how much time and how many git commands 471# it took to generate and display page. Disabled by default. 472# Project specific override is not supported. 473'timed'=> { 474'override'=>0, 475'default'=> [0]}, 476 477# Enable turning some links into links to actions which require 478# JavaScript to run (like 'blame_incremental'). Not enabled by 479# default. Project specific override is currently not supported. 480'javascript-actions'=> { 481'override'=>0, 482'default'=> [0]}, 483 484# Syntax highlighting support. This is based on Daniel Svensson's 485# and Sham Chukoury's work in gitweb-xmms2.git. 486# It requires the 'highlight' program present in $PATH, 487# and therefore is disabled by default. 488 489# To enable system wide have in $GITWEB_CONFIG 490# $feature{'highlight'}{'default'} = [1]; 491 492'highlight'=> { 493'sub'=>sub{ feature_bool('highlight',@_) }, 494'override'=>0, 495'default'=> [0]}, 496 497# Enable displaying of remote heads in the heads list 498 499# To enable system wide have in $GITWEB_CONFIG 500# $feature{'remote_heads'}{'default'} = [1]; 501# To have project specific config enable override in $GITWEB_CONFIG 502# $feature{'remote_heads'}{'override'} = 1; 503# and in project config gitweb.remote_heads = 0|1; 504'remote_heads'=> { 505'sub'=>sub{ feature_bool('remote_heads',@_) }, 506'override'=>0, 507'default'=> [0]}, 508); 509 510sub gitweb_get_feature { 511my($name) =@_; 512return unlessexists$feature{$name}; 513my($sub,$override,@defaults) = ( 514$feature{$name}{'sub'}, 515$feature{$name}{'override'}, 516@{$feature{$name}{'default'}}); 517# project specific override is possible only if we have project 518our$git_dir;# global variable, declared later 519if(!$override|| !defined$git_dir) { 520return@defaults; 521} 522if(!defined$sub) { 523warn"feature$nameis not overridable"; 524return@defaults; 525} 526return$sub->(@defaults); 527} 528 529# A wrapper to check if a given feature is enabled. 530# With this, you can say 531# 532# my $bool_feat = gitweb_check_feature('bool_feat'); 533# gitweb_check_feature('bool_feat') or somecode; 534# 535# instead of 536# 537# my ($bool_feat) = gitweb_get_feature('bool_feat'); 538# (gitweb_get_feature('bool_feat'))[0] or somecode; 539# 540sub gitweb_check_feature { 541return(gitweb_get_feature(@_))[0]; 542} 543 544 545sub feature_bool { 546my$key=shift; 547my($val) = git_get_project_config($key,'--bool'); 548 549if(!defined$val) { 550return($_[0]); 551}elsif($valeq'true') { 552return(1); 553}elsif($valeq'false') { 554return(0); 555} 556} 557 558sub feature_snapshot { 559my(@fmts) =@_; 560 561my($val) = git_get_project_config('snapshot'); 562 563if($val) { 564@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 565} 566 567return@fmts; 568} 569 570sub feature_patches { 571my@val= (git_get_project_config('patches','--int')); 572 573if(@val) { 574return@val; 575} 576 577return($_[0]); 578} 579 580sub feature_avatar { 581my@val= (git_get_project_config('avatar')); 582 583return@val?@val:@_; 584} 585 586# checking HEAD file with -e is fragile if the repository was 587# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 588# and then pruned. 589sub check_head_link { 590my($dir) =@_; 591my$headfile="$dir/HEAD"; 592return((-e $headfile) || 593(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 594} 595 596sub check_export_ok { 597my($dir) =@_; 598return(check_head_link($dir) && 599(!$export_ok|| -e "$dir/$export_ok") && 600(!$export_auth_hook||$export_auth_hook->($dir))); 601} 602 603# process alternate names for backward compatibility 604# filter out unsupported (unknown) snapshot formats 605sub filter_snapshot_fmts { 606my@fmts=@_; 607 608@fmts=map{ 609exists$known_snapshot_format_aliases{$_} ? 610$known_snapshot_format_aliases{$_} :$_}@fmts; 611@fmts=grep{ 612exists$known_snapshot_formats{$_} && 613!$known_snapshot_formats{$_}{'disabled'}}@fmts; 614} 615 616our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM); 617sub evaluate_gitweb_config { 618our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 619our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 620# die if there are errors parsing config file 621if(-e $GITWEB_CONFIG) { 622do$GITWEB_CONFIG; 623die$@if$@; 624}elsif(-e $GITWEB_CONFIG_SYSTEM) { 625do$GITWEB_CONFIG_SYSTEM; 626die$@if$@; 627} 628} 629 630# Get loadavg of system, to compare against $maxload. 631# Currently it requires '/proc/loadavg' present to get loadavg; 632# if it is not present it returns 0, which means no load checking. 633sub get_loadavg { 634if( -e '/proc/loadavg'){ 635open my$fd,'<','/proc/loadavg' 636orreturn0; 637my@load=split(/\s+/,scalar<$fd>); 638close$fd; 639 640# The first three columns measure CPU and IO utilization of the last one, 641# five, and 10 minute periods. The fourth column shows the number of 642# currently running processes and the total number of processes in the m/n 643# format. The last column displays the last process ID used. 644return$load[0] ||0; 645} 646# additional checks for load average should go here for things that don't export 647# /proc/loadavg 648 649return0; 650} 651 652# version of the core git binary 653our$git_version; 654sub evaluate_git_version { 655our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 656$number_of_git_cmds++; 657} 658 659sub check_loadavg { 660if(defined$maxload&& get_loadavg() >$maxload) { 661 die_error(503,"The load average on the server is too high"); 662} 663} 664 665# ====================================================================== 666# input validation and dispatch 667 668# input parameters can be collected from a variety of sources (presently, CGI 669# and PATH_INFO), so we define an %input_params hash that collects them all 670# together during validation: this allows subsequent uses (e.g. href()) to be 671# agnostic of the parameter origin 672 673our%input_params= (); 674 675# input parameters are stored with the long parameter name as key. This will 676# also be used in the href subroutine to convert parameters to their CGI 677# equivalent, and since the href() usage is the most frequent one, we store 678# the name -> CGI key mapping here, instead of the reverse. 679# 680# XXX: Warning: If you touch this, check the search form for updating, 681# too. 682 683our@cgi_param_mapping= ( 684 project =>"p", 685 action =>"a", 686 file_name =>"f", 687 file_parent =>"fp", 688 hash =>"h", 689 hash_parent =>"hp", 690 hash_base =>"hb", 691 hash_parent_base =>"hpb", 692 page =>"pg", 693 order =>"o", 694 searchtext =>"s", 695 searchtype =>"st", 696 snapshot_format =>"sf", 697 extra_options =>"opt", 698 search_use_regexp =>"sr", 699# this must be last entry (for manipulation from JavaScript) 700 javascript =>"js" 701); 702our%cgi_param_mapping=@cgi_param_mapping; 703 704# we will also need to know the possible actions, for validation 705our%actions= ( 706"blame"=> \&git_blame, 707"blame_incremental"=> \&git_blame_incremental, 708"blame_data"=> \&git_blame_data, 709"blobdiff"=> \&git_blobdiff, 710"blobdiff_plain"=> \&git_blobdiff_plain, 711"blob"=> \&git_blob, 712"blob_plain"=> \&git_blob_plain, 713"commitdiff"=> \&git_commitdiff, 714"commitdiff_plain"=> \&git_commitdiff_plain, 715"commit"=> \&git_commit, 716"forks"=> \&git_forks, 717"heads"=> \&git_heads, 718"history"=> \&git_history, 719"log"=> \&git_log, 720"patch"=> \&git_patch, 721"patches"=> \&git_patches, 722"remotes"=> \&git_remotes, 723"rss"=> \&git_rss, 724"atom"=> \&git_atom, 725"search"=> \&git_search, 726"search_help"=> \&git_search_help, 727"shortlog"=> \&git_shortlog, 728"summary"=> \&git_summary, 729"tag"=> \&git_tag, 730"tags"=> \&git_tags, 731"tree"=> \&git_tree, 732"snapshot"=> \&git_snapshot, 733"object"=> \&git_object, 734# those below don't need $project 735"opml"=> \&git_opml, 736"project_list"=> \&git_project_list, 737"project_index"=> \&git_project_index, 738); 739 740# finally, we have the hash of allowed extra_options for the commands that 741# allow them 742our%allowed_options= ( 743"--no-merges"=> [qw(rss atom log shortlog history)], 744); 745 746# fill %input_params with the CGI parameters. All values except for 'opt' 747# should be single values, but opt can be an array. We should probably 748# build an array of parameters that can be multi-valued, but since for the time 749# being it's only this one, we just single it out 750sub evaluate_query_params { 751our$cgi; 752 753while(my($name,$symbol) =each%cgi_param_mapping) { 754if($symboleq'opt') { 755$input_params{$name} = [$cgi->param($symbol) ]; 756}else{ 757$input_params{$name} =$cgi->param($symbol); 758} 759} 760} 761 762# now read PATH_INFO and update the parameter list for missing parameters 763sub evaluate_path_info { 764return ifdefined$input_params{'project'}; 765return if!$path_info; 766$path_info=~ s,^/+,,; 767return if!$path_info; 768 769# find which part of PATH_INFO is project 770my$project=$path_info; 771$project=~ s,/+$,,; 772while($project&& !check_head_link("$projectroot/$project")) { 773$project=~ s,/*[^/]*$,,; 774} 775return unless$project; 776$input_params{'project'} =$project; 777 778# do not change any parameters if an action is given using the query string 779return if$input_params{'action'}; 780$path_info=~ s,^\Q$project\E/*,,; 781 782# next, check if we have an action 783my$action=$path_info; 784$action=~ s,/.*$,,; 785if(exists$actions{$action}) { 786$path_info=~ s,^$action/*,,; 787$input_params{'action'} =$action; 788} 789 790# list of actions that want hash_base instead of hash, but can have no 791# pathname (f) parameter 792my@wants_base= ( 793'tree', 794'history', 795); 796 797# we want to catch, among others 798# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 799my($parentrefname,$parentpathname,$refname,$pathname) = 800($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/); 801 802# first, analyze the 'current' part 803if(defined$pathname) { 804# we got "branch:filename" or "branch:dir/" 805# we could use git_get_type(branch:pathname), but: 806# - it needs $git_dir 807# - it does a git() call 808# - the convention of terminating directories with a slash 809# makes it superfluous 810# - embedding the action in the PATH_INFO would make it even 811# more superfluous 812$pathname=~ s,^/+,,; 813if(!$pathname||substr($pathname, -1)eq"/") { 814$input_params{'action'} ||="tree"; 815$pathname=~ s,/$,,; 816}else{ 817# the default action depends on whether we had parent info 818# or not 819if($parentrefname) { 820$input_params{'action'} ||="blobdiff_plain"; 821}else{ 822$input_params{'action'} ||="blob_plain"; 823} 824} 825$input_params{'hash_base'} ||=$refname; 826$input_params{'file_name'} ||=$pathname; 827}elsif(defined$refname) { 828# we got "branch". In this case we have to choose if we have to 829# set hash or hash_base. 830# 831# Most of the actions without a pathname only want hash to be 832# set, except for the ones specified in @wants_base that want 833# hash_base instead. It should also be noted that hand-crafted 834# links having 'history' as an action and no pathname or hash 835# set will fail, but that happens regardless of PATH_INFO. 836if(defined$parentrefname) { 837# if there is parent let the default be 'shortlog' action 838# (for http://git.example.com/repo.git/A..B links); if there 839# is no parent, dispatch will detect type of object and set 840# action appropriately if required (if action is not set) 841$input_params{'action'} ||="shortlog"; 842} 843if($input_params{'action'} && 844grep{$_eq$input_params{'action'} }@wants_base) { 845$input_params{'hash_base'} ||=$refname; 846}else{ 847$input_params{'hash'} ||=$refname; 848} 849} 850 851# next, handle the 'parent' part, if present 852if(defined$parentrefname) { 853# a missing pathspec defaults to the 'current' filename, allowing e.g. 854# someproject/blobdiff/oldrev..newrev:/filename 855if($parentpathname) { 856$parentpathname=~ s,^/+,,; 857$parentpathname=~ s,/$,,; 858$input_params{'file_parent'} ||=$parentpathname; 859}else{ 860$input_params{'file_parent'} ||=$input_params{'file_name'}; 861} 862# we assume that hash_parent_base is wanted if a path was specified, 863# or if the action wants hash_base instead of hash 864if(defined$input_params{'file_parent'} || 865grep{$_eq$input_params{'action'} }@wants_base) { 866$input_params{'hash_parent_base'} ||=$parentrefname; 867}else{ 868$input_params{'hash_parent'} ||=$parentrefname; 869} 870} 871 872# for the snapshot action, we allow URLs in the form 873# $project/snapshot/$hash.ext 874# where .ext determines the snapshot and gets removed from the 875# passed $refname to provide the $hash. 876# 877# To be able to tell that $refname includes the format extension, we 878# require the following two conditions to be satisfied: 879# - the hash input parameter MUST have been set from the $refname part 880# of the URL (i.e. they must be equal) 881# - the snapshot format MUST NOT have been defined already (e.g. from 882# CGI parameter sf) 883# It's also useless to try any matching unless $refname has a dot, 884# so we check for that too 885if(defined$input_params{'action'} && 886$input_params{'action'}eq'snapshot'&& 887defined$refname&&index($refname,'.') != -1&& 888$refnameeq$input_params{'hash'} && 889!defined$input_params{'snapshot_format'}) { 890# We loop over the known snapshot formats, checking for 891# extensions. Allowed extensions are both the defined suffix 892# (which includes the initial dot already) and the snapshot 893# format key itself, with a prepended dot 894while(my($fmt,$opt) =each%known_snapshot_formats) { 895my$hash=$refname; 896unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 897next; 898} 899my$sfx=$1; 900# a valid suffix was found, so set the snapshot format 901# and reset the hash parameter 902$input_params{'snapshot_format'} =$fmt; 903$input_params{'hash'} =$hash; 904# we also set the format suffix to the one requested 905# in the URL: this way a request for e.g. .tgz returns 906# a .tgz instead of a .tar.gz 907$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 908last; 909} 910} 911} 912 913our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 914$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 915$searchtext,$search_regexp); 916sub evaluate_and_validate_params { 917our$action=$input_params{'action'}; 918if(defined$action) { 919if(!validate_action($action)) { 920 die_error(400,"Invalid action parameter"); 921} 922} 923 924# parameters which are pathnames 925our$project=$input_params{'project'}; 926if(defined$project) { 927if(!validate_project($project)) { 928undef$project; 929 die_error(404,"No such project"); 930} 931} 932 933our$file_name=$input_params{'file_name'}; 934if(defined$file_name) { 935if(!validate_pathname($file_name)) { 936 die_error(400,"Invalid file parameter"); 937} 938} 939 940our$file_parent=$input_params{'file_parent'}; 941if(defined$file_parent) { 942if(!validate_pathname($file_parent)) { 943 die_error(400,"Invalid file parent parameter"); 944} 945} 946 947# parameters which are refnames 948our$hash=$input_params{'hash'}; 949if(defined$hash) { 950if(!validate_refname($hash)) { 951 die_error(400,"Invalid hash parameter"); 952} 953} 954 955our$hash_parent=$input_params{'hash_parent'}; 956if(defined$hash_parent) { 957if(!validate_refname($hash_parent)) { 958 die_error(400,"Invalid hash parent parameter"); 959} 960} 961 962our$hash_base=$input_params{'hash_base'}; 963if(defined$hash_base) { 964if(!validate_refname($hash_base)) { 965 die_error(400,"Invalid hash base parameter"); 966} 967} 968 969our@extra_options= @{$input_params{'extra_options'}}; 970# @extra_options is always defined, since it can only be (currently) set from 971# CGI, and $cgi->param() returns the empty array in array context if the param 972# is not set 973foreachmy$opt(@extra_options) { 974if(not exists$allowed_options{$opt}) { 975 die_error(400,"Invalid option parameter"); 976} 977if(not grep(/^$action$/, @{$allowed_options{$opt}})) { 978 die_error(400,"Invalid option parameter for this action"); 979} 980} 981 982our$hash_parent_base=$input_params{'hash_parent_base'}; 983if(defined$hash_parent_base) { 984if(!validate_refname($hash_parent_base)) { 985 die_error(400,"Invalid hash parent base parameter"); 986} 987} 988 989# other parameters 990our$page=$input_params{'page'}; 991if(defined$page) { 992if($page=~m/[^0-9]/) { 993 die_error(400,"Invalid page parameter"); 994} 995} 996 997our$searchtype=$input_params{'searchtype'}; 998if(defined$searchtype) { 999if($searchtype=~m/[^a-z]/) {1000 die_error(400,"Invalid searchtype parameter");1001}1002}10031004our$search_use_regexp=$input_params{'search_use_regexp'};10051006our$searchtext=$input_params{'searchtext'};1007our$search_regexp;1008if(defined$searchtext) {1009if(length($searchtext) <2) {1010 die_error(403,"At least two characters are required for search parameter");1011}1012$search_regexp=$search_use_regexp?$searchtext:quotemeta$searchtext;1013}1014}10151016# path to the current git repository1017our$git_dir;1018sub evaluate_git_dir {1019our$git_dir="$projectroot/$project"if$project;1020}10211022our(@snapshot_fmts,$git_avatar);1023sub configure_gitweb_features {1024# list of supported snapshot formats1025our@snapshot_fmts= gitweb_get_feature('snapshot');1026@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);10271028# check that the avatar feature is set to a known provider name,1029# and for each provider check if the dependencies are satisfied.1030# if the provider name is invalid or the dependencies are not met,1031# reset $git_avatar to the empty string.1032our($git_avatar) = gitweb_get_feature('avatar');1033if($git_avatareq'gravatar') {1034$git_avatar=''unless(eval{require Digest::MD5;1; });1035}elsif($git_avatareq'picon') {1036# no dependencies1037}else{1038$git_avatar='';1039}1040}10411042# custom error handler: 'die <message>' is Internal Server Error1043sub handle_errors_html {1044my$msg=shift;# it is already HTML escaped10451046# to avoid infinite loop where error occurs in die_error,1047# change handler to default handler, disabling handle_errors_html1048 set_message("Error occured when inside die_error:\n$msg");10491050# you cannot jump out of die_error when called as error handler;1051# the subroutine set via CGI::Carp::set_message is called _after_1052# HTTP headers are already written, so it cannot write them itself1053 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1054}1055set_message(\&handle_errors_html);10561057# dispatch1058sub dispatch {1059if(!defined$action) {1060if(defined$hash) {1061$action= git_get_type($hash);1062}elsif(defined$hash_base&&defined$file_name) {1063$action= git_get_type("$hash_base:$file_name");1064}elsif(defined$project) {1065$action='summary';1066}else{1067$action='project_list';1068}1069}1070if(!defined($actions{$action})) {1071 die_error(400,"Unknown action");1072}1073if($action!~m/^(?:opml|project_list|project_index)$/&&1074!$project) {1075 die_error(400,"Project needed");1076}1077$actions{$action}->();1078}10791080sub reset_timer {1081our$t0= [Time::HiRes::gettimeofday()]1082ifdefined$t0;1083our$number_of_git_cmds=0;1084}10851086sub run_request {1087 reset_timer();10881089 evaluate_uri();1090 evaluate_gitweb_config();1091 check_loadavg();10921093# $projectroot and $projects_list might be set in gitweb config file1094$projects_list||=$projectroot;10951096 evaluate_query_params();1097 evaluate_path_info();1098 evaluate_and_validate_params();1099 evaluate_git_dir();11001101 configure_gitweb_features();11021103 dispatch();1104}11051106our$is_last_request=sub{1};1107our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1108our$CGI='CGI';1109our$cgi;1110sub configure_as_fcgi {1111require CGI::Fast;1112our$CGI='CGI::Fast';11131114my$request_number=0;1115# let each child service 100 requests1116our$is_last_request=sub{ ++$request_number>100};1117}1118sub evaluate_argv {1119my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1120 configure_as_fcgi()1121if$script_name=~/\.fcgi$/;11221123return unless(@ARGV);11241125require Getopt::Long;1126 Getopt::Long::GetOptions(1127'fastcgi|fcgi|f'=> \&configure_as_fcgi,1128'nproc|n=i'=>sub{1129my($arg,$val) =@_;1130return unlesseval{require FCGI::ProcManager;1; };1131my$proc_manager= FCGI::ProcManager->new({1132 n_processes =>$val,1133});1134our$pre_listen_hook=sub{$proc_manager->pm_manage() };1135our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1136our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1137},1138);1139}11401141sub run {1142 evaluate_argv();1143 evaluate_git_version();11441145$pre_listen_hook->()1146if$pre_listen_hook;11471148 REQUEST:1149while($cgi=$CGI->new()) {1150$pre_dispatch_hook->()1151if$pre_dispatch_hook;11521153 run_request();11541155$post_dispatch_hook->()1156if$post_dispatch_hook;11571158last REQUEST if($is_last_request->());1159}11601161 DONE_GITWEB:11621;1163}11641165run();11661167if(defined caller) {1168# wrapped in a subroutine processing requests,1169# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1170return;1171}else{1172# pure CGI script, serving single request1173exit;1174}11751176## ======================================================================1177## action links11781179# possible values of extra options1180# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1181# -replay => 1 - start from a current view (replay with modifications)1182# -path_info => 0|1 - don't use/use path_info URL (if possible)1183sub href {1184my%params=@_;1185# default is to use -absolute url() i.e. $my_uri1186my$href=$params{-full} ?$my_url:$my_uri;11871188$params{'project'} =$projectunlessexists$params{'project'};11891190if($params{-replay}) {1191while(my($name,$symbol) =each%cgi_param_mapping) {1192if(!exists$params{$name}) {1193$params{$name} =$input_params{$name};1194}1195}1196}11971198my$use_pathinfo= gitweb_check_feature('pathinfo');1199if(defined$params{'project'} &&1200(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1201# try to put as many parameters as possible in PATH_INFO:1202# - project name1203# - action1204# - hash_parent or hash_parent_base:/file_parent1205# - hash or hash_base:/filename1206# - the snapshot_format as an appropriate suffix12071208# When the script is the root DirectoryIndex for the domain,1209# $href here would be something like http://gitweb.example.com/1210# Thus, we strip any trailing / from $href, to spare us double1211# slashes in the final URL1212$href=~ s,/$,,;12131214# Then add the project name, if present1215$href.="/".esc_url($params{'project'});1216delete$params{'project'};12171218# since we destructively absorb parameters, we keep this1219# boolean that remembers if we're handling a snapshot1220my$is_snapshot=$params{'action'}eq'snapshot';12211222# Summary just uses the project path URL, any other action is1223# added to the URL1224if(defined$params{'action'}) {1225$href.="/".esc_url($params{'action'})unless$params{'action'}eq'summary';1226delete$params{'action'};1227}12281229# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1230# stripping nonexistent or useless pieces1231$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1232||$params{'hash_parent'} ||$params{'hash'});1233if(defined$params{'hash_base'}) {1234if(defined$params{'hash_parent_base'}) {1235$href.= esc_url($params{'hash_parent_base'});1236# skip the file_parent if it's the same as the file_name1237if(defined$params{'file_parent'}) {1238if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1239delete$params{'file_parent'};1240}elsif($params{'file_parent'} !~/\.\./) {1241$href.=":/".esc_url($params{'file_parent'});1242delete$params{'file_parent'};1243}1244}1245$href.="..";1246delete$params{'hash_parent'};1247delete$params{'hash_parent_base'};1248}elsif(defined$params{'hash_parent'}) {1249$href.= esc_url($params{'hash_parent'})."..";1250delete$params{'hash_parent'};1251}12521253$href.= esc_url($params{'hash_base'});1254if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1255$href.=":/".esc_url($params{'file_name'});1256delete$params{'file_name'};1257}1258delete$params{'hash'};1259delete$params{'hash_base'};1260}elsif(defined$params{'hash'}) {1261$href.= esc_url($params{'hash'});1262delete$params{'hash'};1263}12641265# If the action was a snapshot, we can absorb the1266# snapshot_format parameter too1267if($is_snapshot) {1268my$fmt=$params{'snapshot_format'};1269# snapshot_format should always be defined when href()1270# is called, but just in case some code forgets, we1271# fall back to the default1272$fmt||=$snapshot_fmts[0];1273$href.=$known_snapshot_formats{$fmt}{'suffix'};1274delete$params{'snapshot_format'};1275}1276}12771278# now encode the parameters explicitly1279my@result= ();1280for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1281my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1282if(defined$params{$name}) {1283if(ref($params{$name})eq"ARRAY") {1284foreachmy$par(@{$params{$name}}) {1285push@result,$symbol."=". esc_param($par);1286}1287}else{1288push@result,$symbol."=". esc_param($params{$name});1289}1290}1291}1292$href.="?".join(';',@result)ifscalar@result;12931294return$href;1295}129612971298## ======================================================================1299## validation, quoting/unquoting and escaping13001301sub validate_action {1302my$input=shift||returnundef;1303returnundefunlessexists$actions{$input};1304return$input;1305}13061307sub validate_project {1308my$input=shift||returnundef;1309if(!validate_pathname($input) ||1310!(-d "$projectroot/$input") ||1311!check_export_ok("$projectroot/$input") ||1312($strict_export&& !project_in_list($input))) {1313returnundef;1314}else{1315return$input;1316}1317}13181319sub validate_pathname {1320my$input=shift||returnundef;13211322# no '.' or '..' as elements of path, i.e. no '.' nor '..'1323# at the beginning, at the end, and between slashes.1324# also this catches doubled slashes1325if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1326returnundef;1327}1328# no null characters1329if($input=~m!\0!) {1330returnundef;1331}1332return$input;1333}13341335sub validate_refname {1336my$input=shift||returnundef;13371338# textual hashes are O.K.1339if($input=~m/^[0-9a-fA-F]{40}$/) {1340return$input;1341}1342# it must be correct pathname1343$input= validate_pathname($input)1344orreturnundef;1345# restrictions on ref name according to git-check-ref-format1346if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1347returnundef;1348}1349return$input;1350}13511352# decode sequences of octets in utf8 into Perl's internal form,1353# which is utf-8 with utf8 flag set if needed. gitweb writes out1354# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1355sub to_utf8 {1356my$str=shift;1357returnundefunlessdefined$str;1358if(utf8::valid($str)) {1359 utf8::decode($str);1360return$str;1361}else{1362return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1363}1364}13651366# quote unsafe chars, but keep the slash, even when it's not1367# correct, but quoted slashes look too horrible in bookmarks1368sub esc_param {1369my$str=shift;1370returnundefunlessdefined$str;1371$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1372$str=~s/ /\+/g;1373return$str;1374}13751376# quote unsafe chars in whole URL, so some characters cannot be quoted1377sub esc_url {1378my$str=shift;1379returnundefunlessdefined$str;1380$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1381$str=~s/ /\+/g;1382return$str;1383}13841385# replace invalid utf8 character with SUBSTITUTION sequence1386sub esc_html {1387my$str=shift;1388my%opts=@_;13891390returnundefunlessdefined$str;13911392$str= to_utf8($str);1393$str=$cgi->escapeHTML($str);1394if($opts{'-nbsp'}) {1395$str=~s/ / /g;1396}1397$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1398return$str;1399}14001401# quote control characters and escape filename to HTML1402sub esc_path {1403my$str=shift;1404my%opts=@_;14051406returnundefunlessdefined$str;14071408$str= to_utf8($str);1409$str=$cgi->escapeHTML($str);1410if($opts{'-nbsp'}) {1411$str=~s/ / /g;1412}1413$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1414return$str;1415}14161417# Make control characters "printable", using character escape codes (CEC)1418sub quot_cec {1419my$cntrl=shift;1420my%opts=@_;1421my%es= (# character escape codes, aka escape sequences1422"\t"=>'\t',# tab (HT)1423"\n"=>'\n',# line feed (LF)1424"\r"=>'\r',# carrige return (CR)1425"\f"=>'\f',# form feed (FF)1426"\b"=>'\b',# backspace (BS)1427"\a"=>'\a',# alarm (bell) (BEL)1428"\e"=>'\e',# escape (ESC)1429"\013"=>'\v',# vertical tab (VT)1430"\000"=>'\0',# nul character (NUL)1431);1432my$chr= ( (exists$es{$cntrl})1433?$es{$cntrl}1434:sprintf('\%2x',ord($cntrl)) );1435if($opts{-nohtml}) {1436return$chr;1437}else{1438return"<span class=\"cntrl\">$chr</span>";1439}1440}14411442# Alternatively use unicode control pictures codepoints,1443# Unicode "printable representation" (PR)1444sub quot_upr {1445my$cntrl=shift;1446my%opts=@_;14471448my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1449if($opts{-nohtml}) {1450return$chr;1451}else{1452return"<span class=\"cntrl\">$chr</span>";1453}1454}14551456# git may return quoted and escaped filenames1457sub unquote {1458my$str=shift;14591460sub unq {1461my$seq=shift;1462my%es= (# character escape codes, aka escape sequences1463't'=>"\t",# tab (HT, TAB)1464'n'=>"\n",# newline (NL)1465'r'=>"\r",# return (CR)1466'f'=>"\f",# form feed (FF)1467'b'=>"\b",# backspace (BS)1468'a'=>"\a",# alarm (bell) (BEL)1469'e'=>"\e",# escape (ESC)1470'v'=>"\013",# vertical tab (VT)1471);14721473if($seq=~m/^[0-7]{1,3}$/) {1474# octal char sequence1475returnchr(oct($seq));1476}elsif(exists$es{$seq}) {1477# C escape sequence, aka character escape code1478return$es{$seq};1479}1480# quoted ordinary character1481return$seq;1482}14831484if($str=~m/^"(.*)"$/) {1485# needs unquoting1486$str=$1;1487$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1488}1489return$str;1490}14911492# escape tabs (convert tabs to spaces)1493sub untabify {1494my$line=shift;14951496while((my$pos=index($line,"\t")) != -1) {1497if(my$count= (8- ($pos%8))) {1498my$spaces=' ' x $count;1499$line=~s/\t/$spaces/;1500}1501}15021503return$line;1504}15051506sub project_in_list {1507my$project=shift;1508my@list= git_get_projects_list();1509return@list&&scalar(grep{$_->{'path'}eq$project}@list);1510}15111512## ----------------------------------------------------------------------1513## HTML aware string manipulation15141515# Try to chop given string on a word boundary between position1516# $len and $len+$add_len. If there is no word boundary there,1517# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1518# (marking chopped part) would be longer than given string.1519sub chop_str {1520my$str=shift;1521my$len=shift;1522my$add_len=shift||10;1523my$where=shift||'right';# 'left' | 'center' | 'right'15241525# Make sure perl knows it is utf8 encoded so we don't1526# cut in the middle of a utf8 multibyte char.1527$str= to_utf8($str);15281529# allow only $len chars, but don't cut a word if it would fit in $add_len1530# if it doesn't fit, cut it if it's still longer than the dots we would add1531# remove chopped character entities entirely15321533# when chopping in the middle, distribute $len into left and right part1534# return early if chopping wouldn't make string shorter1535if($whereeq'center') {1536return$strif($len+5>=length($str));# filler is length 51537$len=int($len/2);1538}else{1539return$strif($len+4>=length($str));# filler is length 41540}15411542# regexps: ending and beginning with word part up to $add_len1543my$endre=qr/.{$len}\w{0,$add_len}/;1544my$begre=qr/\w{0,$add_len}.{$len}/;15451546if($whereeq'left') {1547$str=~m/^(.*?)($begre)$/;1548my($lead,$body) = ($1,$2);1549if(length($lead) >4) {1550$lead=" ...";1551}1552return"$lead$body";15531554}elsif($whereeq'center') {1555$str=~m/^($endre)(.*)$/;1556my($left,$str) = ($1,$2);1557$str=~m/^(.*?)($begre)$/;1558my($mid,$right) = ($1,$2);1559if(length($mid) >5) {1560$mid=" ... ";1561}1562return"$left$mid$right";15631564}else{1565$str=~m/^($endre)(.*)$/;1566my$body=$1;1567my$tail=$2;1568if(length($tail) >4) {1569$tail="... ";1570}1571return"$body$tail";1572}1573}15741575# takes the same arguments as chop_str, but also wraps a <span> around the1576# result with a title attribute if it does get chopped. Additionally, the1577# string is HTML-escaped.1578sub chop_and_escape_str {1579my($str) =@_;15801581my$chopped= chop_str(@_);1582if($choppedeq$str) {1583return esc_html($chopped);1584}else{1585$str=~s/[[:cntrl:]]/?/g;1586return$cgi->span({-title=>$str}, esc_html($chopped));1587}1588}15891590## ----------------------------------------------------------------------1591## functions returning short strings15921593# CSS class for given age value (in seconds)1594sub age_class {1595my$age=shift;15961597if(!defined$age) {1598return"noage";1599}elsif($age<60*60*2) {1600return"age0";1601}elsif($age<60*60*24*2) {1602return"age1";1603}else{1604return"age2";1605}1606}16071608# convert age in seconds to "nn units ago" string1609sub age_string {1610my$age=shift;1611my$age_str;16121613if($age>60*60*24*365*2) {1614$age_str= (int$age/60/60/24/365);1615$age_str.=" years ago";1616}elsif($age>60*60*24*(365/12)*2) {1617$age_str=int$age/60/60/24/(365/12);1618$age_str.=" months ago";1619}elsif($age>60*60*24*7*2) {1620$age_str=int$age/60/60/24/7;1621$age_str.=" weeks ago";1622}elsif($age>60*60*24*2) {1623$age_str=int$age/60/60/24;1624$age_str.=" days ago";1625}elsif($age>60*60*2) {1626$age_str=int$age/60/60;1627$age_str.=" hours ago";1628}elsif($age>60*2) {1629$age_str=int$age/60;1630$age_str.=" min ago";1631}elsif($age>2) {1632$age_str=int$age;1633$age_str.=" sec ago";1634}else{1635$age_str.=" right now";1636}1637return$age_str;1638}16391640useconstant{1641 S_IFINVALID =>0030000,1642 S_IFGITLINK =>0160000,1643};16441645# submodule/subproject, a commit object reference1646sub S_ISGITLINK {1647my$mode=shift;16481649return(($mode& S_IFMT) == S_IFGITLINK)1650}16511652# convert file mode in octal to symbolic file mode string1653sub mode_str {1654my$mode=oct shift;16551656if(S_ISGITLINK($mode)) {1657return'm---------';1658}elsif(S_ISDIR($mode& S_IFMT)) {1659return'drwxr-xr-x';1660}elsif(S_ISLNK($mode)) {1661return'lrwxrwxrwx';1662}elsif(S_ISREG($mode)) {1663# git cares only about the executable bit1664if($mode& S_IXUSR) {1665return'-rwxr-xr-x';1666}else{1667return'-rw-r--r--';1668};1669}else{1670return'----------';1671}1672}16731674# convert file mode in octal to file type string1675sub file_type {1676my$mode=shift;16771678if($mode!~m/^[0-7]+$/) {1679return$mode;1680}else{1681$mode=oct$mode;1682}16831684if(S_ISGITLINK($mode)) {1685return"submodule";1686}elsif(S_ISDIR($mode& S_IFMT)) {1687return"directory";1688}elsif(S_ISLNK($mode)) {1689return"symlink";1690}elsif(S_ISREG($mode)) {1691return"file";1692}else{1693return"unknown";1694}1695}16961697# convert file mode in octal to file type description string1698sub file_type_long {1699my$mode=shift;17001701if($mode!~m/^[0-7]+$/) {1702return$mode;1703}else{1704$mode=oct$mode;1705}17061707if(S_ISGITLINK($mode)) {1708return"submodule";1709}elsif(S_ISDIR($mode& S_IFMT)) {1710return"directory";1711}elsif(S_ISLNK($mode)) {1712return"symlink";1713}elsif(S_ISREG($mode)) {1714if($mode& S_IXUSR) {1715return"executable";1716}else{1717return"file";1718};1719}else{1720return"unknown";1721}1722}172317241725## ----------------------------------------------------------------------1726## functions returning short HTML fragments, or transforming HTML fragments1727## which don't belong to other sections17281729# format line of commit message.1730sub format_log_line_html {1731my$line=shift;17321733$line= esc_html($line, -nbsp=>1);1734$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1735$cgi->a({-href => href(action=>"object", hash=>$1),1736-class=>"text"},$1);1737}eg;17381739return$line;1740}17411742# format marker of refs pointing to given object17431744# the destination action is chosen based on object type and current context:1745# - for annotated tags, we choose the tag view unless it's the current view1746# already, in which case we go to shortlog view1747# - for other refs, we keep the current view if we're in history, shortlog or1748# log view, and select shortlog otherwise1749sub format_ref_marker {1750my($refs,$id) =@_;1751my$markers='';17521753if(defined$refs->{$id}) {1754foreachmy$ref(@{$refs->{$id}}) {1755# this code exploits the fact that non-lightweight tags are the1756# only indirect objects, and that they are the only objects for which1757# we want to use tag instead of shortlog as action1758my($type,$name) =qw();1759my$indirect= ($ref=~s/\^\{\}$//);1760# e.g. tags/v2.6.11 or heads/next1761if($ref=~m!^(.*?)s?/(.*)$!) {1762$type=$1;1763$name=$2;1764}else{1765$type="ref";1766$name=$ref;1767}17681769my$class=$type;1770$class.=" indirect"if$indirect;17711772my$dest_action="shortlog";17731774if($indirect) {1775$dest_action="tag"unless$actioneq"tag";1776}elsif($action=~/^(history|(short)?log)$/) {1777$dest_action=$action;1778}17791780my$dest="";1781$dest.="refs/"unless$ref=~ m!^refs/!;1782$dest.=$ref;17831784my$link=$cgi->a({1785-href => href(1786 action=>$dest_action,1787 hash=>$dest1788)},$name);17891790$markers.=" <span class=\"$class\"title=\"$ref\">".1791$link."</span>";1792}1793}17941795if($markers) {1796return' <span class="refs">'.$markers.'</span>';1797}else{1798return"";1799}1800}18011802# format, perhaps shortened and with markers, title line1803sub format_subject_html {1804my($long,$short,$href,$extra) =@_;1805$extra=''unlessdefined($extra);18061807if(length($short) <length($long)) {1808$long=~s/[[:cntrl:]]/?/g;1809return$cgi->a({-href =>$href, -class=>"list subject",1810-title => to_utf8($long)},1811 esc_html($short)) .$extra;1812}else{1813return$cgi->a({-href =>$href, -class=>"list subject"},1814 esc_html($long)) .$extra;1815}1816}18171818# Rather than recomputing the url for an email multiple times, we cache it1819# after the first hit. This gives a visible benefit in views where the avatar1820# for the same email is used repeatedly (e.g. shortlog).1821# The cache is shared by all avatar engines (currently gravatar only), which1822# are free to use it as preferred. Since only one avatar engine is used for any1823# given page, there's no risk for cache conflicts.1824our%avatar_cache= ();18251826# Compute the picon url for a given email, by using the picon search service over at1827# http://www.cs.indiana.edu/picons/search.html1828sub picon_url {1829my$email=lc shift;1830if(!$avatar_cache{$email}) {1831my($user,$domain) =split('@',$email);1832$avatar_cache{$email} =1833"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1834"$domain/$user/".1835"users+domains+unknown/up/single";1836}1837return$avatar_cache{$email};1838}18391840# Compute the gravatar url for a given email, if it's not in the cache already.1841# Gravatar stores only the part of the URL before the size, since that's the1842# one computationally more expensive. This also allows reuse of the cache for1843# different sizes (for this particular engine).1844sub gravatar_url {1845my$email=lc shift;1846my$size=shift;1847$avatar_cache{$email} ||=1848"http://www.gravatar.com/avatar/".1849 Digest::MD5::md5_hex($email) ."?s=";1850return$avatar_cache{$email} .$size;1851}18521853# Insert an avatar for the given $email at the given $size if the feature1854# is enabled.1855sub git_get_avatar {1856my($email,%opts) =@_;1857my$pre_white= ($opts{-pad_before} ?" ":"");1858my$post_white= ($opts{-pad_after} ?" ":"");1859$opts{-size} ||='default';1860my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1861my$url="";1862if($git_avatareq'gravatar') {1863$url= gravatar_url($email,$size);1864}elsif($git_avatareq'picon') {1865$url= picon_url($email);1866}1867# Other providers can be added by extending the if chain, defining $url1868# as needed. If no variant puts something in $url, we assume avatars1869# are completely disabled/unavailable.1870if($url) {1871return$pre_white.1872"<img width=\"$size\"".1873"class=\"avatar\"".1874"src=\"$url\"".1875"alt=\"\"".1876"/>".$post_white;1877}else{1878return"";1879}1880}18811882sub format_search_author {1883my($author,$searchtype,$displaytext) =@_;1884my$have_search= gitweb_check_feature('search');18851886if($have_search) {1887my$performed="";1888if($searchtypeeq'author') {1889$performed="authored";1890}elsif($searchtypeeq'committer') {1891$performed="committed";1892}18931894return$cgi->a({-href => href(action=>"search", hash=>$hash,1895 searchtext=>$author,1896 searchtype=>$searchtype),class=>"list",1897 title=>"Search for commits$performedby$author"},1898$displaytext);18991900}else{1901return$displaytext;1902}1903}19041905# format the author name of the given commit with the given tag1906# the author name is chopped and escaped according to the other1907# optional parameters (see chop_str).1908sub format_author_html {1909my$tag=shift;1910my$co=shift;1911my$author= chop_and_escape_str($co->{'author_name'},@_);1912return"<$tagclass=\"author\">".1913 format_search_author($co->{'author_name'},"author",1914 git_get_avatar($co->{'author_email'}, -pad_after =>1) .1915$author) .1916"</$tag>";1917}19181919# format git diff header line, i.e. "diff --(git|combined|cc) ..."1920sub format_git_diff_header_line {1921my$line=shift;1922my$diffinfo=shift;1923my($from,$to) =@_;19241925if($diffinfo->{'nparents'}) {1926# combined diff1927$line=~s!^(diff (.*?) )"?.*$!$1!;1928if($to->{'href'}) {1929$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1930 esc_path($to->{'file'}));1931}else{# file was deleted (no href)1932$line.= esc_path($to->{'file'});1933}1934}else{1935# "ordinary" diff1936$line=~s!^(diff (.*?) )"?a/.*$!$1!;1937if($from->{'href'}) {1938$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},1939'a/'. esc_path($from->{'file'}));1940}else{# file was added (no href)1941$line.='a/'. esc_path($from->{'file'});1942}1943$line.=' ';1944if($to->{'href'}) {1945$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1946'b/'. esc_path($to->{'file'}));1947}else{# file was deleted1948$line.='b/'. esc_path($to->{'file'});1949}1950}19511952return"<div class=\"diff header\">$line</div>\n";1953}19541955# format extended diff header line, before patch itself1956sub format_extended_diff_header_line {1957my$line=shift;1958my$diffinfo=shift;1959my($from,$to) =@_;19601961# match <path>1962if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {1963$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},1964 esc_path($from->{'file'}));1965}1966if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {1967$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},1968 esc_path($to->{'file'}));1969}1970# match single <mode>1971if($line=~m/\s(\d{6})$/) {1972$line.='<span class="info"> ('.1973 file_type_long($1) .1974')</span>';1975}1976# match <hash>1977if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {1978# can match only for combined diff1979$line='index ';1980for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {1981if($from->{'href'}[$i]) {1982$line.=$cgi->a({-href=>$from->{'href'}[$i],1983-class=>"hash"},1984substr($diffinfo->{'from_id'}[$i],0,7));1985}else{1986$line.='0' x 7;1987}1988# separator1989$line.=','if($i<$diffinfo->{'nparents'} -1);1990}1991$line.='..';1992if($to->{'href'}) {1993$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},1994substr($diffinfo->{'to_id'},0,7));1995}else{1996$line.='0' x 7;1997}19981999}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {2000# can match only for ordinary diff2001my($from_link,$to_link);2002if($from->{'href'}) {2003$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},2004substr($diffinfo->{'from_id'},0,7));2005}else{2006$from_link='0' x 7;2007}2008if($to->{'href'}) {2009$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2010substr($diffinfo->{'to_id'},0,7));2011}else{2012$to_link='0' x 7;2013}2014my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});2015$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;2016}20172018return$line."<br/>\n";2019}20202021# format from-file/to-file diff header2022sub format_diff_from_to_header {2023my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2024my$line;2025my$result='';20262027$line=$from_line;2028#assert($line =~ m/^---/) if DEBUG;2029# no extra formatting for "^--- /dev/null"2030if(!$diffinfo->{'nparents'}) {2031# ordinary (single parent) diff2032if($line=~m!^--- "?a/!) {2033if($from->{'href'}) {2034$line='--- a/'.2035$cgi->a({-href=>$from->{'href'}, -class=>"path"},2036 esc_path($from->{'file'}));2037}else{2038$line='--- a/'.2039 esc_path($from->{'file'});2040}2041}2042$result.= qq!<div class="diff from_file">$line</div>\n!;20432044}else{2045# combined diff (merge commit)2046for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2047if($from->{'href'}[$i]) {2048$line='--- '.2049$cgi->a({-href=>href(action=>"blobdiff",2050 hash_parent=>$diffinfo->{'from_id'}[$i],2051 hash_parent_base=>$parents[$i],2052 file_parent=>$from->{'file'}[$i],2053 hash=>$diffinfo->{'to_id'},2054 hash_base=>$hash,2055 file_name=>$to->{'file'}),2056-class=>"path",2057-title=>"diff". ($i+1)},2058$i+1) .2059'/'.2060$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2061 esc_path($from->{'file'}[$i]));2062}else{2063$line='--- /dev/null';2064}2065$result.= qq!<div class="diff from_file">$line</div>\n!;2066}2067}20682069$line=$to_line;2070#assert($line =~ m/^\+\+\+/) if DEBUG;2071# no extra formatting for "^+++ /dev/null"2072if($line=~m!^\+\+\+ "?b/!) {2073if($to->{'href'}) {2074$line='+++ b/'.2075$cgi->a({-href=>$to->{'href'}, -class=>"path"},2076 esc_path($to->{'file'}));2077}else{2078$line='+++ b/'.2079 esc_path($to->{'file'});2080}2081}2082$result.= qq!<div class="diff to_file">$line</div>\n!;20832084return$result;2085}20862087# create note for patch simplified by combined diff2088sub format_diff_cc_simplified {2089my($diffinfo,@parents) =@_;2090my$result='';20912092$result.="<div class=\"diff header\">".2093"diff --cc ";2094if(!is_deleted($diffinfo)) {2095$result.=$cgi->a({-href => href(action=>"blob",2096 hash_base=>$hash,2097 hash=>$diffinfo->{'to_id'},2098 file_name=>$diffinfo->{'to_file'}),2099-class=>"path"},2100 esc_path($diffinfo->{'to_file'}));2101}else{2102$result.= esc_path($diffinfo->{'to_file'});2103}2104$result.="</div>\n".# class="diff header"2105"<div class=\"diff nodifferences\">".2106"Simple merge".2107"</div>\n";# class="diff nodifferences"21082109return$result;2110}21112112# format patch (diff) line (not to be used for diff headers)2113sub format_diff_line {2114my$line=shift;2115my($from,$to) =@_;2116my$diff_class="";21172118chomp$line;21192120if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2121# combined diff2122my$prefix=substr($line,0,scalar@{$from->{'href'}});2123if($line=~m/^\@{3}/) {2124$diff_class=" chunk_header";2125}elsif($line=~m/^\\/) {2126$diff_class=" incomplete";2127}elsif($prefix=~tr/+/+/) {2128$diff_class=" add";2129}elsif($prefix=~tr/-/-/) {2130$diff_class=" rem";2131}2132}else{2133# assume ordinary diff2134my$char=substr($line,0,1);2135if($chareq'+') {2136$diff_class=" add";2137}elsif($chareq'-') {2138$diff_class=" rem";2139}elsif($chareq'@') {2140$diff_class=" chunk_header";2141}elsif($chareq"\\") {2142$diff_class=" incomplete";2143}2144}2145$line= untabify($line);2146if($from&&$to&&$line=~m/^\@{2} /) {2147my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2148$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;21492150$from_lines=0unlessdefined$from_lines;2151$to_lines=0unlessdefined$to_lines;21522153if($from->{'href'}) {2154$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2155-class=>"list"},$from_text);2156}2157if($to->{'href'}) {2158$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2159-class=>"list"},$to_text);2160}2161$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2162"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2163return"<div class=\"diff$diff_class\">$line</div>\n";2164}elsif($from&&$to&&$line=~m/^\@{3}/) {2165my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2166my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);21672168@from_text=split(' ',$ranges);2169for(my$i=0;$i<@from_text; ++$i) {2170($from_start[$i],$from_nlines[$i]) =2171(split(',',substr($from_text[$i],1)),0);2172}21732174$to_text=pop@from_text;2175$to_start=pop@from_start;2176$to_nlines=pop@from_nlines;21772178$line="<span class=\"chunk_info\">$prefix";2179for(my$i=0;$i<@from_text; ++$i) {2180if($from->{'href'}[$i]) {2181$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2182-class=>"list"},$from_text[$i]);2183}else{2184$line.=$from_text[$i];2185}2186$line.=" ";2187}2188if($to->{'href'}) {2189$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2190-class=>"list"},$to_text);2191}else{2192$line.=$to_text;2193}2194$line.="$prefix</span>".2195"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2196return"<div class=\"diff$diff_class\">$line</div>\n";2197}2198return"<div class=\"diff$diff_class\">". esc_html($line, -nbsp=>1) ."</div>\n";2199}22002201# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2202# linked. Pass the hash of the tree/commit to snapshot.2203sub format_snapshot_links {2204my($hash) =@_;2205my$num_fmts=@snapshot_fmts;2206if($num_fmts>1) {2207# A parenthesized list of links bearing format names.2208# e.g. "snapshot (_tar.gz_ _zip_)"2209return"snapshot (".join(' ',map2210$cgi->a({2211-href => href(2212 action=>"snapshot",2213 hash=>$hash,2214 snapshot_format=>$_2215)2216},$known_snapshot_formats{$_}{'display'})2217,@snapshot_fmts) .")";2218}elsif($num_fmts==1) {2219# A single "snapshot" link whose tooltip bears the format name.2220# i.e. "_snapshot_"2221my($fmt) =@snapshot_fmts;2222return2223$cgi->a({2224-href => href(2225 action=>"snapshot",2226 hash=>$hash,2227 snapshot_format=>$fmt2228),2229-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2230},"snapshot");2231}else{# $num_fmts == 02232returnundef;2233}2234}22352236## ......................................................................2237## functions returning values to be passed, perhaps after some2238## transformation, to other functions; e.g. returning arguments to href()22392240# returns hash to be passed to href to generate gitweb URL2241# in -title key it returns description of link2242sub get_feed_info {2243my$format=shift||'Atom';2244my%res= (action =>lc($format));22452246# feed links are possible only for project views2247return unless(defined$project);2248# some views should link to OPML, or to generic project feed,2249# or don't have specific feed yet (so they should use generic)2250return if($action=~/^(?:tags|heads|forks|tag|search)$/x);22512252my$branch;2253# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2254# from tag links; this also makes possible to detect branch links2255if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2256(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2257$branch=$1;2258}2259# find log type for feed description (title)2260my$type='log';2261if(defined$file_name) {2262$type="history of$file_name";2263$type.="/"if($actioneq'tree');2264$type.=" on '$branch'"if(defined$branch);2265}else{2266$type="log of$branch"if(defined$branch);2267}22682269$res{-title} =$type;2270$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2271$res{'file_name'} =$file_name;22722273return%res;2274}22752276## ----------------------------------------------------------------------2277## git utility subroutines, invoking git commands22782279# returns path to the core git executable and the --git-dir parameter as list2280sub git_cmd {2281$number_of_git_cmds++;2282return$GIT,'--git-dir='.$git_dir;2283}22842285# quote the given arguments for passing them to the shell2286# quote_command("command", "arg 1", "arg with ' and ! characters")2287# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2288# Try to avoid using this function wherever possible.2289sub quote_command {2290returnjoin(' ',2291map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2292}22932294# get HEAD ref of given project as hash2295sub git_get_head_hash {2296return git_get_full_hash(shift,'HEAD');2297}22982299sub git_get_full_hash {2300return git_get_hash(@_);2301}23022303sub git_get_short_hash {2304return git_get_hash(@_,'--short=7');2305}23062307sub git_get_hash {2308my($project,$hash,@options) =@_;2309my$o_git_dir=$git_dir;2310my$retval=undef;2311$git_dir="$projectroot/$project";2312if(open my$fd,'-|', git_cmd(),'rev-parse',2313'--verify','-q',@options,$hash) {2314$retval= <$fd>;2315chomp$retvalifdefined$retval;2316close$fd;2317}2318if(defined$o_git_dir) {2319$git_dir=$o_git_dir;2320}2321return$retval;2322}23232324# get type of given object2325sub git_get_type {2326my$hash=shift;23272328open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2329my$type= <$fd>;2330close$fdorreturn;2331chomp$type;2332return$type;2333}23342335# repository configuration2336our$config_file='';2337our%config;23382339# store multiple values for single key as anonymous array reference2340# single values stored directly in the hash, not as [ <value> ]2341sub hash_set_multi {2342my($hash,$key,$value) =@_;23432344if(!exists$hash->{$key}) {2345$hash->{$key} =$value;2346}elsif(!ref$hash->{$key}) {2347$hash->{$key} = [$hash->{$key},$value];2348}else{2349push@{$hash->{$key}},$value;2350}2351}23522353# return hash of git project configuration2354# optionally limited to some section, e.g. 'gitweb'2355sub git_parse_project_config {2356my$section_regexp=shift;2357my%config;23582359local$/="\0";23602361open my$fh,"-|", git_cmd(),"config",'-z','-l',2362orreturn;23632364while(my$keyval= <$fh>) {2365chomp$keyval;2366my($key,$value) =split(/\n/,$keyval,2);23672368 hash_set_multi(\%config,$key,$value)2369if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2370}2371close$fh;23722373return%config;2374}23752376# convert config value to boolean: 'true' or 'false'2377# no value, number > 0, 'true' and 'yes' values are true2378# rest of values are treated as false (never as error)2379sub config_to_bool {2380my$val=shift;23812382return1if!defined$val;# section.key23832384# strip leading and trailing whitespace2385$val=~s/^\s+//;2386$val=~s/\s+$//;23872388return(($val=~/^\d+$/&&$val) ||# section.key = 12389($val=~/^(?:true|yes)$/i));# section.key = true2390}23912392# convert config value to simple decimal number2393# an optional value suffix of 'k', 'm', or 'g' will cause the value2394# to be multiplied by 1024, 1048576, or 10737418242395sub config_to_int {2396my$val=shift;23972398# strip leading and trailing whitespace2399$val=~s/^\s+//;2400$val=~s/\s+$//;24012402if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2403$unit=lc($unit);2404# unknown unit is treated as 12405return$num* ($uniteq'g'?1073741824:2406$uniteq'm'?1048576:2407$uniteq'k'?1024:1);2408}2409return$val;2410}24112412# convert config value to array reference, if needed2413sub config_to_multi {2414my$val=shift;24152416returnref($val) ?$val: (defined($val) ? [$val] : []);2417}24182419sub git_get_project_config {2420my($key,$type) =@_;24212422return unlessdefined$git_dir;24232424# key sanity check2425return unless($key);2426$key=~s/^gitweb\.//;2427return if($key=~m/\W/);24282429# type sanity check2430if(defined$type) {2431$type=~s/^--//;2432$type=undef2433unless($typeeq'bool'||$typeeq'int');2434}24352436# get config2437if(!defined$config_file||2438$config_filene"$git_dir/config") {2439%config= git_parse_project_config('gitweb');2440$config_file="$git_dir/config";2441}24422443# check if config variable (key) exists2444return unlessexists$config{"gitweb.$key"};24452446# ensure given type2447if(!defined$type) {2448return$config{"gitweb.$key"};2449}elsif($typeeq'bool') {2450# backward compatibility: 'git config --bool' returns true/false2451return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2452}elsif($typeeq'int') {2453return config_to_int($config{"gitweb.$key"});2454}2455return$config{"gitweb.$key"};2456}24572458# get hash of given path at given ref2459sub git_get_hash_by_path {2460my$base=shift;2461my$path=shift||returnundef;2462my$type=shift;24632464$path=~ s,/+$,,;24652466open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2467or die_error(500,"Open git-ls-tree failed");2468my$line= <$fd>;2469close$fdorreturnundef;24702471if(!defined$line) {2472# there is no tree or hash given by $path at $base2473returnundef;2474}24752476#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2477$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2478if(defined$type&&$typene$2) {2479# type doesn't match2480returnundef;2481}2482return$3;2483}24842485# get path of entry with given hash at given tree-ish (ref)2486# used to get 'from' filename for combined diff (merge commit) for renames2487sub git_get_path_by_hash {2488my$base=shift||return;2489my$hash=shift||return;24902491local$/="\0";24922493open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2494orreturnundef;2495while(my$line= <$fd>) {2496chomp$line;24972498#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2499#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2500if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2501close$fd;2502return$1;2503}2504}2505close$fd;2506returnundef;2507}25082509## ......................................................................2510## git utility functions, directly accessing git repository25112512sub git_get_project_description {2513my$path=shift;25142515$git_dir="$projectroot/$path";2516open my$fd,'<',"$git_dir/description"2517orreturn git_get_project_config('description');2518my$descr= <$fd>;2519close$fd;2520if(defined$descr) {2521chomp$descr;2522}2523return$descr;2524}25252526sub git_get_project_ctags {2527my$path=shift;2528my$ctags= {};25292530$git_dir="$projectroot/$path";2531opendir my$dh,"$git_dir/ctags"2532orreturn$ctags;2533foreach(grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh)) {2534open my$ct,'<',$_ornext;2535my$val= <$ct>;2536chomp$val;2537close$ct;2538my$ctag=$_;$ctag=~ s#.*/##;2539$ctags->{$ctag} =$val;2540}2541closedir$dh;2542$ctags;2543}25442545sub git_populate_project_tagcloud {2546my$ctags=shift;25472548# First, merge different-cased tags; tags vote on casing2549my%ctags_lc;2550foreach(keys%$ctags) {2551$ctags_lc{lc$_}->{count} +=$ctags->{$_};2552if(not$ctags_lc{lc$_}->{topcount}2553or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2554$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2555$ctags_lc{lc$_}->{topname} =$_;2556}2557}25582559my$cloud;2560if(eval{require HTML::TagCloud;1; }) {2561$cloud= HTML::TagCloud->new;2562foreach(sort keys%ctags_lc) {2563# Pad the title with spaces so that the cloud looks2564# less crammed.2565my$title=$ctags_lc{$_}->{topname};2566$title=~s/ / /g;2567$title=~s/^/ /g;2568$title=~s/$/ /g;2569$cloud->add($title,$home_link."?by_tag=".$_,$ctags_lc{$_}->{count});2570}2571}else{2572$cloud= \%ctags_lc;2573}2574$cloud;2575}25762577sub git_show_project_tagcloud {2578my($cloud,$count) =@_;2579print STDERR ref($cloud)."..\n";2580if(ref$cloudeq'HTML::TagCloud') {2581return$cloud->html_and_css($count);2582}else{2583my@tags=sort{$cloud->{$a}->{count} <=>$cloud->{$b}->{count} }keys%$cloud;2584return'<p align="center">'.join(', ',map{2585"<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"2586}splice(@tags,0,$count)) .'</p>';2587}2588}25892590sub git_get_project_url_list {2591my$path=shift;25922593$git_dir="$projectroot/$path";2594open my$fd,'<',"$git_dir/cloneurl"2595orreturnwantarray?2596@{ config_to_multi(git_get_project_config('url')) } :2597 config_to_multi(git_get_project_config('url'));2598my@git_project_url_list=map{chomp;$_} <$fd>;2599close$fd;26002601returnwantarray?@git_project_url_list: \@git_project_url_list;2602}26032604sub git_get_projects_list {2605my($filter) =@_;2606my@list;26072608$filter||='';2609$filter=~s/\.git$//;26102611my$check_forks= gitweb_check_feature('forks');26122613if(-d $projects_list) {2614# search in directory2615my$dir=$projects_list. ($filter?"/$filter":'');2616# remove the trailing "/"2617$dir=~s!/+$!!;2618my$pfxlen=length("$dir");2619my$pfxdepth= ($dir=~tr!/!!);26202621 File::Find::find({2622 follow_fast =>1,# follow symbolic links2623 follow_skip =>2,# ignore duplicates2624 dangling_symlinks =>0,# ignore dangling symlinks, silently2625 wanted =>sub{2626# global variables2627our$project_maxdepth;2628our$projectroot;2629# skip project-list toplevel, if we get it.2630return if(m!^[/.]$!);2631# only directories can be git repositories2632return unless(-d $_);2633# don't traverse too deep (Find is super slow on os x)2634if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2635$File::Find::prune =1;2636return;2637}26382639my$subdir=substr($File::Find::name,$pfxlen+1);2640# we check related file in $projectroot2641my$path= ($filter?"$filter/":'') .$subdir;2642if(check_export_ok("$projectroot/$path")) {2643push@list, { path =>$path};2644$File::Find::prune =1;2645}2646},2647},"$dir");26482649}elsif(-f $projects_list) {2650# read from file(url-encoded):2651# 'git%2Fgit.git Linus+Torvalds'2652# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2653# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2654my%paths;2655open my$fd,'<',$projects_listorreturn;2656 PROJECT:2657while(my$line= <$fd>) {2658chomp$line;2659my($path,$owner) =split' ',$line;2660$path= unescape($path);2661$owner= unescape($owner);2662if(!defined$path) {2663next;2664}2665if($filterne'') {2666# looking for forks;2667my$pfx=substr($path,0,length($filter));2668if($pfxne$filter) {2669next PROJECT;2670}2671my$sfx=substr($path,length($filter));2672if($sfx!~/^\/.*\.git$/) {2673next PROJECT;2674}2675}elsif($check_forks) {2676 PATH:2677foreachmy$filter(keys%paths) {2678# looking for forks;2679my$pfx=substr($path,0,length($filter));2680if($pfxne$filter) {2681next PATH;2682}2683my$sfx=substr($path,length($filter));2684if($sfx!~/^\/.*\.git$/) {2685next PATH;2686}2687# is a fork, don't include it in2688# the list2689next PROJECT;2690}2691}2692if(check_export_ok("$projectroot/$path")) {2693my$pr= {2694 path =>$path,2695 owner => to_utf8($owner),2696};2697push@list,$pr;2698(my$forks_path=$path) =~s/\.git$//;2699$paths{$forks_path}++;2700}2701}2702close$fd;2703}2704return@list;2705}27062707our$gitweb_project_owner=undef;2708sub git_get_project_list_from_file {27092710return if(defined$gitweb_project_owner);27112712$gitweb_project_owner= {};2713# read from file (url-encoded):2714# 'git%2Fgit.git Linus+Torvalds'2715# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2716# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2717if(-f $projects_list) {2718open(my$fd,'<',$projects_list);2719while(my$line= <$fd>) {2720chomp$line;2721my($pr,$ow) =split' ',$line;2722$pr= unescape($pr);2723$ow= unescape($ow);2724$gitweb_project_owner->{$pr} = to_utf8($ow);2725}2726close$fd;2727}2728}27292730sub git_get_project_owner {2731my$project=shift;2732my$owner;27332734returnundefunless$project;2735$git_dir="$projectroot/$project";27362737if(!defined$gitweb_project_owner) {2738 git_get_project_list_from_file();2739}27402741if(exists$gitweb_project_owner->{$project}) {2742$owner=$gitweb_project_owner->{$project};2743}2744if(!defined$owner){2745$owner= git_get_project_config('owner');2746}2747if(!defined$owner) {2748$owner= get_file_owner("$git_dir");2749}27502751return$owner;2752}27532754sub git_get_last_activity {2755my($path) =@_;2756my$fd;27572758$git_dir="$projectroot/$path";2759open($fd,"-|", git_cmd(),'for-each-ref',2760'--format=%(committer)',2761'--sort=-committerdate',2762'--count=1',2763'refs/heads')orreturn;2764my$most_recent= <$fd>;2765close$fdorreturn;2766if(defined$most_recent&&2767$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {2768my$timestamp=$1;2769my$age=time-$timestamp;2770return($age, age_string($age));2771}2772return(undef,undef);2773}27742775sub git_get_references {2776my$type=shift||"";2777my%refs;2778# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.112779# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}2780open my$fd,"-|", git_cmd(),"show-ref","--dereference",2781($type? ("--","refs/$type") : ())# use -- <pattern> if $type2782orreturn;27832784while(my$line= <$fd>) {2785chomp$line;2786if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {2787if(defined$refs{$1}) {2788push@{$refs{$1}},$2;2789}else{2790$refs{$1} = [$2];2791}2792}2793}2794close$fdorreturn;2795return \%refs;2796}27972798sub git_get_rev_name_tags {2799my$hash=shift||returnundef;28002801open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash2802orreturn;2803my$name_rev= <$fd>;2804close$fd;28052806if($name_rev=~ m|^$hash tags/(.*)$|) {2807return$1;2808}else{2809# catches also '$hash undefined' output2810returnundef;2811}2812}28132814## ----------------------------------------------------------------------2815## parse to hash functions28162817sub parse_date {2818my$epoch=shift;2819my$tz=shift||"-0000";28202821my%date;2822my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");2823my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");2824my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);2825$date{'hour'} =$hour;2826$date{'minute'} =$min;2827$date{'mday'} =$mday;2828$date{'day'} =$days[$wday];2829$date{'month'} =$months[$mon];2830$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",2831$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;2832$date{'mday-time'} =sprintf"%d%s%02d:%02d",2833$mday,$months[$mon],$hour,$min;2834$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",28351900+$year,1+$mon,$mday,$hour,$min,$sec;28362837$tz=~m/^([+\-][0-9][0-9])([0-9][0-9])$/;2838my$local=$epoch+ ((int$1+ ($2/60)) *3600);2839($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);2840$date{'hour_local'} =$hour;2841$date{'minute_local'} =$min;2842$date{'tz_local'} =$tz;2843$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",28441900+$year,$mon+1,$mday,2845$hour,$min,$sec,$tz);2846return%date;2847}28482849sub parse_tag {2850my$tag_id=shift;2851my%tag;2852my@comment;28532854open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;2855$tag{'id'} =$tag_id;2856while(my$line= <$fd>) {2857chomp$line;2858if($line=~m/^object ([0-9a-fA-F]{40})$/) {2859$tag{'object'} =$1;2860}elsif($line=~m/^type (.+)$/) {2861$tag{'type'} =$1;2862}elsif($line=~m/^tag (.+)$/) {2863$tag{'name'} =$1;2864}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {2865$tag{'author'} =$1;2866$tag{'author_epoch'} =$2;2867$tag{'author_tz'} =$3;2868if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {2869$tag{'author_name'} =$1;2870$tag{'author_email'} =$2;2871}else{2872$tag{'author_name'} =$tag{'author'};2873}2874}elsif($line=~m/--BEGIN/) {2875push@comment,$line;2876last;2877}elsif($lineeq"") {2878last;2879}2880}2881push@comment, <$fd>;2882$tag{'comment'} = \@comment;2883close$fdorreturn;2884if(!defined$tag{'name'}) {2885return2886};2887return%tag2888}28892890sub parse_commit_text {2891my($commit_text,$withparents) =@_;2892my@commit_lines=split'\n',$commit_text;2893my%co;28942895pop@commit_lines;# Remove '\0'28962897if(!@commit_lines) {2898return;2899}29002901my$header=shift@commit_lines;2902if($header!~m/^[0-9a-fA-F]{40}/) {2903return;2904}2905($co{'id'},my@parents) =split' ',$header;2906while(my$line=shift@commit_lines) {2907last if$lineeq"\n";2908if($line=~m/^tree ([0-9a-fA-F]{40})$/) {2909$co{'tree'} =$1;2910}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {2911push@parents,$1;2912}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {2913$co{'author'} = to_utf8($1);2914$co{'author_epoch'} =$2;2915$co{'author_tz'} =$3;2916if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {2917$co{'author_name'} =$1;2918$co{'author_email'} =$2;2919}else{2920$co{'author_name'} =$co{'author'};2921}2922}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {2923$co{'committer'} = to_utf8($1);2924$co{'committer_epoch'} =$2;2925$co{'committer_tz'} =$3;2926if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {2927$co{'committer_name'} =$1;2928$co{'committer_email'} =$2;2929}else{2930$co{'committer_name'} =$co{'committer'};2931}2932}2933}2934if(!defined$co{'tree'}) {2935return;2936};2937$co{'parents'} = \@parents;2938$co{'parent'} =$parents[0];29392940foreachmy$title(@commit_lines) {2941$title=~s/^ //;2942if($titlene"") {2943$co{'title'} = chop_str($title,80,5);2944# remove leading stuff of merges to make the interesting part visible2945if(length($title) >50) {2946$title=~s/^Automatic //;2947$title=~s/^merge (of|with) /Merge ... /i;2948if(length($title) >50) {2949$title=~s/(http|rsync):\/\///;2950}2951if(length($title) >50) {2952$title=~s/(master|www|rsync)\.//;2953}2954if(length($title) >50) {2955$title=~s/kernel.org:?//;2956}2957if(length($title) >50) {2958$title=~s/\/pub\/scm//;2959}2960}2961$co{'title_short'} = chop_str($title,50,5);2962last;2963}2964}2965if(!defined$co{'title'} ||$co{'title'}eq"") {2966$co{'title'} =$co{'title_short'} ='(no commit message)';2967}2968# remove added spaces2969foreachmy$line(@commit_lines) {2970$line=~s/^ //;2971}2972$co{'comment'} = \@commit_lines;29732974my$age=time-$co{'committer_epoch'};2975$co{'age'} =$age;2976$co{'age_string'} = age_string($age);2977my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});2978if($age>60*60*24*7*2) {2979$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;2980$co{'age_string_age'} =$co{'age_string'};2981}else{2982$co{'age_string_date'} =$co{'age_string'};2983$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;2984}2985return%co;2986}29872988sub parse_commit {2989my($commit_id) =@_;2990my%co;29912992local$/="\0";29932994open my$fd,"-|", git_cmd(),"rev-list",2995"--parents",2996"--header",2997"--max-count=1",2998$commit_id,2999"--",3000or die_error(500,"Open git-rev-list failed");3001%co= parse_commit_text(<$fd>,1);3002close$fd;30033004return%co;3005}30063007sub parse_commits {3008my($commit_id,$maxcount,$skip,$filename,@args) =@_;3009my@cos;30103011$maxcount||=1;3012$skip||=0;30133014local$/="\0";30153016open my$fd,"-|", git_cmd(),"rev-list",3017"--header",3018@args,3019("--max-count=".$maxcount),3020("--skip=".$skip),3021@extra_options,3022$commit_id,3023"--",3024($filename? ($filename) : ())3025or die_error(500,"Open git-rev-list failed");3026while(my$line= <$fd>) {3027my%co= parse_commit_text($line);3028push@cos, \%co;3029}3030close$fd;30313032returnwantarray?@cos: \@cos;3033}30343035# parse line of git-diff-tree "raw" output3036sub parse_difftree_raw_line {3037my$line=shift;3038my%res;30393040# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3041# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3042if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3043$res{'from_mode'} =$1;3044$res{'to_mode'} =$2;3045$res{'from_id'} =$3;3046$res{'to_id'} =$4;3047$res{'status'} =$5;3048$res{'similarity'} =$6;3049if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3050($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3051}else{3052$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3053}3054}3055# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3056# combined diff (for merge commit)3057elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3058$res{'nparents'} =length($1);3059$res{'from_mode'} = [split(' ',$2) ];3060$res{'to_mode'} =pop@{$res{'from_mode'}};3061$res{'from_id'} = [split(' ',$3) ];3062$res{'to_id'} =pop@{$res{'from_id'}};3063$res{'status'} = [split('',$4) ];3064$res{'to_file'} = unquote($5);3065}3066# 'c512b523472485aef4fff9e57b229d9d243c967f'3067elsif($line=~m/^([0-9a-fA-F]{40})$/) {3068$res{'commit'} =$1;3069}30703071returnwantarray?%res: \%res;3072}30733074# wrapper: return parsed line of git-diff-tree "raw" output3075# (the argument might be raw line, or parsed info)3076sub parsed_difftree_line {3077my$line_or_ref=shift;30783079if(ref($line_or_ref)eq"HASH") {3080# pre-parsed (or generated by hand)3081return$line_or_ref;3082}else{3083return parse_difftree_raw_line($line_or_ref);3084}3085}30863087# parse line of git-ls-tree output3088sub parse_ls_tree_line {3089my$line=shift;3090my%opts=@_;3091my%res;30923093if($opts{'-l'}) {3094#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3095$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;30963097$res{'mode'} =$1;3098$res{'type'} =$2;3099$res{'hash'} =$3;3100$res{'size'} =$4;3101if($opts{'-z'}) {3102$res{'name'} =$5;3103}else{3104$res{'name'} = unquote($5);3105}3106}else{3107#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3108$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;31093110$res{'mode'} =$1;3111$res{'type'} =$2;3112$res{'hash'} =$3;3113if($opts{'-z'}) {3114$res{'name'} =$4;3115}else{3116$res{'name'} = unquote($4);3117}3118}31193120returnwantarray?%res: \%res;3121}31223123# generates _two_ hashes, references to which are passed as 2 and 3 argument3124sub parse_from_to_diffinfo {3125my($diffinfo,$from,$to,@parents) =@_;31263127if($diffinfo->{'nparents'}) {3128# combined diff3129$from->{'file'} = [];3130$from->{'href'} = [];3131 fill_from_file_info($diffinfo,@parents)3132unlessexists$diffinfo->{'from_file'};3133for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3134$from->{'file'}[$i] =3135defined$diffinfo->{'from_file'}[$i] ?3136$diffinfo->{'from_file'}[$i] :3137$diffinfo->{'to_file'};3138if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3139$from->{'href'}[$i] = href(action=>"blob",3140 hash_base=>$parents[$i],3141 hash=>$diffinfo->{'from_id'}[$i],3142 file_name=>$from->{'file'}[$i]);3143}else{3144$from->{'href'}[$i] =undef;3145}3146}3147}else{3148# ordinary (not combined) diff3149$from->{'file'} =$diffinfo->{'from_file'};3150if($diffinfo->{'status'}ne"A") {# not new (added) file3151$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3152 hash=>$diffinfo->{'from_id'},3153 file_name=>$from->{'file'});3154}else{3155delete$from->{'href'};3156}3157}31583159$to->{'file'} =$diffinfo->{'to_file'};3160if(!is_deleted($diffinfo)) {# file exists in result3161$to->{'href'} = href(action=>"blob", hash_base=>$hash,3162 hash=>$diffinfo->{'to_id'},3163 file_name=>$to->{'file'});3164}else{3165delete$to->{'href'};3166}3167}31683169## ......................................................................3170## parse to array of hashes functions31713172sub git_get_heads_list {3173my($limit,@classes) =@_;3174@classes= ('heads')unless@classes;3175my@patterns=map{"refs/$_"}@classes;3176my@headslist;31773178open my$fd,'-|', git_cmd(),'for-each-ref',3179($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3180'--format=%(objectname) %(refname) %(subject)%00%(committer)',3181@patterns3182orreturn;3183while(my$line= <$fd>) {3184my%ref_item;31853186chomp$line;3187my($refinfo,$committerinfo) =split(/\0/,$line);3188my($hash,$name,$title) =split(' ',$refinfo,3);3189my($committer,$epoch,$tz) =3190($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3191$ref_item{'fullname'} =$name;3192$name=~s!^refs/(?:head|remote)s/!!;31933194$ref_item{'name'} =$name;3195$ref_item{'id'} =$hash;3196$ref_item{'title'} =$title||'(no commit message)';3197$ref_item{'epoch'} =$epoch;3198if($epoch) {3199$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3200}else{3201$ref_item{'age'} ="unknown";3202}32033204push@headslist, \%ref_item;3205}3206close$fd;32073208returnwantarray?@headslist: \@headslist;3209}32103211sub git_get_tags_list {3212my$limit=shift;3213my@tagslist;32143215open my$fd,'-|', git_cmd(),'for-each-ref',3216($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3217'--format=%(objectname) %(objecttype) %(refname) '.3218'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3219'refs/tags'3220orreturn;3221while(my$line= <$fd>) {3222my%ref_item;32233224chomp$line;3225my($refinfo,$creatorinfo) =split(/\0/,$line);3226my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3227my($creator,$epoch,$tz) =3228($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3229$ref_item{'fullname'} =$name;3230$name=~s!^refs/tags/!!;32313232$ref_item{'type'} =$type;3233$ref_item{'id'} =$id;3234$ref_item{'name'} =$name;3235if($typeeq"tag") {3236$ref_item{'subject'} =$title;3237$ref_item{'reftype'} =$reftype;3238$ref_item{'refid'} =$refid;3239}else{3240$ref_item{'reftype'} =$type;3241$ref_item{'refid'} =$id;3242}32433244if($typeeq"tag"||$typeeq"commit") {3245$ref_item{'epoch'} =$epoch;3246if($epoch) {3247$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3248}else{3249$ref_item{'age'} ="unknown";3250}3251}32523253push@tagslist, \%ref_item;3254}3255close$fd;32563257returnwantarray?@tagslist: \@tagslist;3258}32593260## ----------------------------------------------------------------------3261## filesystem-related functions32623263sub get_file_owner {3264my$path=shift;32653266my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3267my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3268if(!defined$gcos) {3269returnundef;3270}3271my$owner=$gcos;3272$owner=~s/[,;].*$//;3273return to_utf8($owner);3274}32753276# assume that file exists3277sub insert_file {3278my$filename=shift;32793280open my$fd,'<',$filename;3281print map{ to_utf8($_) } <$fd>;3282close$fd;3283}32843285## ......................................................................3286## mimetype related functions32873288sub mimetype_guess_file {3289my$filename=shift;3290my$mimemap=shift;3291-r $mimemaporreturnundef;32923293my%mimemap;3294open(my$mh,'<',$mimemap)orreturnundef;3295while(<$mh>) {3296next ifm/^#/;# skip comments3297my($mimetype,$exts) =split(/\t+/);3298if(defined$exts) {3299my@exts=split(/\s+/,$exts);3300foreachmy$ext(@exts) {3301$mimemap{$ext} =$mimetype;3302}3303}3304}3305close($mh);33063307$filename=~/\.([^.]*)$/;3308return$mimemap{$1};3309}33103311sub mimetype_guess {3312my$filename=shift;3313my$mime;3314$filename=~/\./orreturnundef;33153316if($mimetypes_file) {3317my$file=$mimetypes_file;3318if($file!~m!^/!) {# if it is relative path3319# it is relative to project3320$file="$projectroot/$project/$file";3321}3322$mime= mimetype_guess_file($filename,$file);3323}3324$mime||= mimetype_guess_file($filename,'/etc/mime.types');3325return$mime;3326}33273328sub blob_mimetype {3329my$fd=shift;3330my$filename=shift;33313332if($filename) {3333my$mime= mimetype_guess($filename);3334$mimeandreturn$mime;3335}33363337# just in case3338return$default_blob_plain_mimetypeunless$fd;33393340if(-T $fd) {3341return'text/plain';3342}elsif(!$filename) {3343return'application/octet-stream';3344}elsif($filename=~m/\.png$/i) {3345return'image/png';3346}elsif($filename=~m/\.gif$/i) {3347return'image/gif';3348}elsif($filename=~m/\.jpe?g$/i) {3349return'image/jpeg';3350}else{3351return'application/octet-stream';3352}3353}33543355sub blob_contenttype {3356my($fd,$file_name,$type) =@_;33573358$type||= blob_mimetype($fd,$file_name);3359if($typeeq'text/plain'&&defined$default_text_plain_charset) {3360$type.="; charset=$default_text_plain_charset";3361}33623363return$type;3364}33653366# guess file syntax for syntax highlighting; return undef if no highlighting3367# the name of syntax can (in the future) depend on syntax highlighter used3368sub guess_file_syntax {3369my($highlight,$mimetype,$file_name) =@_;3370returnundefunless($highlight&&defined$file_name);3371my$basename= basename($file_name,'.in');3372return$highlight_basename{$basename}3373ifexists$highlight_basename{$basename};33743375$basename=~/\.([^.]*)$/;3376my$ext=$1orreturnundef;3377return$highlight_ext{$ext}3378ifexists$highlight_ext{$ext};33793380returnundef;3381}33823383# run highlighter and return FD of its output,3384# or return original FD if no highlighting3385sub run_highlighter {3386my($fd,$highlight,$syntax) =@_;3387return$fdunless($highlight&&defined$syntax);33883389close$fd3390or die_error(404,"Reading blob failed");3391open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3392 quote_command($highlight_bin).3393" --xhtml --fragment --syntax$syntax|"3394or die_error(500,"Couldn't open file or run syntax highlighter");3395return$fd;3396}33973398## ======================================================================3399## functions printing HTML: header, footer, error page34003401sub get_page_title {3402my$title= to_utf8($site_name);34033404return$titleunless(defined$project);3405$title.=" - ". to_utf8($project);34063407return$titleunless(defined$action);3408$title.="/$action";# $action is US-ASCII (7bit ASCII)34093410return$titleunless(defined$file_name);3411$title.=" - ". esc_path($file_name);3412if($actioneq"tree"&&$file_name!~ m|/$|) {3413$title.="/";3414}34153416return$title;3417}34183419sub git_header_html {3420my$status=shift||"200 OK";3421my$expires=shift;3422my%opts=@_;34233424my$title= get_page_title();3425my$content_type;3426# require explicit support from the UA if we are to send the page as3427# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3428# we have to do this because MSIE sometimes globs '*/*', pretending to3429# support xhtml+xml but choking when it gets what it asked for.3430if(defined$cgi->http('HTTP_ACCEPT') &&3431$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3432$cgi->Accept('application/xhtml+xml') !=0) {3433$content_type='application/xhtml+xml';3434}else{3435$content_type='text/html';3436}3437print$cgi->header(-type=>$content_type, -charset =>'utf-8',3438-status=>$status, -expires =>$expires)3439unless($opts{'-no_http_header'});3440my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3441print<<EOF;3442<?xml version="1.0" encoding="utf-8"?>3443<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3444<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3445<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3446<!-- git core binaries version$git_version-->3447<head>3448<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3449<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3450<meta name="robots" content="index, nofollow"/>3451<title>$title</title>3452EOF3453# the stylesheet, favicon etc urls won't work correctly with path_info3454# unless we set the appropriate base URL3455if($ENV{'PATH_INFO'}) {3456print"<base href=\"".esc_url($base_url)."\"/>\n";3457}3458# print out each stylesheet that exist, providing backwards capability3459# for those people who defined $stylesheet in a config file3460if(defined$stylesheet) {3461print'<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";3462}else{3463foreachmy$stylesheet(@stylesheets) {3464next unless$stylesheet;3465print'<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";3466}3467}3468if(defined$project) {3469my%href_params= get_feed_info();3470if(!exists$href_params{'-title'}) {3471$href_params{'-title'} ='log';3472}34733474foreachmy$formatqw(RSS Atom){3475my$type=lc($format);3476my%link_attr= (3477'-rel'=>'alternate',3478'-title'=>"$project-$href_params{'-title'} -$formatfeed",3479'-type'=>"application/$type+xml"3480);34813482$href_params{'action'} =$type;3483$link_attr{'-href'} = href(%href_params);3484print"<link ".3485"rel=\"$link_attr{'-rel'}\"".3486"title=\"$link_attr{'-title'}\"".3487"href=\"$link_attr{'-href'}\"".3488"type=\"$link_attr{'-type'}\"".3489"/>\n";34903491$href_params{'extra_options'} ='--no-merges';3492$link_attr{'-href'} = href(%href_params);3493$link_attr{'-title'} .=' (no merges)';3494print"<link ".3495"rel=\"$link_attr{'-rel'}\"".3496"title=\"$link_attr{'-title'}\"".3497"href=\"$link_attr{'-href'}\"".3498"type=\"$link_attr{'-type'}\"".3499"/>\n";3500}35013502}else{3503printf('<link rel="alternate" title="%sprojects list" '.3504'href="%s" type="text/plain; charset=utf-8" />'."\n",3505$site_name, href(project=>undef, action=>"project_index"));3506printf('<link rel="alternate" title="%sprojects feeds" '.3507'href="%s" type="text/x-opml" />'."\n",3508$site_name, href(project=>undef, action=>"opml"));3509}3510if(defined$favicon) {3511printqq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);3512}35133514print"</head>\n".3515"<body>\n";35163517if(defined$site_header&& -f $site_header) {3518 insert_file($site_header);3519}35203521print"<div class=\"page_header\">\n".3522$cgi->a({-href => esc_url($logo_url),3523-title =>$logo_label},3524qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));3525print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3526if(defined$project) {3527print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3528if(defined$action) {3529print" /$action";3530}3531print"\n";3532}3533print"</div>\n";35343535my$have_search= gitweb_check_feature('search');3536if(defined$project&&$have_search) {3537if(!defined$searchtext) {3538$searchtext="";3539}3540my$search_hash;3541if(defined$hash_base) {3542$search_hash=$hash_base;3543}elsif(defined$hash) {3544$search_hash=$hash;3545}else{3546$search_hash="HEAD";3547}3548my$action=$my_uri;3549my$use_pathinfo= gitweb_check_feature('pathinfo');3550if($use_pathinfo) {3551$action.="/".esc_url($project);3552}3553print$cgi->startform(-method=>"get", -action =>$action) .3554"<div class=\"search\">\n".3555(!$use_pathinfo&&3556$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3557$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3558$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3559$cgi->popup_menu(-name =>'st', -default=>'commit',3560-values=> ['commit','grep','author','committer','pickaxe']) .3561$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3562" search:\n",3563$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3564"<span title=\"Extended regular expression\">".3565$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3566-checked =>$search_use_regexp) .3567"</span>".3568"</div>".3569$cgi->end_form() ."\n";3570}3571}35723573sub git_footer_html {3574my$feed_class='rss_logo';35753576print"<div class=\"page_footer\">\n";3577if(defined$project) {3578my$descr= git_get_project_description($project);3579if(defined$descr) {3580print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3581}35823583my%href_params= get_feed_info();3584if(!%href_params) {3585$feed_class.=' generic';3586}3587$href_params{'-title'} ||='log';35883589foreachmy$formatqw(RSS Atom){3590$href_params{'action'} =lc($format);3591print$cgi->a({-href => href(%href_params),3592-title =>"$href_params{'-title'}$formatfeed",3593-class=>$feed_class},$format)."\n";3594}35953596}else{3597print$cgi->a({-href => href(project=>undef, action=>"opml"),3598-class=>$feed_class},"OPML") ." ";3599print$cgi->a({-href => href(project=>undef, action=>"project_index"),3600-class=>$feed_class},"TXT") ."\n";3601}3602print"</div>\n";# class="page_footer"36033604if(defined$t0&& gitweb_check_feature('timed')) {3605print"<div id=\"generating_info\">\n";3606print'This page took '.3607'<span id="generating_time" class="time_span">'.3608 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).3609' seconds </span>'.3610' and '.3611'<span id="generating_cmd">'.3612$number_of_git_cmds.3613'</span> git commands '.3614" to generate.\n";3615print"</div>\n";# class="page_footer"3616}36173618if(defined$site_footer&& -f $site_footer) {3619 insert_file($site_footer);3620}36213622print qq!<script type="text/javascript" src="$javascript"></script>\n!;3623if(defined$action&&3624$actioneq'blame_incremental') {3625print qq!<script type="text/javascript">\n!.3626 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.3627 qq!"!. href() .qq!");\n!.3628 qq!</script>\n!;3629}elsif(gitweb_check_feature('javascript-actions')) {3630print qq!<script type="text/javascript">\n!.3631 qq!window.onload = fixLinks;\n!.3632 qq!</script>\n!;3633}36343635print"</body>\n".3636"</html>";3637}36383639# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])3640# Example: die_error(404, 'Hash not found')3641# By convention, use the following status codes (as defined in RFC 2616):3642# 400: Invalid or missing CGI parameters, or3643# requested object exists but has wrong type.3644# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3645# this server or project.3646# 404: Requested object/revision/project doesn't exist.3647# 500: The server isn't configured properly, or3648# an internal error occurred (e.g. failed assertions caused by bugs), or3649# an unknown error occurred (e.g. the git binary died unexpectedly).3650# 503: The server is currently unavailable (because it is overloaded,3651# or down for maintenance). Generally, this is a temporary state.3652sub die_error {3653my$status=shift||500;3654my$error= esc_html(shift) ||"Internal Server Error";3655my$extra=shift;3656my%opts=@_;36573658my%http_responses= (3659400=>'400 Bad Request',3660403=>'403 Forbidden',3661404=>'404 Not Found',3662500=>'500 Internal Server Error',3663503=>'503 Service Unavailable',3664);3665 git_header_html($http_responses{$status},undef,%opts);3666print<<EOF;3667<div class="page_body">3668<br /><br />3669$status-$error3670<br />3671EOF3672if(defined$extra) {3673print"<hr />\n".3674"$extra\n";3675}3676print"</div>\n";36773678 git_footer_html();3679goto DONE_GITWEB3680unless($opts{'-error_handler'});3681}36823683## ----------------------------------------------------------------------3684## functions printing or outputting HTML: navigation36853686sub git_print_page_nav {3687my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;3688$extra=''if!defined$extra;# pager or formats36893690my@navs=qw(summary shortlog log commit commitdiff tree);3691if($suppress) {3692@navs=grep{$_ne$suppress}@navs;3693}36943695my%arg=map{$_=> {action=>$_} }@navs;3696if(defined$head) {3697for(qw(commit commitdiff)) {3698$arg{$_}{'hash'} =$head;3699}3700if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {3701for(qw(shortlog log)) {3702$arg{$_}{'hash'} =$head;3703}3704}3705}37063707$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;3708$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;37093710my@actions= gitweb_get_feature('actions');3711my%repl= (3712'%'=>'%',3713'n'=>$project,# project name3714'f'=>$git_dir,# project path within filesystem3715'h'=>$treehead||'',# current hash ('h' parameter)3716'b'=>$treebase||'',# hash base ('hb' parameter)3717);3718while(@actions) {3719my($label,$link,$pos) =splice(@actions,0,3);3720# insert3721@navs=map{$_eq$pos? ($_,$label) :$_}@navs;3722# munch munch3723$link=~s/%([%nfhb])/$repl{$1}/g;3724$arg{$label}{'_href'} =$link;3725}37263727print"<div class=\"page_nav\">\n".3728(join" | ",3729map{$_eq$current?3730$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")3731}@navs);3732print"<br/>\n$extra<br/>\n".3733"</div>\n";3734}37353736sub format_paging_nav {3737my($action,$page,$has_next_link) =@_;3738my$paging_nav;373937403741if($page>0) {3742$paging_nav.=3743$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .3744" ⋅ ".3745$cgi->a({-href => href(-replay=>1, page=>$page-1),3746-accesskey =>"p", -title =>"Alt-p"},"prev");3747}else{3748$paging_nav.="first ⋅ prev";3749}37503751if($has_next_link) {3752$paging_nav.=" ⋅ ".3753$cgi->a({-href => href(-replay=>1, page=>$page+1),3754-accesskey =>"n", -title =>"Alt-n"},"next");3755}else{3756$paging_nav.=" ⋅ next";3757}37583759return$paging_nav;3760}37613762## ......................................................................3763## functions printing or outputting HTML: div37643765sub git_print_header_div {3766my($action,$title,$hash,$hash_base) =@_;3767my%args= ();37683769$args{'action'} =$action;3770$args{'hash'} =$hashif$hash;3771$args{'hash_base'} =$hash_baseif$hash_base;37723773print"<div class=\"header\">\n".3774$cgi->a({-href => href(%args), -class=>"title"},3775$title?$title:$action) .3776"\n</div>\n";3777}37783779sub print_local_time {3780print format_local_time(@_);3781}37823783sub format_local_time {3784my$localtime='';3785my%date=@_;3786if($date{'hour_local'} <6) {3787$localtime.=sprintf(" (<span class=\"atnight\">%02d:%02d</span>%s)",3788$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});3789}else{3790$localtime.=sprintf(" (%02d:%02d%s)",3791$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});3792}37933794return$localtime;3795}37963797# Outputs the author name and date in long form3798sub git_print_authorship {3799my$co=shift;3800my%opts=@_;3801my$tag=$opts{-tag} ||'div';3802my$author=$co->{'author_name'};38033804my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});3805print"<$tagclass=\"author_date\">".3806 format_search_author($author,"author", esc_html($author)) .3807" [$ad{'rfc2822'}";3808 print_local_time(%ad)if($opts{-localtime});3809print"]". git_get_avatar($co->{'author_email'}, -pad_before =>1)3810."</$tag>\n";3811}38123813# Outputs table rows containing the full author or committer information,3814# in the format expected for 'commit' view (& similar).3815# Parameters are a commit hash reference, followed by the list of people3816# to output information for. If the list is empty it defaults to both3817# author and committer.3818sub git_print_authorship_rows {3819my$co=shift;3820# too bad we can't use @people = @_ || ('author', 'committer')3821my@people=@_;3822@people= ('author','committer')unless@people;3823foreachmy$who(@people) {3824my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});3825print"<tr><td>$who</td><td>".3826 format_search_author($co->{"${who}_name"},$who,3827 esc_html($co->{"${who}_name"})) ." ".3828 format_search_author($co->{"${who}_email"},$who,3829 esc_html("<".$co->{"${who}_email"} .">")) .3830"</td><td rowspan=\"2\">".3831 git_get_avatar($co->{"${who}_email"}, -size =>'double') .3832"</td></tr>\n".3833"<tr>".3834"<td></td><td>$wd{'rfc2822'}";3835 print_local_time(%wd);3836print"</td>".3837"</tr>\n";3838}3839}38403841sub git_print_page_path {3842my$name=shift;3843my$type=shift;3844my$hb=shift;384538463847print"<div class=\"page_path\">";3848print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),3849-title =>'tree root'}, to_utf8("[$project]"));3850print" / ";3851if(defined$name) {3852my@dirname=split'/',$name;3853my$basename=pop@dirname;3854my$fullname='';38553856foreachmy$dir(@dirname) {3857$fullname.= ($fullname?'/':'') .$dir;3858print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,3859 hash_base=>$hb),3860-title =>$fullname}, esc_path($dir));3861print" / ";3862}3863if(defined$type&&$typeeq'blob') {3864print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,3865 hash_base=>$hb),3866-title =>$name}, esc_path($basename));3867}elsif(defined$type&&$typeeq'tree') {3868print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,3869 hash_base=>$hb),3870-title =>$name}, esc_path($basename));3871print" / ";3872}else{3873print esc_path($basename);3874}3875}3876print"<br/></div>\n";3877}38783879sub git_print_log {3880my$log=shift;3881my%opts=@_;38823883if($opts{'-remove_title'}) {3884# remove title, i.e. first line of log3885shift@$log;3886}3887# remove leading empty lines3888while(defined$log->[0] &&$log->[0]eq"") {3889shift@$log;3890}38913892# print log3893my$signoff=0;3894my$empty=0;3895foreachmy$line(@$log) {3896if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {3897$signoff=1;3898$empty=0;3899if(!$opts{'-remove_signoff'}) {3900print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";3901next;3902}else{3903# remove signoff lines3904next;3905}3906}else{3907$signoff=0;3908}39093910# print only one empty line3911# do not print empty line after signoff3912if($lineeq"") {3913next if($empty||$signoff);3914$empty=1;3915}else{3916$empty=0;3917}39183919print format_log_line_html($line) ."<br/>\n";3920}39213922if($opts{'-final_empty_line'}) {3923# end with single empty line3924print"<br/>\n"unless$empty;3925}3926}39273928# return link target (what link points to)3929sub git_get_link_target {3930my$hash=shift;3931my$link_target;39323933# read link3934open my$fd,"-|", git_cmd(),"cat-file","blob",$hash3935orreturn;3936{3937local$/=undef;3938$link_target= <$fd>;3939}3940close$fd3941orreturn;39423943return$link_target;3944}39453946# given link target, and the directory (basedir) the link is in,3947# return target of link relative to top directory (top tree);3948# return undef if it is not possible (including absolute links).3949sub normalize_link_target {3950my($link_target,$basedir) =@_;39513952# absolute symlinks (beginning with '/') cannot be normalized3953return if(substr($link_target,0,1)eq'/');39543955# normalize link target to path from top (root) tree (dir)3956my$path;3957if($basedir) {3958$path=$basedir.'/'.$link_target;3959}else{3960# we are in top (root) tree (dir)3961$path=$link_target;3962}39633964# remove //, /./, and /../3965my@path_parts;3966foreachmy$part(split('/',$path)) {3967# discard '.' and ''3968next if(!$part||$parteq'.');3969# handle '..'3970if($parteq'..') {3971if(@path_parts) {3972pop@path_parts;3973}else{3974# link leads outside repository (outside top dir)3975return;3976}3977}else{3978push@path_parts,$part;3979}3980}3981$path=join('/',@path_parts);39823983return$path;3984}39853986# print tree entry (row of git_tree), but without encompassing <tr> element3987sub git_print_tree_entry {3988my($t,$basedir,$hash_base,$have_blame) =@_;39893990my%base_key= ();3991$base_key{'hash_base'} =$hash_baseifdefined$hash_base;39923993# The format of a table row is: mode list link. Where mode is3994# the mode of the entry, list is the name of the entry, an href,3995# and link is the action links of the entry.39963997print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";3998if(exists$t->{'size'}) {3999print"<td class=\"size\">$t->{'size'}</td>\n";4000}4001if($t->{'type'}eq"blob") {4002print"<td class=\"list\">".4003$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4004 file_name=>"$basedir$t->{'name'}",%base_key),4005-class=>"list"}, esc_path($t->{'name'}));4006if(S_ISLNK(oct$t->{'mode'})) {4007my$link_target= git_get_link_target($t->{'hash'});4008if($link_target) {4009my$norm_target= normalize_link_target($link_target,$basedir);4010if(defined$norm_target) {4011print" -> ".4012$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4013 file_name=>$norm_target),4014-title =>$norm_target}, esc_path($link_target));4015}else{4016print" -> ". esc_path($link_target);4017}4018}4019}4020print"</td>\n";4021print"<td class=\"link\">";4022print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4023 file_name=>"$basedir$t->{'name'}",%base_key)},4024"blob");4025if($have_blame) {4026print" | ".4027$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4028 file_name=>"$basedir$t->{'name'}",%base_key)},4029"blame");4030}4031if(defined$hash_base) {4032print" | ".4033$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4034 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4035"history");4036}4037print" | ".4038$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4039 file_name=>"$basedir$t->{'name'}")},4040"raw");4041print"</td>\n";40424043}elsif($t->{'type'}eq"tree") {4044print"<td class=\"list\">";4045print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4046 file_name=>"$basedir$t->{'name'}",4047%base_key)},4048 esc_path($t->{'name'}));4049print"</td>\n";4050print"<td class=\"link\">";4051print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4052 file_name=>"$basedir$t->{'name'}",4053%base_key)},4054"tree");4055if(defined$hash_base) {4056print" | ".4057$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4058 file_name=>"$basedir$t->{'name'}")},4059"history");4060}4061print"</td>\n";4062}else{4063# unknown object: we can only present history for it4064# (this includes 'commit' object, i.e. submodule support)4065print"<td class=\"list\">".4066 esc_path($t->{'name'}) .4067"</td>\n";4068print"<td class=\"link\">";4069if(defined$hash_base) {4070print$cgi->a({-href => href(action=>"history",4071 hash_base=>$hash_base,4072 file_name=>"$basedir$t->{'name'}")},4073"history");4074}4075print"</td>\n";4076}4077}40784079## ......................................................................4080## functions printing large fragments of HTML40814082# get pre-image filenames for merge (combined) diff4083sub fill_from_file_info {4084my($diff,@parents) =@_;40854086$diff->{'from_file'} = [ ];4087$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4088for(my$i=0;$i<$diff->{'nparents'};$i++) {4089if($diff->{'status'}[$i]eq'R'||4090$diff->{'status'}[$i]eq'C') {4091$diff->{'from_file'}[$i] =4092 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4093}4094}40954096return$diff;4097}40984099# is current raw difftree line of file deletion4100sub is_deleted {4101my$diffinfo=shift;41024103return$diffinfo->{'to_id'}eq('0' x 40);4104}41054106# does patch correspond to [previous] difftree raw line4107# $diffinfo - hashref of parsed raw diff format4108# $patchinfo - hashref of parsed patch diff format4109# (the same keys as in $diffinfo)4110sub is_patch_split {4111my($diffinfo,$patchinfo) =@_;41124113returndefined$diffinfo&&defined$patchinfo4114&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4115}411641174118sub git_difftree_body {4119my($difftree,$hash,@parents) =@_;4120my($parent) =$parents[0];4121my$have_blame= gitweb_check_feature('blame');4122print"<div class=\"list_head\">\n";4123if($#{$difftree} >10) {4124print(($#{$difftree} +1) ." files changed:\n");4125}4126print"</div>\n";41274128print"<table class=\"".4129(@parents>1?"combined ":"") .4130"diff_tree\">\n";41314132# header only for combined diff in 'commitdiff' view4133my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4134if($has_header) {4135# table header4136print"<thead><tr>\n".4137"<th></th><th></th>\n";# filename, patchN link4138for(my$i=0;$i<@parents;$i++) {4139my$par=$parents[$i];4140print"<th>".4141$cgi->a({-href => href(action=>"commitdiff",4142 hash=>$hash, hash_parent=>$par),4143-title =>'commitdiff to parent number '.4144($i+1) .': '.substr($par,0,7)},4145$i+1) .4146" </th>\n";4147}4148print"</tr></thead>\n<tbody>\n";4149}41504151my$alternate=1;4152my$patchno=0;4153foreachmy$line(@{$difftree}) {4154my$diff= parsed_difftree_line($line);41554156if($alternate) {4157print"<tr class=\"dark\">\n";4158}else{4159print"<tr class=\"light\">\n";4160}4161$alternate^=1;41624163if(exists$diff->{'nparents'}) {# combined diff41644165 fill_from_file_info($diff,@parents)4166unlessexists$diff->{'from_file'};41674168if(!is_deleted($diff)) {4169# file exists in the result (child) commit4170print"<td>".4171$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4172 file_name=>$diff->{'to_file'},4173 hash_base=>$hash),4174-class=>"list"}, esc_path($diff->{'to_file'})) .4175"</td>\n";4176}else{4177print"<td>".4178 esc_path($diff->{'to_file'}) .4179"</td>\n";4180}41814182if($actioneq'commitdiff') {4183# link to patch4184$patchno++;4185print"<td class=\"link\">".4186$cgi->a({-href =>"#patch$patchno"},"patch") .4187" | ".4188"</td>\n";4189}41904191my$has_history=0;4192my$not_deleted=0;4193for(my$i=0;$i<$diff->{'nparents'};$i++) {4194my$hash_parent=$parents[$i];4195my$from_hash=$diff->{'from_id'}[$i];4196my$from_path=$diff->{'from_file'}[$i];4197my$status=$diff->{'status'}[$i];41984199$has_history||= ($statusne'A');4200$not_deleted||= ($statusne'D');42014202if($statuseq'A') {4203print"<td class=\"link\"align=\"right\"> | </td>\n";4204}elsif($statuseq'D') {4205print"<td class=\"link\">".4206$cgi->a({-href => href(action=>"blob",4207 hash_base=>$hash,4208 hash=>$from_hash,4209 file_name=>$from_path)},4210"blob". ($i+1)) .4211" | </td>\n";4212}else{4213if($diff->{'to_id'}eq$from_hash) {4214print"<td class=\"link nochange\">";4215}else{4216print"<td class=\"link\">";4217}4218print$cgi->a({-href => href(action=>"blobdiff",4219 hash=>$diff->{'to_id'},4220 hash_parent=>$from_hash,4221 hash_base=>$hash,4222 hash_parent_base=>$hash_parent,4223 file_name=>$diff->{'to_file'},4224 file_parent=>$from_path)},4225"diff". ($i+1)) .4226" | </td>\n";4227}4228}42294230print"<td class=\"link\">";4231if($not_deleted) {4232print$cgi->a({-href => href(action=>"blob",4233 hash=>$diff->{'to_id'},4234 file_name=>$diff->{'to_file'},4235 hash_base=>$hash)},4236"blob");4237print" | "if($has_history);4238}4239if($has_history) {4240print$cgi->a({-href => href(action=>"history",4241 file_name=>$diff->{'to_file'},4242 hash_base=>$hash)},4243"history");4244}4245print"</td>\n";42464247print"</tr>\n";4248next;# instead of 'else' clause, to avoid extra indent4249}4250# else ordinary diff42514252my($to_mode_oct,$to_mode_str,$to_file_type);4253my($from_mode_oct,$from_mode_str,$from_file_type);4254if($diff->{'to_mode'}ne('0' x 6)) {4255$to_mode_oct=oct$diff->{'to_mode'};4256if(S_ISREG($to_mode_oct)) {# only for regular file4257$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4258}4259$to_file_type= file_type($diff->{'to_mode'});4260}4261if($diff->{'from_mode'}ne('0' x 6)) {4262$from_mode_oct=oct$diff->{'from_mode'};4263if(S_ISREG($to_mode_oct)) {# only for regular file4264$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4265}4266$from_file_type= file_type($diff->{'from_mode'});4267}42684269if($diff->{'status'}eq"A") {# created4270my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4271$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4272$mode_chng.="]</span>";4273print"<td>";4274print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4275 hash_base=>$hash, file_name=>$diff->{'file'}),4276-class=>"list"}, esc_path($diff->{'file'}));4277print"</td>\n";4278print"<td>$mode_chng</td>\n";4279print"<td class=\"link\">";4280if($actioneq'commitdiff') {4281# link to patch4282$patchno++;4283print$cgi->a({-href =>"#patch$patchno"},"patch");4284print" | ";4285}4286print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4287 hash_base=>$hash, file_name=>$diff->{'file'})},4288"blob");4289print"</td>\n";42904291}elsif($diff->{'status'}eq"D") {# deleted4292my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4293print"<td>";4294print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4295 hash_base=>$parent, file_name=>$diff->{'file'}),4296-class=>"list"}, esc_path($diff->{'file'}));4297print"</td>\n";4298print"<td>$mode_chng</td>\n";4299print"<td class=\"link\">";4300if($actioneq'commitdiff') {4301# link to patch4302$patchno++;4303print$cgi->a({-href =>"#patch$patchno"},"patch");4304print" | ";4305}4306print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4307 hash_base=>$parent, file_name=>$diff->{'file'})},4308"blob") ." | ";4309if($have_blame) {4310print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4311 file_name=>$diff->{'file'})},4312"blame") ." | ";4313}4314print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4315 file_name=>$diff->{'file'})},4316"history");4317print"</td>\n";43184319}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4320my$mode_chnge="";4321if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4322$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4323if($from_file_typene$to_file_type) {4324$mode_chnge.=" from$from_file_typeto$to_file_type";4325}4326if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4327if($from_mode_str&&$to_mode_str) {4328$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4329}elsif($to_mode_str) {4330$mode_chnge.=" mode:$to_mode_str";4331}4332}4333$mode_chnge.="]</span>\n";4334}4335print"<td>";4336print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4337 hash_base=>$hash, file_name=>$diff->{'file'}),4338-class=>"list"}, esc_path($diff->{'file'}));4339print"</td>\n";4340print"<td>$mode_chnge</td>\n";4341print"<td class=\"link\">";4342if($actioneq'commitdiff') {4343# link to patch4344$patchno++;4345print$cgi->a({-href =>"#patch$patchno"},"patch") .4346" | ";4347}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4348# "commit" view and modified file (not onlu mode changed)4349print$cgi->a({-href => href(action=>"blobdiff",4350 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4351 hash_base=>$hash, hash_parent_base=>$parent,4352 file_name=>$diff->{'file'})},4353"diff") .4354" | ";4355}4356print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4357 hash_base=>$hash, file_name=>$diff->{'file'})},4358"blob") ." | ";4359if($have_blame) {4360print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4361 file_name=>$diff->{'file'})},4362"blame") ." | ";4363}4364print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4365 file_name=>$diff->{'file'})},4366"history");4367print"</td>\n";43684369}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4370my%status_name= ('R'=>'moved','C'=>'copied');4371my$nstatus=$status_name{$diff->{'status'}};4372my$mode_chng="";4373if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4374# mode also for directories, so we cannot use $to_mode_str4375$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4376}4377print"<td>".4378$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4379 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4380-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4381"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4382$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4383 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4384-class=>"list"}, esc_path($diff->{'from_file'})) .4385" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4386"<td class=\"link\">";4387if($actioneq'commitdiff') {4388# link to patch4389$patchno++;4390print$cgi->a({-href =>"#patch$patchno"},"patch") .4391" | ";4392}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4393# "commit" view and modified file (not only pure rename or copy)4394print$cgi->a({-href => href(action=>"blobdiff",4395 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4396 hash_base=>$hash, hash_parent_base=>$parent,4397 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4398"diff") .4399" | ";4400}4401print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4402 hash_base=>$parent, file_name=>$diff->{'to_file'})},4403"blob") ." | ";4404if($have_blame) {4405print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4406 file_name=>$diff->{'to_file'})},4407"blame") ." | ";4408}4409print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4410 file_name=>$diff->{'to_file'})},4411"history");4412print"</td>\n";44134414}# we should not encounter Unmerged (U) or Unknown (X) status4415print"</tr>\n";4416}4417print"</tbody>"if$has_header;4418print"</table>\n";4419}44204421sub git_patchset_body {4422my($fd,$difftree,$hash,@hash_parents) =@_;4423my($hash_parent) =$hash_parents[0];44244425my$is_combined= (@hash_parents>1);4426my$patch_idx=0;4427my$patch_number=0;4428my$patch_line;4429my$diffinfo;4430my$to_name;4431my(%from,%to);44324433print"<div class=\"patchset\">\n";44344435# skip to first patch4436while($patch_line= <$fd>) {4437chomp$patch_line;44384439last if($patch_line=~m/^diff /);4440}44414442 PATCH:4443while($patch_line) {44444445# parse "git diff" header line4446if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4447# $1 is from_name, which we do not use4448$to_name= unquote($2);4449$to_name=~s!^b/!!;4450}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4451# $1 is 'cc' or 'combined', which we do not use4452$to_name= unquote($2);4453}else{4454$to_name=undef;4455}44564457# check if current patch belong to current raw line4458# and parse raw git-diff line if needed4459if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4460# this is continuation of a split patch4461print"<div class=\"patch cont\">\n";4462}else{4463# advance raw git-diff output if needed4464$patch_idx++ifdefined$diffinfo;44654466# read and prepare patch information4467$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);44684469# compact combined diff output can have some patches skipped4470# find which patch (using pathname of result) we are at now;4471if($is_combined) {4472while($to_namene$diffinfo->{'to_file'}) {4473print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4474 format_diff_cc_simplified($diffinfo,@hash_parents) .4475"</div>\n";# class="patch"44764477$patch_idx++;4478$patch_number++;44794480last if$patch_idx>$#$difftree;4481$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4482}4483}44844485# modifies %from, %to hashes4486 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);44874488# this is first patch for raw difftree line with $patch_idx index4489# we index @$difftree array from 0, but number patches from 14490print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4491}44924493# git diff header4494#assert($patch_line =~ m/^diff /) if DEBUG;4495#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4496$patch_number++;4497# print "git diff" header4498print format_git_diff_header_line($patch_line,$diffinfo,4499 \%from, \%to);45004501# print extended diff header4502print"<div class=\"diff extended_header\">\n";4503 EXTENDED_HEADER:4504while($patch_line= <$fd>) {4505chomp$patch_line;45064507last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);45084509print format_extended_diff_header_line($patch_line,$diffinfo,4510 \%from, \%to);4511}4512print"</div>\n";# class="diff extended_header"45134514# from-file/to-file diff header4515if(!$patch_line) {4516print"</div>\n";# class="patch"4517last PATCH;4518}4519next PATCH if($patch_line=~m/^diff /);4520#assert($patch_line =~ m/^---/) if DEBUG;45214522my$last_patch_line=$patch_line;4523$patch_line= <$fd>;4524chomp$patch_line;4525#assert($patch_line =~ m/^\+\+\+/) if DEBUG;45264527print format_diff_from_to_header($last_patch_line,$patch_line,4528$diffinfo, \%from, \%to,4529@hash_parents);45304531# the patch itself4532 LINE:4533while($patch_line= <$fd>) {4534chomp$patch_line;45354536next PATCH if($patch_line=~m/^diff /);45374538print format_diff_line($patch_line, \%from, \%to);4539}45404541}continue{4542print"</div>\n";# class="patch"4543}45444545# for compact combined (--cc) format, with chunk and patch simplification4546# the patchset might be empty, but there might be unprocessed raw lines4547for(++$patch_idxif$patch_number>0;4548$patch_idx<@$difftree;4549++$patch_idx) {4550# read and prepare patch information4551$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);45524553# generate anchor for "patch" links in difftree / whatchanged part4554print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4555 format_diff_cc_simplified($diffinfo,@hash_parents) .4556"</div>\n";# class="patch"45574558$patch_number++;4559}45604561if($patch_number==0) {4562if(@hash_parents>1) {4563print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4564}else{4565print"<div class=\"diff nodifferences\">No differences found</div>\n";4566}4567}45684569print"</div>\n";# class="patchset"4570}45714572# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .45734574# fills project list info (age, description, owner, forks) for each4575# project in the list, removing invalid projects from returned list4576# NOTE: modifies $projlist, but does not remove entries from it4577sub fill_project_list_info {4578my($projlist,$check_forks) =@_;4579my@projects;45804581my$show_ctags= gitweb_check_feature('ctags');4582 PROJECT:4583foreachmy$pr(@$projlist) {4584my(@activity) = git_get_last_activity($pr->{'path'});4585unless(@activity) {4586next PROJECT;4587}4588($pr->{'age'},$pr->{'age_string'}) =@activity;4589if(!defined$pr->{'descr'}) {4590my$descr= git_get_project_description($pr->{'path'}) ||"";4591$descr= to_utf8($descr);4592$pr->{'descr_long'} =$descr;4593$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);4594}4595if(!defined$pr->{'owner'}) {4596$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";4597}4598if($check_forks) {4599my$pname=$pr->{'path'};4600if(($pname=~s/\.git$//) &&4601($pname!~/\/$/) &&4602(-d "$projectroot/$pname")) {4603$pr->{'forks'} ="-d$projectroot/$pname";4604}else{4605$pr->{'forks'} =0;4606}4607}4608$show_ctagsand$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});4609push@projects,$pr;4610}46114612return@projects;4613}46144615# print 'sort by' <th> element, generating 'sort by $name' replay link4616# if that order is not selected4617sub print_sort_th {4618print format_sort_th(@_);4619}46204621sub format_sort_th {4622my($name,$order,$header) =@_;4623my$sort_th="";4624$header||=ucfirst($name);46254626if($ordereq$name) {4627$sort_th.="<th>$header</th>\n";4628}else{4629$sort_th.="<th>".4630$cgi->a({-href => href(-replay=>1, order=>$name),4631-class=>"header"},$header) .4632"</th>\n";4633}46344635return$sort_th;4636}46374638sub git_project_list_body {4639# actually uses global variable $project4640my($projlist,$order,$from,$to,$extra,$no_header) =@_;46414642my$check_forks= gitweb_check_feature('forks');4643my@projects= fill_project_list_info($projlist,$check_forks);46444645$order||=$default_projects_order;4646$from=0unlessdefined$from;4647$to=$#projectsif(!defined$to||$#projects<$to);46484649my%order_info= (4650 project => { key =>'path', type =>'str'},4651 descr => { key =>'descr_long', type =>'str'},4652 owner => { key =>'owner', type =>'str'},4653 age => { key =>'age', type =>'num'}4654);4655my$oi=$order_info{$order};4656if($oi->{'type'}eq'str') {4657@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@projects;4658}else{4659@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@projects;4660}46614662my$show_ctags= gitweb_check_feature('ctags');4663if($show_ctags) {4664my%ctags;4665foreachmy$p(@projects) {4666foreachmy$ct(keys%{$p->{'ctags'}}) {4667$ctags{$ct} +=$p->{'ctags'}->{$ct};4668}4669}4670my$cloud= git_populate_project_tagcloud(\%ctags);4671print git_show_project_tagcloud($cloud,64);4672}46734674print"<table class=\"project_list\">\n";4675unless($no_header) {4676print"<tr>\n";4677if($check_forks) {4678print"<th></th>\n";4679}4680 print_sort_th('project',$order,'Project');4681 print_sort_th('descr',$order,'Description');4682 print_sort_th('owner',$order,'Owner');4683 print_sort_th('age',$order,'Last Change');4684print"<th></th>\n".# for links4685"</tr>\n";4686}4687my$alternate=1;4688my$tagfilter=$cgi->param('by_tag');4689for(my$i=$from;$i<=$to;$i++) {4690my$pr=$projects[$i];46914692next if$tagfilterand$show_ctagsand not grep{lc$_eq lc$tagfilter}keys%{$pr->{'ctags'}};4693next if$searchtextand not$pr->{'path'} =~/$searchtext/4694and not$pr->{'descr_long'} =~/$searchtext/;4695# Weed out forks or non-matching entries of search4696if($check_forks) {4697my$forkbase=$project;$forkbase||='';$forkbase=~ s#\.git$#/#;4698$forkbase="^$forkbase"if$forkbase;4699next ifnot$searchtextand not$tagfilterand$show_ctags4700and$pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe4701}47024703if($alternate) {4704print"<tr class=\"dark\">\n";4705}else{4706print"<tr class=\"light\">\n";4707}4708$alternate^=1;4709if($check_forks) {4710print"<td>";4711if($pr->{'forks'}) {4712print"<!--$pr->{'forks'} -->\n";4713print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"+");4714}4715print"</td>\n";4716}4717print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),4718-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".4719"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),4720-class=>"list", -title =>$pr->{'descr_long'}},4721 esc_html($pr->{'descr'})) ."</td>\n".4722"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";4723print"<td class=\"". age_class($pr->{'age'}) ."\">".4724(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".4725"<td class=\"link\">".4726$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".4727$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".4728$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".4729$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .4730($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .4731"</td>\n".4732"</tr>\n";4733}4734if(defined$extra) {4735print"<tr>\n";4736if($check_forks) {4737print"<td></td>\n";4738}4739print"<td colspan=\"5\">$extra</td>\n".4740"</tr>\n";4741}4742print"</table>\n";4743}47444745sub git_log_body {4746# uses global variable $project4747my($commitlist,$from,$to,$refs,$extra) =@_;47484749$from=0unlessdefined$from;4750$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);47514752for(my$i=0;$i<=$to;$i++) {4753my%co= %{$commitlist->[$i]};4754next if!%co;4755my$commit=$co{'id'};4756my$ref= format_ref_marker($refs,$commit);4757my%ad= parse_date($co{'author_epoch'});4758 git_print_header_div('commit',4759"<span class=\"age\">$co{'age_string'}</span>".4760 esc_html($co{'title'}) .$ref,4761$commit);4762print"<div class=\"title_text\">\n".4763"<div class=\"log_link\">\n".4764$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .4765" | ".4766$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .4767" | ".4768$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .4769"<br/>\n".4770"</div>\n";4771 git_print_authorship(\%co, -tag =>'span');4772print"<br/>\n</div>\n";47734774print"<div class=\"log_body\">\n";4775 git_print_log($co{'comment'}, -final_empty_line=>1);4776print"</div>\n";4777}4778if($extra) {4779print"<div class=\"page_nav\">\n";4780print"$extra\n";4781print"</div>\n";4782}4783}47844785sub git_shortlog_body {4786# uses global variable $project4787my($commitlist,$from,$to,$refs,$extra) =@_;47884789$from=0unlessdefined$from;4790$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);47914792print"<table class=\"shortlog\">\n";4793my$alternate=1;4794for(my$i=$from;$i<=$to;$i++) {4795my%co= %{$commitlist->[$i]};4796my$commit=$co{'id'};4797my$ref= format_ref_marker($refs,$commit);4798if($alternate) {4799print"<tr class=\"dark\">\n";4800}else{4801print"<tr class=\"light\">\n";4802}4803$alternate^=1;4804# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .4805print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4806 format_author_html('td', \%co,10) ."<td>";4807print format_subject_html($co{'title'},$co{'title_short'},4808 href(action=>"commit", hash=>$commit),$ref);4809print"</td>\n".4810"<td class=\"link\">".4811$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".4812$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".4813$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");4814my$snapshot_links= format_snapshot_links($commit);4815if(defined$snapshot_links) {4816print" | ".$snapshot_links;4817}4818print"</td>\n".4819"</tr>\n";4820}4821if(defined$extra) {4822print"<tr>\n".4823"<td colspan=\"4\">$extra</td>\n".4824"</tr>\n";4825}4826print"</table>\n";4827}48284829sub git_history_body {4830# Warning: assumes constant type (blob or tree) during history4831my($commitlist,$from,$to,$refs,$extra,4832$file_name,$file_hash,$ftype) =@_;48334834$from=0unlessdefined$from;4835$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});48364837print"<table class=\"history\">\n";4838my$alternate=1;4839for(my$i=$from;$i<=$to;$i++) {4840my%co= %{$commitlist->[$i]};4841if(!%co) {4842next;4843}4844my$commit=$co{'id'};48454846my$ref= format_ref_marker($refs,$commit);48474848if($alternate) {4849print"<tr class=\"dark\">\n";4850}else{4851print"<tr class=\"light\">\n";4852}4853$alternate^=1;4854print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4855# shortlog: format_author_html('td', \%co, 10)4856 format_author_html('td', \%co,15,3) ."<td>";4857# originally git_history used chop_str($co{'title'}, 50)4858print format_subject_html($co{'title'},$co{'title_short'},4859 href(action=>"commit", hash=>$commit),$ref);4860print"</td>\n".4861"<td class=\"link\">".4862$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".4863$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");48644865if($ftypeeq'blob') {4866my$blob_current=$file_hash;4867my$blob_parent= git_get_hash_by_path($commit,$file_name);4868if(defined$blob_current&&defined$blob_parent&&4869$blob_currentne$blob_parent) {4870print" | ".4871$cgi->a({-href => href(action=>"blobdiff",4872 hash=>$blob_current, hash_parent=>$blob_parent,4873 hash_base=>$hash_base, hash_parent_base=>$commit,4874 file_name=>$file_name)},4875"diff to current");4876}4877}4878print"</td>\n".4879"</tr>\n";4880}4881if(defined$extra) {4882print"<tr>\n".4883"<td colspan=\"4\">$extra</td>\n".4884"</tr>\n";4885}4886print"</table>\n";4887}48884889sub git_tags_body {4890# uses global variable $project4891my($taglist,$from,$to,$extra) =@_;4892$from=0unlessdefined$from;4893$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);48944895print"<table class=\"tags\">\n";4896my$alternate=1;4897for(my$i=$from;$i<=$to;$i++) {4898my$entry=$taglist->[$i];4899my%tag=%$entry;4900my$comment=$tag{'subject'};4901my$comment_short;4902if(defined$comment) {4903$comment_short= chop_str($comment,30,5);4904}4905if($alternate) {4906print"<tr class=\"dark\">\n";4907}else{4908print"<tr class=\"light\">\n";4909}4910$alternate^=1;4911if(defined$tag{'age'}) {4912print"<td><i>$tag{'age'}</i></td>\n";4913}else{4914print"<td></td>\n";4915}4916print"<td>".4917$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),4918-class=>"list name"}, esc_html($tag{'name'})) .4919"</td>\n".4920"<td>";4921if(defined$comment) {4922print format_subject_html($comment,$comment_short,4923 href(action=>"tag", hash=>$tag{'id'}));4924}4925print"</td>\n".4926"<td class=\"selflink\">";4927if($tag{'type'}eq"tag") {4928print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");4929}else{4930print" ";4931}4932print"</td>\n".4933"<td class=\"link\">"." | ".4934$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});4935if($tag{'reftype'}eq"commit") {4936print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .4937" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");4938}elsif($tag{'reftype'}eq"blob") {4939print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");4940}4941print"</td>\n".4942"</tr>";4943}4944if(defined$extra) {4945print"<tr>\n".4946"<td colspan=\"5\">$extra</td>\n".4947"</tr>\n";4948}4949print"</table>\n";4950}49514952sub git_heads_body {4953# uses global variable $project4954my($headlist,$head,$from,$to,$extra) =@_;4955$from=0unlessdefined$from;4956$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);49574958print"<table class=\"heads\">\n";4959my$alternate=1;4960for(my$i=$from;$i<=$to;$i++) {4961my$entry=$headlist->[$i];4962my%ref=%$entry;4963my$curr=$ref{'id'}eq$head;4964if($alternate) {4965print"<tr class=\"dark\">\n";4966}else{4967print"<tr class=\"light\">\n";4968}4969$alternate^=1;4970print"<td><i>$ref{'age'}</i></td>\n".4971($curr?"<td class=\"current_head\">":"<td>") .4972$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),4973-class=>"list name"},esc_html($ref{'name'})) .4974"</td>\n".4975"<td class=\"link\">".4976$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".4977$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".4978$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .4979"</td>\n".4980"</tr>";4981}4982if(defined$extra) {4983print"<tr>\n".4984"<td colspan=\"3\">$extra</td>\n".4985"</tr>\n";4986}4987print"</table>\n";4988}49894990sub git_search_grep_body {4991my($commitlist,$from,$to,$extra) =@_;4992$from=0unlessdefined$from;4993$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);49944995print"<table class=\"commit_search\">\n";4996my$alternate=1;4997for(my$i=$from;$i<=$to;$i++) {4998my%co= %{$commitlist->[$i]};4999if(!%co) {5000next;5001}5002my$commit=$co{'id'};5003if($alternate) {5004print"<tr class=\"dark\">\n";5005}else{5006print"<tr class=\"light\">\n";5007}5008$alternate^=1;5009print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5010 format_author_html('td', \%co,15,5) .5011"<td>".5012$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5013-class=>"list subject"},5014 chop_and_escape_str($co{'title'},50) ."<br/>");5015my$comment=$co{'comment'};5016foreachmy$line(@$comment) {5017if($line=~m/^(.*?)($search_regexp)(.*)$/i) {5018my($lead,$match,$trail) = ($1,$2,$3);5019$match= chop_str($match,70,5,'center');5020my$contextlen=int((80-length($match))/2);5021$contextlen=30if($contextlen>30);5022$lead= chop_str($lead,$contextlen,10,'left');5023$trail= chop_str($trail,$contextlen,10,'right');50245025$lead= esc_html($lead);5026$match= esc_html($match);5027$trail= esc_html($trail);50285029print"$lead<span class=\"match\">$match</span>$trail<br />";5030}5031}5032print"</td>\n".5033"<td class=\"link\">".5034$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .5035" | ".5036$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .5037" | ".5038$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");5039print"</td>\n".5040"</tr>\n";5041}5042if(defined$extra) {5043print"<tr>\n".5044"<td colspan=\"3\">$extra</td>\n".5045"</tr>\n";5046}5047print"</table>\n";5048}50495050## ======================================================================5051## ======================================================================5052## actions50535054sub git_project_list {5055my$order=$input_params{'order'};5056if(defined$order&&$order!~m/none|project|descr|owner|age/) {5057 die_error(400,"Unknown order parameter");5058}50595060my@list= git_get_projects_list();5061if(!@list) {5062 die_error(404,"No projects found");5063}50645065 git_header_html();5066if(defined$home_text&& -f $home_text) {5067print"<div class=\"index_include\">\n";5068 insert_file($home_text);5069print"</div>\n";5070}5071print$cgi->startform(-method=>"get") .5072"<p class=\"projsearch\">Search:\n".5073$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".5074"</p>".5075$cgi->end_form() ."\n";5076 git_project_list_body(\@list,$order);5077 git_footer_html();5078}50795080sub git_forks {5081my$order=$input_params{'order'};5082if(defined$order&&$order!~m/none|project|descr|owner|age/) {5083 die_error(400,"Unknown order parameter");5084}50855086my@list= git_get_projects_list($project);5087if(!@list) {5088 die_error(404,"No forks found");5089}50905091 git_header_html();5092 git_print_page_nav('','');5093 git_print_header_div('summary',"$projectforks");5094 git_project_list_body(\@list,$order);5095 git_footer_html();5096}50975098sub git_project_index {5099my@projects= git_get_projects_list($project);51005101print$cgi->header(5102-type =>'text/plain',5103-charset =>'utf-8',5104-content_disposition =>'inline; filename="index.aux"');51055106foreachmy$pr(@projects) {5107if(!exists$pr->{'owner'}) {5108$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");5109}51105111my($path,$owner) = ($pr->{'path'},$pr->{'owner'});5112# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '5113$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5114$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5115$path=~s/ /\+/g;5116$owner=~s/ /\+/g;51175118print"$path$owner\n";5119}5120}51215122sub git_summary {5123my$descr= git_get_project_description($project) ||"none";5124my%co= parse_commit("HEAD");5125my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();5126my$head=$co{'id'};5127my$remote_heads= gitweb_check_feature('remote_heads');51285129my$owner= git_get_project_owner($project);51305131my$refs= git_get_references();5132# These get_*_list functions return one more to allow us to see if5133# there are more ...5134my@taglist= git_get_tags_list(16);5135my@headlist= git_get_heads_list(16);5136my@remotelist=$remote_heads? git_get_heads_list(16,'remotes') : ();5137my@forklist;5138my$check_forks= gitweb_check_feature('forks');51395140if($check_forks) {5141@forklist= git_get_projects_list($project);5142}51435144 git_header_html();5145 git_print_page_nav('summary','',$head);51465147print"<div class=\"title\"> </div>\n";5148print"<table class=\"projects_list\">\n".5149"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".5150"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";5151if(defined$cd{'rfc2822'}) {5152print"<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";5153}51545155# use per project git URL list in $projectroot/$project/cloneurl5156# or make project git URL from git base URL and project name5157my$url_tag="URL";5158my@url_list= git_get_project_url_list($project);5159@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;5160foreachmy$git_url(@url_list) {5161next unless$git_url;5162print"<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";5163$url_tag="";5164}51655166# Tag cloud5167my$show_ctags= gitweb_check_feature('ctags');5168if($show_ctags) {5169my$ctags= git_get_project_ctags($project);5170my$cloud= git_populate_project_tagcloud($ctags);5171print"<tr id=\"metadata_ctags\"><td>Content tags:<br />";5172print"</td>\n<td>"unless%$ctags;5173print"<form action=\"$show_ctags\"method=\"post\"><input type=\"hidden\"name=\"p\"value=\"$project\"/>Add: <input type=\"text\"name=\"t\"size=\"8\"/></form>";5174print"</td>\n<td>"if%$ctags;5175print git_show_project_tagcloud($cloud,48);5176print"</td></tr>";5177}51785179print"</table>\n";51805181# If XSS prevention is on, we don't include README.html.5182# TODO: Allow a readme in some safe format.5183if(!$prevent_xss&& -s "$projectroot/$project/README.html") {5184print"<div class=\"title\">readme</div>\n".5185"<div class=\"readme\">\n";5186 insert_file("$projectroot/$project/README.html");5187print"\n</div>\n";# class="readme"5188}51895190# we need to request one more than 16 (0..15) to check if5191# those 16 are all5192my@commitlist=$head? parse_commits($head,17) : ();5193if(@commitlist) {5194 git_print_header_div('shortlog');5195 git_shortlog_body(\@commitlist,0,15,$refs,5196$#commitlist<=15?undef:5197$cgi->a({-href => href(action=>"shortlog")},"..."));5198}51995200if(@taglist) {5201 git_print_header_div('tags');5202 git_tags_body(\@taglist,0,15,5203$#taglist<=15?undef:5204$cgi->a({-href => href(action=>"tags")},"..."));5205}52065207if(@headlist) {5208 git_print_header_div('heads');5209 git_heads_body(\@headlist,$head,0,15,5210$#headlist<=15?undef:5211$cgi->a({-href => href(action=>"heads")},"..."));5212}52135214if(@remotelist) {5215 git_print_header_div('remotes');5216 git_heads_body(\@remotelist,$head,0,15,5217$#remotelist<=15?undef:5218$cgi->a({-href => href(action=>"remotes")},"..."));5219}52205221if(@forklist) {5222 git_print_header_div('forks');5223 git_project_list_body(\@forklist,'age',0,15,5224$#forklist<=15?undef:5225$cgi->a({-href => href(action=>"forks")},"..."),5226'no_header');5227}52285229 git_footer_html();5230}52315232sub git_tag {5233my%tag= parse_tag($hash);52345235if(!%tag) {5236 die_error(404,"Unknown tag object");5237}52385239my$head= git_get_head_hash($project);5240 git_header_html();5241 git_print_page_nav('','',$head,undef,$head);5242 git_print_header_div('commit', esc_html($tag{'name'}),$hash);5243print"<div class=\"title_text\">\n".5244"<table class=\"object_header\">\n".5245"<tr>\n".5246"<td>object</td>\n".5247"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5248$tag{'object'}) ."</td>\n".5249"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5250$tag{'type'}) ."</td>\n".5251"</tr>\n";5252if(defined($tag{'author'})) {5253 git_print_authorship_rows(\%tag,'author');5254}5255print"</table>\n\n".5256"</div>\n";5257print"<div class=\"page_body\">";5258my$comment=$tag{'comment'};5259foreachmy$line(@$comment) {5260chomp$line;5261print esc_html($line, -nbsp=>1) ."<br/>\n";5262}5263print"</div>\n";5264 git_footer_html();5265}52665267sub git_blame_common {5268my$format=shift||'porcelain';5269if($formateq'porcelain'&&$cgi->param('js')) {5270$format='incremental';5271$action='blame_incremental';# for page title etc5272}52735274# permissions5275 gitweb_check_feature('blame')5276or die_error(403,"Blame view not allowed");52775278# error checking5279 die_error(400,"No file name given")unless$file_name;5280$hash_base||= git_get_head_hash($project);5281 die_error(404,"Couldn't find base commit")unless$hash_base;5282my%co= parse_commit($hash_base)5283or die_error(404,"Commit not found");5284my$ftype="blob";5285if(!defined$hash) {5286$hash= git_get_hash_by_path($hash_base,$file_name,"blob")5287or die_error(404,"Error looking up file");5288}else{5289$ftype= git_get_type($hash);5290if($ftype!~"blob") {5291 die_error(400,"Object is not a blob");5292}5293}52945295my$fd;5296if($formateq'incremental') {5297# get file contents (as base)5298open$fd,"-|", git_cmd(),'cat-file','blob',$hash5299or die_error(500,"Open git-cat-file failed");5300}elsif($formateq'data') {5301# run git-blame --incremental5302open$fd,"-|", git_cmd(),"blame","--incremental",5303$hash_base,"--",$file_name5304or die_error(500,"Open git-blame --incremental failed");5305}else{5306# run git-blame --porcelain5307open$fd,"-|", git_cmd(),"blame",'-p',5308$hash_base,'--',$file_name5309or die_error(500,"Open git-blame --porcelain failed");5310}53115312# incremental blame data returns early5313if($formateq'data') {5314print$cgi->header(5315-type=>"text/plain", -charset =>"utf-8",5316-status=>"200 OK");5317local$| =1;# output autoflush5318printwhile<$fd>;5319close$fd5320or print"ERROR$!\n";53215322print'END';5323if(defined$t0&& gitweb_check_feature('timed')) {5324print' '.5325 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).5326' '.$number_of_git_cmds;5327}5328print"\n";53295330return;5331}53325333# page header5334 git_header_html();5335my$formats_nav=5336$cgi->a({-href => href(action=>"blob", -replay=>1)},5337"blob") .5338" | ";5339if($formateq'incremental') {5340$formats_nav.=5341$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},5342"blame") ." (non-incremental)";5343}else{5344$formats_nav.=5345$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},5346"blame") ." (incremental)";5347}5348$formats_nav.=5349" | ".5350$cgi->a({-href => href(action=>"history", -replay=>1)},5351"history") .5352" | ".5353$cgi->a({-href => href(action=>$action, file_name=>$file_name)},5354"HEAD");5355 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5356 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5357 git_print_page_path($file_name,$ftype,$hash_base);53585359# page body5360if($formateq'incremental') {5361print"<noscript>\n<div class=\"error\"><center><b>\n".5362"This page requires JavaScript to run.\nUse ".5363$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},5364'this page').5365" instead.\n".5366"</b></center></div>\n</noscript>\n";53675368print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;5369}53705371print qq!<div class="page_body">\n!;5372print qq!<div id="progress_info">.../ ...</div>\n!5373if($formateq'incremental');5374print qq!<table id="blame_table"class="blame" width="100%">\n!.5375#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.5376 qq!<thead>\n!.5377 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.5378 qq!</thead>\n!.5379 qq!<tbody>\n!;53805381my@rev_color=qw(light dark);5382my$num_colors=scalar(@rev_color);5383my$current_color=0;53845385if($formateq'incremental') {5386my$color_class=$rev_color[$current_color];53875388#contents of a file5389my$linenr=0;5390 LINE:5391while(my$line= <$fd>) {5392chomp$line;5393$linenr++;53945395print qq!<tr id="l$linenr"class="$color_class">!.5396 qq!<td class="sha1"><a href=""> </a></td>!.5397 qq!<td class="linenr">!.5398 qq!<a class="linenr" href="">$linenr</a></td>!;5399print qq!<td class="pre">! . esc_html($line) ."</td>\n";5400print qq!</tr>\n!;5401}54025403}else{# porcelain, i.e. ordinary blame5404my%metainfo= ();# saves information about commits54055406# blame data5407 LINE:5408while(my$line= <$fd>) {5409chomp$line;5410# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]5411# no <lines in group> for subsequent lines in group of lines5412my($full_rev,$orig_lineno,$lineno,$group_size) =5413($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);5414if(!exists$metainfo{$full_rev}) {5415$metainfo{$full_rev} = {'nprevious'=>0};5416}5417my$meta=$metainfo{$full_rev};5418my$data;5419while($data= <$fd>) {5420chomp$data;5421last if($data=~s/^\t//);# contents of line5422if($data=~/^(\S+)(?: (.*))?$/) {5423$meta->{$1} =$2unlessexists$meta->{$1};5424}5425if($data=~/^previous /) {5426$meta->{'nprevious'}++;5427}5428}5429my$short_rev=substr($full_rev,0,8);5430my$author=$meta->{'author'};5431my%date=5432 parse_date($meta->{'author-time'},$meta->{'author-tz'});5433my$date=$date{'iso-tz'};5434if($group_size) {5435$current_color= ($current_color+1) %$num_colors;5436}5437my$tr_class=$rev_color[$current_color];5438$tr_class.=' boundary'if(exists$meta->{'boundary'});5439$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);5440$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);5441print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";5442if($group_size) {5443print"<td class=\"sha1\"";5444print" title=\"". esc_html($author) .",$date\"";5445print" rowspan=\"$group_size\""if($group_size>1);5446print">";5447print$cgi->a({-href => href(action=>"commit",5448 hash=>$full_rev,5449 file_name=>$file_name)},5450 esc_html($short_rev));5451if($group_size>=2) {5452my@author_initials= ($author=~/\b([[:upper:]])\B/g);5453if(@author_initials) {5454print"<br />".5455 esc_html(join('',@author_initials));5456# or join('.', ...)5457}5458}5459print"</td>\n";5460}5461# 'previous' <sha1 of parent commit> <filename at commit>5462if(exists$meta->{'previous'} &&5463$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {5464$meta->{'parent'} =$1;5465$meta->{'file_parent'} = unquote($2);5466}5467my$linenr_commit=5468exists($meta->{'parent'}) ?5469$meta->{'parent'} :$full_rev;5470my$linenr_filename=5471exists($meta->{'file_parent'}) ?5472$meta->{'file_parent'} : unquote($meta->{'filename'});5473my$blamed= href(action =>'blame',5474 file_name =>$linenr_filename,5475 hash_base =>$linenr_commit);5476print"<td class=\"linenr\">";5477print$cgi->a({ -href =>"$blamed#l$orig_lineno",5478-class=>"linenr"},5479 esc_html($lineno));5480print"</td>";5481print"<td class=\"pre\">". esc_html($data) ."</td>\n";5482print"</tr>\n";5483}# end while54845485}54865487# footer5488print"</tbody>\n".5489"</table>\n";# class="blame"5490print"</div>\n";# class="blame_body"5491close$fd5492or print"Reading blob failed\n";54935494 git_footer_html();5495}54965497sub git_blame {5498 git_blame_common();5499}55005501sub git_blame_incremental {5502 git_blame_common('incremental');5503}55045505sub git_blame_data {5506 git_blame_common('data');5507}55085509sub git_tags {5510my$head= git_get_head_hash($project);5511 git_header_html();5512 git_print_page_nav('','',$head,undef,$head);5513 git_print_header_div('summary',$project);55145515my@tagslist= git_get_tags_list();5516if(@tagslist) {5517 git_tags_body(\@tagslist);5518}5519 git_footer_html();5520}55215522sub git_heads {5523my$head= git_get_head_hash($project);5524 git_header_html();5525 git_print_page_nav('','',$head,undef,$head);5526 git_print_header_div('summary',$project);55275528my@headslist= git_get_heads_list();5529if(@headslist) {5530 git_heads_body(\@headslist,$head);5531}5532 git_footer_html();5533}55345535sub git_remotes {5536 gitweb_check_feature('remote_heads')5537or die_error(403,"Remote heads view is disabled");55385539my$head= git_get_head_hash($project);5540 git_header_html();5541 git_print_page_nav('','',$head,undef,$head);5542 git_print_header_div('summary',$project);55435544my@remotelist= git_get_heads_list(undef,'remotes');5545if(@remotelist) {5546 git_heads_body(\@remotelist,$head);5547}5548 git_footer_html();5549}55505551sub git_blob_plain {5552my$type=shift;5553my$expires;55545555if(!defined$hash) {5556if(defined$file_name) {5557my$base=$hash_base|| git_get_head_hash($project);5558$hash= git_get_hash_by_path($base,$file_name,"blob")5559or die_error(404,"Cannot find file");5560}else{5561 die_error(400,"No file name defined");5562}5563}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {5564# blobs defined by non-textual hash id's can be cached5565$expires="+1d";5566}55675568open my$fd,"-|", git_cmd(),"cat-file","blob",$hash5569or die_error(500,"Open git-cat-file blob '$hash' failed");55705571# content-type (can include charset)5572$type= blob_contenttype($fd,$file_name,$type);55735574# "save as" filename, even when no $file_name is given5575my$save_as="$hash";5576if(defined$file_name) {5577$save_as=$file_name;5578}elsif($type=~m/^text\//) {5579$save_as.='.txt';5580}55815582# With XSS prevention on, blobs of all types except a few known safe5583# ones are served with "Content-Disposition: attachment" to make sure5584# they don't run in our security domain. For certain image types,5585# blob view writes an <img> tag referring to blob_plain view, and we5586# want to be sure not to break that by serving the image as an5587# attachment (though Firefox 3 doesn't seem to care).5588my$sandbox=$prevent_xss&&5589$type!~m!^(?:text/plain|image/(?:gif|png|jpeg))$!;55905591print$cgi->header(5592-type =>$type,5593-expires =>$expires,5594-content_disposition =>5595($sandbox?'attachment':'inline')5596.'; filename="'.$save_as.'"');5597local$/=undef;5598binmode STDOUT,':raw';5599print<$fd>;5600binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi5601close$fd;5602}56035604sub git_blob {5605my$expires;56065607if(!defined$hash) {5608if(defined$file_name) {5609my$base=$hash_base|| git_get_head_hash($project);5610$hash= git_get_hash_by_path($base,$file_name,"blob")5611or die_error(404,"Cannot find file");5612}else{5613 die_error(400,"No file name defined");5614}5615}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {5616# blobs defined by non-textual hash id's can be cached5617$expires="+1d";5618}56195620my$have_blame= gitweb_check_feature('blame');5621open my$fd,"-|", git_cmd(),"cat-file","blob",$hash5622or die_error(500,"Couldn't cat$file_name,$hash");5623my$mimetype= blob_mimetype($fd,$file_name);5624# use 'blob_plain' (aka 'raw') view for files that cannot be displayed5625if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {5626close$fd;5627return git_blob_plain($mimetype);5628}5629# we can have blame only for text/* mimetype5630$have_blame&&= ($mimetype=~m!^text/!);56315632my$highlight= gitweb_check_feature('highlight');5633my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);5634$fd= run_highlighter($fd,$highlight,$syntax)5635if$syntax;56365637 git_header_html(undef,$expires);5638my$formats_nav='';5639if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5640if(defined$file_name) {5641if($have_blame) {5642$formats_nav.=5643$cgi->a({-href => href(action=>"blame", -replay=>1)},5644"blame") .5645" | ";5646}5647$formats_nav.=5648$cgi->a({-href => href(action=>"history", -replay=>1)},5649"history") .5650" | ".5651$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},5652"raw") .5653" | ".5654$cgi->a({-href => href(action=>"blob",5655 hash_base=>"HEAD", file_name=>$file_name)},5656"HEAD");5657}else{5658$formats_nav.=5659$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},5660"raw");5661}5662 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5663 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5664}else{5665print"<div class=\"page_nav\">\n".5666"<br/><br/></div>\n".5667"<div class=\"title\">$hash</div>\n";5668}5669 git_print_page_path($file_name,"blob",$hash_base);5670print"<div class=\"page_body\">\n";5671if($mimetype=~m!^image/!) {5672print qq!<img type="$mimetype"!;5673if($file_name) {5674print qq! alt="$file_name" title="$file_name"!;5675}5676print qq! src="! .5677 href(action=>"blob_plain", hash=>$hash,5678 hash_base=>$hash_base, file_name=>$file_name) .5679 qq!"/>\n!;5680}else{5681my$nr;5682while(my$line= <$fd>) {5683chomp$line;5684$nr++;5685$line= untabify($line);5686printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,5687$nr, href(-replay =>1),$nr,$nr,$syntax?$line: esc_html($line, -nbsp=>1);5688}5689}5690close$fd5691or print"Reading blob failed.\n";5692print"</div>";5693 git_footer_html();5694}56955696sub git_tree {5697if(!defined$hash_base) {5698$hash_base="HEAD";5699}5700if(!defined$hash) {5701if(defined$file_name) {5702$hash= git_get_hash_by_path($hash_base,$file_name,"tree");5703}else{5704$hash=$hash_base;5705}5706}5707 die_error(404,"No such tree")unlessdefined($hash);57085709my$show_sizes= gitweb_check_feature('show-sizes');5710my$have_blame= gitweb_check_feature('blame');57115712my@entries= ();5713{5714local$/="\0";5715open my$fd,"-|", git_cmd(),"ls-tree",'-z',5716($show_sizes?'-l': ()),@extra_options,$hash5717or die_error(500,"Open git-ls-tree failed");5718@entries=map{chomp;$_} <$fd>;5719close$fd5720or die_error(404,"Reading tree failed");5721}57225723my$refs= git_get_references();5724my$ref= format_ref_marker($refs,$hash_base);5725 git_header_html();5726my$basedir='';5727if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5728my@views_nav= ();5729if(defined$file_name) {5730push@views_nav,5731$cgi->a({-href => href(action=>"history", -replay=>1)},5732"history"),5733$cgi->a({-href => href(action=>"tree",5734 hash_base=>"HEAD", file_name=>$file_name)},5735"HEAD"),5736}5737my$snapshot_links= format_snapshot_links($hash);5738if(defined$snapshot_links) {5739# FIXME: Should be available when we have no hash base as well.5740push@views_nav,$snapshot_links;5741}5742 git_print_page_nav('tree','',$hash_base,undef,undef,5743join(' | ',@views_nav));5744 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);5745}else{5746undef$hash_base;5747print"<div class=\"page_nav\">\n";5748print"<br/><br/></div>\n";5749print"<div class=\"title\">$hash</div>\n";5750}5751if(defined$file_name) {5752$basedir=$file_name;5753if($basedirne''&&substr($basedir, -1)ne'/') {5754$basedir.='/';5755}5756 git_print_page_path($file_name,'tree',$hash_base);5757}5758print"<div class=\"page_body\">\n";5759print"<table class=\"tree\">\n";5760my$alternate=1;5761# '..' (top directory) link if possible5762if(defined$hash_base&&5763defined$file_name&&$file_name=~m![^/]+$!) {5764if($alternate) {5765print"<tr class=\"dark\">\n";5766}else{5767print"<tr class=\"light\">\n";5768}5769$alternate^=1;57705771my$up=$file_name;5772$up=~s!/?[^/]+$!!;5773undef$upunless$up;5774# based on git_print_tree_entry5775print'<td class="mode">'. mode_str('040000') ."</td>\n";5776print'<td class="size"> </td>'."\n"if$show_sizes;5777print'<td class="list">';5778print$cgi->a({-href => href(action=>"tree",5779 hash_base=>$hash_base,5780 file_name=>$up)},5781"..");5782print"</td>\n";5783print"<td class=\"link\"></td>\n";57845785print"</tr>\n";5786}5787foreachmy$line(@entries) {5788my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);57895790if($alternate) {5791print"<tr class=\"dark\">\n";5792}else{5793print"<tr class=\"light\">\n";5794}5795$alternate^=1;57965797 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);57985799print"</tr>\n";5800}5801print"</table>\n".5802"</div>";5803 git_footer_html();5804}58055806sub snapshot_name {5807my($project,$hash) =@_;58085809# path/to/project.git -> project5810# path/to/project/.git -> project5811my$name= to_utf8($project);5812$name=~ s,([^/])/*\.git$,$1,;5813$name= basename($name);5814# sanitize name5815$name=~s/[[:cntrl:]]/?/g;58165817my$ver=$hash;5818if($hash=~/^[0-9a-fA-F]+$/) {5819# shorten SHA-1 hash5820my$full_hash= git_get_full_hash($project,$hash);5821if($full_hash=~/^$hash/&&length($hash) >7) {5822$ver= git_get_short_hash($project,$hash);5823}5824}elsif($hash=~m!^refs/tags/(.*)$!) {5825# tags don't need shortened SHA-1 hash5826$ver=$1;5827}else{5828# branches and other need shortened SHA-1 hash5829if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {5830$ver=$1;5831}5832$ver.='-'. git_get_short_hash($project,$hash);5833}5834# in case of hierarchical branch names5835$ver=~s!/!.!g;58365837# name = project-version_string5838$name="$name-$ver";58395840returnwantarray? ($name,$name) :$name;5841}58425843sub git_snapshot {5844my$format=$input_params{'snapshot_format'};5845if(!@snapshot_fmts) {5846 die_error(403,"Snapshots not allowed");5847}5848# default to first supported snapshot format5849$format||=$snapshot_fmts[0];5850if($format!~m/^[a-z0-9]+$/) {5851 die_error(400,"Invalid snapshot format parameter");5852}elsif(!exists($known_snapshot_formats{$format})) {5853 die_error(400,"Unknown snapshot format");5854}elsif($known_snapshot_formats{$format}{'disabled'}) {5855 die_error(403,"Snapshot format not allowed");5856}elsif(!grep($_eq$format,@snapshot_fmts)) {5857 die_error(403,"Unsupported snapshot format");5858}58595860my$type= git_get_type("$hash^{}");5861if(!$type) {5862 die_error(404,'Object does not exist');5863}elsif($typeeq'blob') {5864 die_error(400,'Object is not a tree-ish');5865}58665867my($name,$prefix) = snapshot_name($project,$hash);5868my$filename="$name$known_snapshot_formats{$format}{'suffix'}";5869my$cmd= quote_command(5870 git_cmd(),'archive',5871"--format=$known_snapshot_formats{$format}{'format'}",5872"--prefix=$prefix/",$hash);5873if(exists$known_snapshot_formats{$format}{'compressor'}) {5874$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});5875}58765877$filename=~s/(["\\])/\\$1/g;5878print$cgi->header(5879-type =>$known_snapshot_formats{$format}{'type'},5880-content_disposition =>'inline; filename="'.$filename.'"',5881-status =>'200 OK');58825883open my$fd,"-|",$cmd5884or die_error(500,"Execute git-archive failed");5885binmode STDOUT,':raw';5886print<$fd>;5887binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi5888close$fd;5889}58905891sub git_log_generic {5892my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;58935894my$head= git_get_head_hash($project);5895if(!defined$base) {5896$base=$head;5897}5898if(!defined$page) {5899$page=0;5900}5901my$refs= git_get_references();59025903my$commit_hash=$base;5904if(defined$parent) {5905$commit_hash="$parent..$base";5906}5907my@commitlist=5908 parse_commits($commit_hash,101, (100*$page),5909defined$file_name? ($file_name,"--full-history") : ());59105911my$ftype;5912if(!defined$file_hash&&defined$file_name) {5913# some commits could have deleted file in question,5914# and not have it in tree, but one of them has to have it5915for(my$i=0;$i<@commitlist;$i++) {5916$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);5917last ifdefined$file_hash;5918}5919}5920if(defined$file_hash) {5921$ftype= git_get_type($file_hash);5922}5923if(defined$file_name&& !defined$ftype) {5924 die_error(500,"Unknown type of object");5925}5926my%co;5927if(defined$file_name) {5928%co= parse_commit($base)5929or die_error(404,"Unknown commit object");5930}593159325933my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);5934my$next_link='';5935if($#commitlist>=100) {5936$next_link=5937$cgi->a({-href => href(-replay=>1, page=>$page+1),5938-accesskey =>"n", -title =>"Alt-n"},"next");5939}5940my$patch_max= gitweb_get_feature('patches');5941if($patch_max&& !defined$file_name) {5942if($patch_max<0||@commitlist<=$patch_max) {5943$paging_nav.=" ⋅ ".5944$cgi->a({-href => href(action=>"patches", -replay=>1)},5945"patches");5946}5947}59485949 git_header_html();5950 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);5951if(defined$file_name) {5952 git_print_header_div('commit', esc_html($co{'title'}),$base);5953}else{5954 git_print_header_div('summary',$project)5955}5956 git_print_page_path($file_name,$ftype,$hash_base)5957if(defined$file_name);59585959$body_subr->(\@commitlist,0,99,$refs,$next_link,5960$file_name,$file_hash,$ftype);59615962 git_footer_html();5963}59645965sub git_log {5966 git_log_generic('log', \&git_log_body,5967$hash,$hash_parent);5968}59695970sub git_commit {5971$hash||=$hash_base||"HEAD";5972my%co= parse_commit($hash)5973or die_error(404,"Unknown commit object");59745975my$parent=$co{'parent'};5976my$parents=$co{'parents'};# listref59775978# we need to prepare $formats_nav before any parameter munging5979my$formats_nav;5980if(!defined$parent) {5981# --root commitdiff5982$formats_nav.='(initial)';5983}elsif(@$parents==1) {5984# single parent commit5985$formats_nav.=5986'(parent: '.5987$cgi->a({-href => href(action=>"commit",5988 hash=>$parent)},5989 esc_html(substr($parent,0,7))) .5990')';5991}else{5992# merge commit5993$formats_nav.=5994'(merge: '.5995join(' ',map{5996$cgi->a({-href => href(action=>"commit",5997 hash=>$_)},5998 esc_html(substr($_,0,7)));5999}@$parents) .6000')';6001}6002if(gitweb_check_feature('patches') &&@$parents<=1) {6003$formats_nav.=" | ".6004$cgi->a({-href => href(action=>"patch", -replay=>1)},6005"patch");6006}60076008if(!defined$parent) {6009$parent="--root";6010}6011my@difftree;6012open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",6013@diff_opts,6014(@$parents<=1?$parent:'-c'),6015$hash,"--"6016or die_error(500,"Open git-diff-tree failed");6017@difftree=map{chomp;$_} <$fd>;6018close$fdor die_error(404,"Reading git-diff-tree failed");60196020# non-textual hash id's can be cached6021my$expires;6022if($hash=~m/^[0-9a-fA-F]{40}$/) {6023$expires="+1d";6024}6025my$refs= git_get_references();6026my$ref= format_ref_marker($refs,$co{'id'});60276028 git_header_html(undef,$expires);6029 git_print_page_nav('commit','',6030$hash,$co{'tree'},$hash,6031$formats_nav);60326033if(defined$co{'parent'}) {6034 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);6035}else{6036 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);6037}6038print"<div class=\"title_text\">\n".6039"<table class=\"object_header\">\n";6040 git_print_authorship_rows(\%co);6041print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";6042print"<tr>".6043"<td>tree</td>".6044"<td class=\"sha1\">".6045$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),6046class=>"list"},$co{'tree'}) .6047"</td>".6048"<td class=\"link\">".6049$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},6050"tree");6051my$snapshot_links= format_snapshot_links($hash);6052if(defined$snapshot_links) {6053print" | ".$snapshot_links;6054}6055print"</td>".6056"</tr>\n";60576058foreachmy$par(@$parents) {6059print"<tr>".6060"<td>parent</td>".6061"<td class=\"sha1\">".6062$cgi->a({-href => href(action=>"commit", hash=>$par),6063class=>"list"},$par) .6064"</td>".6065"<td class=\"link\">".6066$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .6067" | ".6068$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .6069"</td>".6070"</tr>\n";6071}6072print"</table>".6073"</div>\n";60746075print"<div class=\"page_body\">\n";6076 git_print_log($co{'comment'});6077print"</div>\n";60786079 git_difftree_body(\@difftree,$hash,@$parents);60806081 git_footer_html();6082}60836084sub git_object {6085# object is defined by:6086# - hash or hash_base alone6087# - hash_base and file_name6088my$type;60896090# - hash or hash_base alone6091if($hash|| ($hash_base&& !defined$file_name)) {6092my$object_id=$hash||$hash_base;60936094open my$fd,"-|", quote_command(6095 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'6096or die_error(404,"Object does not exist");6097$type= <$fd>;6098chomp$type;6099close$fd6100or die_error(404,"Object does not exist");61016102# - hash_base and file_name6103}elsif($hash_base&&defined$file_name) {6104$file_name=~ s,/+$,,;61056106system(git_cmd(),"cat-file",'-e',$hash_base) ==06107or die_error(404,"Base object does not exist");61086109# here errors should not hapen6110open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name6111or die_error(500,"Open git-ls-tree failed");6112my$line= <$fd>;6113close$fd;61146115#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'6116unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {6117 die_error(404,"File or directory for given base does not exist");6118}6119$type=$2;6120$hash=$3;6121}else{6122 die_error(400,"Not enough information to find object");6123}61246125print$cgi->redirect(-uri => href(action=>$type, -full=>1,6126 hash=>$hash, hash_base=>$hash_base,6127 file_name=>$file_name),6128-status =>'302 Found');6129}61306131sub git_blobdiff {6132my$format=shift||'html';61336134my$fd;6135my@difftree;6136my%diffinfo;6137my$expires;61386139# preparing $fd and %diffinfo for git_patchset_body6140# new style URI6141if(defined$hash_base&&defined$hash_parent_base) {6142if(defined$file_name) {6143# read raw output6144open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6145$hash_parent_base,$hash_base,6146"--", (defined$file_parent?$file_parent: ()),$file_name6147or die_error(500,"Open git-diff-tree failed");6148@difftree=map{chomp;$_} <$fd>;6149close$fd6150or die_error(404,"Reading git-diff-tree failed");6151@difftree6152or die_error(404,"Blob diff not found");61536154}elsif(defined$hash&&6155$hash=~/[0-9a-fA-F]{40}/) {6156# try to find filename from $hash61576158# read filtered raw output6159open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6160$hash_parent_base,$hash_base,"--"6161or die_error(500,"Open git-diff-tree failed");6162@difftree=6163# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'6164# $hash == to_id6165grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}6166map{chomp;$_} <$fd>;6167close$fd6168or die_error(404,"Reading git-diff-tree failed");6169@difftree6170or die_error(404,"Blob diff not found");61716172}else{6173 die_error(400,"Missing one of the blob diff parameters");6174}61756176if(@difftree>1) {6177 die_error(400,"Ambiguous blob diff specification");6178}61796180%diffinfo= parse_difftree_raw_line($difftree[0]);6181$file_parent||=$diffinfo{'from_file'} ||$file_name;6182$file_name||=$diffinfo{'to_file'};61836184$hash_parent||=$diffinfo{'from_id'};6185$hash||=$diffinfo{'to_id'};61866187# non-textual hash id's can be cached6188if($hash_base=~m/^[0-9a-fA-F]{40}$/&&6189$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {6190$expires='+1d';6191}61926193# open patch output6194open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6195'-p', ($formateq'html'?"--full-index": ()),6196$hash_parent_base,$hash_base,6197"--", (defined$file_parent?$file_parent: ()),$file_name6198or die_error(500,"Open git-diff-tree failed");6199}62006201# old/legacy style URI -- not generated anymore since 1.4.3.6202if(!%diffinfo) {6203 die_error('404 Not Found',"Missing one of the blob diff parameters")6204}62056206# header6207if($formateq'html') {6208my$formats_nav=6209$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},6210"raw");6211 git_header_html(undef,$expires);6212if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6213 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6214 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6215}else{6216print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";6217print"<div class=\"title\">$hashvs$hash_parent</div>\n";6218}6219if(defined$file_name) {6220 git_print_page_path($file_name,"blob",$hash_base);6221}else{6222print"<div class=\"page_path\"></div>\n";6223}62246225}elsif($formateq'plain') {6226print$cgi->header(6227-type =>'text/plain',6228-charset =>'utf-8',6229-expires =>$expires,6230-content_disposition =>'inline; filename="'."$file_name".'.patch"');62316232print"X-Git-Url: ".$cgi->self_url() ."\n\n";62336234}else{6235 die_error(400,"Unknown blobdiff format");6236}62376238# patch6239if($formateq'html') {6240print"<div class=\"page_body\">\n";62416242 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);6243close$fd;62446245print"</div>\n";# class="page_body"6246 git_footer_html();62476248}else{6249while(my$line= <$fd>) {6250$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;6251$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;62526253print$line;62546255last if$line=~m!^\+\+\+!;6256}6257local$/=undef;6258print<$fd>;6259close$fd;6260}6261}62626263sub git_blobdiff_plain {6264 git_blobdiff('plain');6265}62666267sub git_commitdiff {6268my%params=@_;6269my$format=$params{-format} ||'html';62706271my($patch_max) = gitweb_get_feature('patches');6272if($formateq'patch') {6273 die_error(403,"Patch view not allowed")unless$patch_max;6274}62756276$hash||=$hash_base||"HEAD";6277my%co= parse_commit($hash)6278or die_error(404,"Unknown commit object");62796280# choose format for commitdiff for merge6281if(!defined$hash_parent&& @{$co{'parents'}} >1) {6282$hash_parent='--cc';6283}6284# we need to prepare $formats_nav before almost any parameter munging6285my$formats_nav;6286if($formateq'html') {6287$formats_nav=6288$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},6289"raw");6290if($patch_max&& @{$co{'parents'}} <=1) {6291$formats_nav.=" | ".6292$cgi->a({-href => href(action=>"patch", -replay=>1)},6293"patch");6294}62956296if(defined$hash_parent&&6297$hash_parentne'-c'&&$hash_parentne'--cc') {6298# commitdiff with two commits given6299my$hash_parent_short=$hash_parent;6300if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {6301$hash_parent_short=substr($hash_parent,0,7);6302}6303$formats_nav.=6304' (from';6305for(my$i=0;$i< @{$co{'parents'}};$i++) {6306if($co{'parents'}[$i]eq$hash_parent) {6307$formats_nav.=' parent '. ($i+1);6308last;6309}6310}6311$formats_nav.=': '.6312$cgi->a({-href => href(action=>"commitdiff",6313 hash=>$hash_parent)},6314 esc_html($hash_parent_short)) .6315')';6316}elsif(!$co{'parent'}) {6317# --root commitdiff6318$formats_nav.=' (initial)';6319}elsif(scalar@{$co{'parents'}} ==1) {6320# single parent commit6321$formats_nav.=6322' (parent: '.6323$cgi->a({-href => href(action=>"commitdiff",6324 hash=>$co{'parent'})},6325 esc_html(substr($co{'parent'},0,7))) .6326')';6327}else{6328# merge commit6329if($hash_parenteq'--cc') {6330$formats_nav.=' | '.6331$cgi->a({-href => href(action=>"commitdiff",6332 hash=>$hash, hash_parent=>'-c')},6333'combined');6334}else{# $hash_parent eq '-c'6335$formats_nav.=' | '.6336$cgi->a({-href => href(action=>"commitdiff",6337 hash=>$hash, hash_parent=>'--cc')},6338'compact');6339}6340$formats_nav.=6341' (merge: '.6342join(' ',map{6343$cgi->a({-href => href(action=>"commitdiff",6344 hash=>$_)},6345 esc_html(substr($_,0,7)));6346} @{$co{'parents'}} ) .6347')';6348}6349}63506351my$hash_parent_param=$hash_parent;6352if(!defined$hash_parent_param) {6353# --cc for multiple parents, --root for parentless6354$hash_parent_param=6355@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';6356}63576358# read commitdiff6359my$fd;6360my@difftree;6361if($formateq'html') {6362open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6363"--no-commit-id","--patch-with-raw","--full-index",6364$hash_parent_param,$hash,"--"6365or die_error(500,"Open git-diff-tree failed");63666367while(my$line= <$fd>) {6368chomp$line;6369# empty line ends raw part of diff-tree output6370last unless$line;6371push@difftree,scalar parse_difftree_raw_line($line);6372}63736374}elsif($formateq'plain') {6375open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6376'-p',$hash_parent_param,$hash,"--"6377or die_error(500,"Open git-diff-tree failed");6378}elsif($formateq'patch') {6379# For commit ranges, we limit the output to the number of6380# patches specified in the 'patches' feature.6381# For single commits, we limit the output to a single patch,6382# diverging from the git-format-patch default.6383my@commit_spec= ();6384if($hash_parent) {6385if($patch_max>0) {6386push@commit_spec,"-$patch_max";6387}6388push@commit_spec,'-n',"$hash_parent..$hash";6389}else{6390if($params{-single}) {6391push@commit_spec,'-1';6392}else{6393if($patch_max>0) {6394push@commit_spec,"-$patch_max";6395}6396push@commit_spec,"-n";6397}6398push@commit_spec,'--root',$hash;6399}6400open$fd,"-|", git_cmd(),"format-patch",@diff_opts,6401'--encoding=utf8','--stdout',@commit_spec6402or die_error(500,"Open git-format-patch failed");6403}else{6404 die_error(400,"Unknown commitdiff format");6405}64066407# non-textual hash id's can be cached6408my$expires;6409if($hash=~m/^[0-9a-fA-F]{40}$/) {6410$expires="+1d";6411}64126413# write commit message6414if($formateq'html') {6415my$refs= git_get_references();6416my$ref= format_ref_marker($refs,$co{'id'});64176418 git_header_html(undef,$expires);6419 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);6420 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);6421print"<div class=\"title_text\">\n".6422"<table class=\"object_header\">\n";6423 git_print_authorship_rows(\%co);6424print"</table>".6425"</div>\n";6426print"<div class=\"page_body\">\n";6427if(@{$co{'comment'}} >1) {6428print"<div class=\"log\">\n";6429 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);6430print"</div>\n";# class="log"6431}64326433}elsif($formateq'plain') {6434my$refs= git_get_references("tags");6435my$tagname= git_get_rev_name_tags($hash);6436my$filename= basename($project) ."-$hash.patch";64376438print$cgi->header(6439-type =>'text/plain',6440-charset =>'utf-8',6441-expires =>$expires,6442-content_disposition =>'inline; filename="'."$filename".'"');6443my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});6444print"From: ". to_utf8($co{'author'}) ."\n";6445print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";6446print"Subject: ". to_utf8($co{'title'}) ."\n";64476448print"X-Git-Tag:$tagname\n"if$tagname;6449print"X-Git-Url: ".$cgi->self_url() ."\n\n";64506451foreachmy$line(@{$co{'comment'}}) {6452print to_utf8($line) ."\n";6453}6454print"---\n\n";6455}elsif($formateq'patch') {6456my$filename= basename($project) ."-$hash.patch";64576458print$cgi->header(6459-type =>'text/plain',6460-charset =>'utf-8',6461-expires =>$expires,6462-content_disposition =>'inline; filename="'."$filename".'"');6463}64646465# write patch6466if($formateq'html') {6467my$use_parents= !defined$hash_parent||6468$hash_parenteq'-c'||$hash_parenteq'--cc';6469 git_difftree_body(\@difftree,$hash,6470$use_parents? @{$co{'parents'}} :$hash_parent);6471print"<br/>\n";64726473 git_patchset_body($fd, \@difftree,$hash,6474$use_parents? @{$co{'parents'}} :$hash_parent);6475close$fd;6476print"</div>\n";# class="page_body"6477 git_footer_html();64786479}elsif($formateq'plain') {6480local$/=undef;6481print<$fd>;6482close$fd6483or print"Reading git-diff-tree failed\n";6484}elsif($formateq'patch') {6485local$/=undef;6486print<$fd>;6487close$fd6488or print"Reading git-format-patch failed\n";6489}6490}64916492sub git_commitdiff_plain {6493 git_commitdiff(-format =>'plain');6494}64956496# format-patch-style patches6497sub git_patch {6498 git_commitdiff(-format =>'patch', -single =>1);6499}65006501sub git_patches {6502 git_commitdiff(-format =>'patch');6503}65046505sub git_history {6506 git_log_generic('history', \&git_history_body,6507$hash_base,$hash_parent_base,6508$file_name,$hash);6509}65106511sub git_search {6512 gitweb_check_feature('search')or die_error(403,"Search is disabled");6513if(!defined$searchtext) {6514 die_error(400,"Text field is empty");6515}6516if(!defined$hash) {6517$hash= git_get_head_hash($project);6518}6519my%co= parse_commit($hash);6520if(!%co) {6521 die_error(404,"Unknown commit object");6522}6523if(!defined$page) {6524$page=0;6525}65266527$searchtype||='commit';6528if($searchtypeeq'pickaxe') {6529# pickaxe may take all resources of your box and run for several minutes6530# with every query - so decide by yourself how public you make this feature6531 gitweb_check_feature('pickaxe')6532or die_error(403,"Pickaxe is disabled");6533}6534if($searchtypeeq'grep') {6535 gitweb_check_feature('grep')6536or die_error(403,"Grep is disabled");6537}65386539 git_header_html();65406541if($searchtypeeq'commit'or$searchtypeeq'author'or$searchtypeeq'committer') {6542my$greptype;6543if($searchtypeeq'commit') {6544$greptype="--grep=";6545}elsif($searchtypeeq'author') {6546$greptype="--author=";6547}elsif($searchtypeeq'committer') {6548$greptype="--committer=";6549}6550$greptype.=$searchtext;6551my@commitlist= parse_commits($hash,101, (100*$page),undef,6552$greptype,'--regexp-ignore-case',6553$search_use_regexp?'--extended-regexp':'--fixed-strings');65546555my$paging_nav='';6556if($page>0) {6557$paging_nav.=6558$cgi->a({-href => href(action=>"search", hash=>$hash,6559 searchtext=>$searchtext,6560 searchtype=>$searchtype)},6561"first");6562$paging_nav.=" ⋅ ".6563$cgi->a({-href => href(-replay=>1, page=>$page-1),6564-accesskey =>"p", -title =>"Alt-p"},"prev");6565}else{6566$paging_nav.="first";6567$paging_nav.=" ⋅ prev";6568}6569my$next_link='';6570if($#commitlist>=100) {6571$next_link=6572$cgi->a({-href => href(-replay=>1, page=>$page+1),6573-accesskey =>"n", -title =>"Alt-n"},"next");6574$paging_nav.=" ⋅$next_link";6575}else{6576$paging_nav.=" ⋅ next";6577}65786579 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);6580 git_print_header_div('commit', esc_html($co{'title'}),$hash);6581if($page==0&& !@commitlist) {6582print"<p>No match.</p>\n";6583}else{6584 git_search_grep_body(\@commitlist,0,99,$next_link);6585}6586}65876588if($searchtypeeq'pickaxe') {6589 git_print_page_nav('','',$hash,$co{'tree'},$hash);6590 git_print_header_div('commit', esc_html($co{'title'}),$hash);65916592print"<table class=\"pickaxe search\">\n";6593my$alternate=1;6594local$/="\n";6595open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,6596'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",6597($search_use_regexp?'--pickaxe-regex': ());6598undef%co;6599my@files;6600while(my$line= <$fd>) {6601chomp$line;6602next unless$line;66036604my%set= parse_difftree_raw_line($line);6605if(defined$set{'commit'}) {6606# finish previous commit6607if(%co) {6608print"</td>\n".6609"<td class=\"link\">".6610$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6611" | ".6612$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6613print"</td>\n".6614"</tr>\n";6615}66166617if($alternate) {6618print"<tr class=\"dark\">\n";6619}else{6620print"<tr class=\"light\">\n";6621}6622$alternate^=1;6623%co= parse_commit($set{'commit'});6624my$author= chop_and_escape_str($co{'author_name'},15,5);6625print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6626"<td><i>$author</i></td>\n".6627"<td>".6628$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6629-class=>"list subject"},6630 chop_and_escape_str($co{'title'},50) ."<br/>");6631}elsif(defined$set{'to_id'}) {6632next if($set{'to_id'} =~m/^0{40}$/);66336634print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},6635 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),6636-class=>"list"},6637"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .6638"<br/>\n";6639}6640}6641close$fd;66426643# finish last commit (warning: repetition!)6644if(%co) {6645print"</td>\n".6646"<td class=\"link\">".6647$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6648" | ".6649$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6650print"</td>\n".6651"</tr>\n";6652}66536654print"</table>\n";6655}66566657if($searchtypeeq'grep') {6658 git_print_page_nav('','',$hash,$co{'tree'},$hash);6659 git_print_header_div('commit', esc_html($co{'title'}),$hash);66606661print"<table class=\"grep_search\">\n";6662my$alternate=1;6663my$matches=0;6664local$/="\n";6665open my$fd,"-|", git_cmd(),'grep','-n',6666$search_use_regexp? ('-E','-i') :'-F',6667$searchtext,$co{'tree'};6668my$lastfile='';6669while(my$line= <$fd>) {6670chomp$line;6671my($file,$lno,$ltext,$binary);6672last if($matches++>1000);6673if($line=~/^Binary file (.+) matches$/) {6674$file=$1;6675$binary=1;6676}else{6677(undef,$file,$lno,$ltext) =split(/:/,$line,4);6678}6679if($filene$lastfile) {6680$lastfileand print"</td></tr>\n";6681if($alternate++) {6682print"<tr class=\"dark\">\n";6683}else{6684print"<tr class=\"light\">\n";6685}6686print"<td class=\"list\">".6687$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},6688 file_name=>"$file"),6689-class=>"list"}, esc_path($file));6690print"</td><td>\n";6691$lastfile=$file;6692}6693if($binary) {6694print"<div class=\"binary\">Binary file</div>\n";6695}else{6696$ltext= untabify($ltext);6697if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6698$ltext= esc_html($1, -nbsp=>1);6699$ltext.='<span class="match">';6700$ltext.= esc_html($2, -nbsp=>1);6701$ltext.='</span>';6702$ltext.= esc_html($3, -nbsp=>1);6703}else{6704$ltext= esc_html($ltext, -nbsp=>1);6705}6706print"<div class=\"pre\">".6707$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},6708 file_name=>"$file").'#l'.$lno,6709-class=>"linenr"},sprintf('%4i',$lno))6710.' '.$ltext."</div>\n";6711}6712}6713if($lastfile) {6714print"</td></tr>\n";6715if($matches>1000) {6716print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6717}6718}else{6719print"<div class=\"diff nodifferences\">No matches found</div>\n";6720}6721close$fd;67226723print"</table>\n";6724}6725 git_footer_html();6726}67276728sub git_search_help {6729 git_header_html();6730 git_print_page_nav('','',$hash,$hash,$hash);6731print<<EOT;6732<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without6733regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,6734the pattern entered is recognized as the POSIX extended6735<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case6736insensitive).</p>6737<dl>6738<dt><b>commit</b></dt>6739<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>6740EOT6741my$have_grep= gitweb_check_feature('grep');6742if($have_grep) {6743print<<EOT;6744<dt><b>grep</b></dt>6745<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing6746 a different one) are searched for the given pattern. On large trees, this search can take6747a while and put some strain on the server, so please use it with some consideration. Note that6748due to git-grep peculiarity, currently if regexp mode is turned off, the matches are6749case-sensitive.</dd>6750EOT6751}6752print<<EOT;6753<dt><b>author</b></dt>6754<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>6755<dt><b>committer</b></dt>6756<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>6757EOT6758my$have_pickaxe= gitweb_check_feature('pickaxe');6759if($have_pickaxe) {6760print<<EOT;6761<dt><b>pickaxe</b></dt>6762<dd>All commits that caused the string to appear or disappear from any file (changes that6763added, removed or "modified" the string) will be listed. This search can take a while and6764takes a lot of strain on the server, so please use it wisely. Note that since you may be6765interested even in changes just changing the case as well, this search is case sensitive.</dd>6766EOT6767}6768print"</dl>\n";6769 git_footer_html();6770}67716772sub git_shortlog {6773 git_log_generic('shortlog', \&git_shortlog_body,6774$hash,$hash_parent);6775}67766777## ......................................................................6778## feeds (RSS, Atom; OPML)67796780sub git_feed {6781my$format=shift||'atom';6782my$have_blame= gitweb_check_feature('blame');67836784# Atom: http://www.atomenabled.org/developers/syndication/6785# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ6786if($formatne'rss'&&$formatne'atom') {6787 die_error(400,"Unknown web feed format");6788}67896790# log/feed of current (HEAD) branch, log of given branch, history of file/directory6791my$head=$hash||'HEAD';6792my@commitlist= parse_commits($head,150,0,$file_name);67936794my%latest_commit;6795my%latest_date;6796my$content_type="application/$format+xml";6797if(defined$cgi->http('HTTP_ACCEPT') &&6798$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {6799# browser (feed reader) prefers text/xml6800$content_type='text/xml';6801}6802if(defined($commitlist[0])) {6803%latest_commit= %{$commitlist[0]};6804my$latest_epoch=$latest_commit{'committer_epoch'};6805%latest_date= parse_date($latest_epoch);6806my$if_modified=$cgi->http('IF_MODIFIED_SINCE');6807if(defined$if_modified) {6808my$since;6809if(eval{require HTTP::Date;1; }) {6810$since= HTTP::Date::str2time($if_modified);6811}elsif(eval{require Time::ParseDate;1; }) {6812$since= Time::ParseDate::parsedate($if_modified, GMT =>1);6813}6814if(defined$since&&$latest_epoch<=$since) {6815print$cgi->header(6816-type =>$content_type,6817-charset =>'utf-8',6818-last_modified =>$latest_date{'rfc2822'},6819-status =>'304 Not Modified');6820return;6821}6822}6823print$cgi->header(6824-type =>$content_type,6825-charset =>'utf-8',6826-last_modified =>$latest_date{'rfc2822'});6827}else{6828print$cgi->header(6829-type =>$content_type,6830-charset =>'utf-8');6831}68326833# Optimization: skip generating the body if client asks only6834# for Last-Modified date.6835return if($cgi->request_method()eq'HEAD');68366837# header variables6838my$title="$site_name-$project/$action";6839my$feed_type='log';6840if(defined$hash) {6841$title.=" - '$hash'";6842$feed_type='branch log';6843if(defined$file_name) {6844$title.=" ::$file_name";6845$feed_type='history';6846}6847}elsif(defined$file_name) {6848$title.=" -$file_name";6849$feed_type='history';6850}6851$title.="$feed_type";6852my$descr= git_get_project_description($project);6853if(defined$descr) {6854$descr= esc_html($descr);6855}else{6856$descr="$project".6857($formateq'rss'?'RSS':'Atom') .6858" feed";6859}6860my$owner= git_get_project_owner($project);6861$owner= esc_html($owner);68626863#header6864my$alt_url;6865if(defined$file_name) {6866$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);6867}elsif(defined$hash) {6868$alt_url= href(-full=>1, action=>"log", hash=>$hash);6869}else{6870$alt_url= href(-full=>1, action=>"summary");6871}6872print qq!<?xml version="1.0" encoding="utf-8"?>\n!;6873if($formateq'rss') {6874print<<XML;6875<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">6876<channel>6877XML6878print"<title>$title</title>\n".6879"<link>$alt_url</link>\n".6880"<description>$descr</description>\n".6881"<language>en</language>\n".6882# project owner is responsible for 'editorial' content6883"<managingEditor>$owner</managingEditor>\n";6884if(defined$logo||defined$favicon) {6885# prefer the logo to the favicon, since RSS6886# doesn't allow both6887my$img= esc_url($logo||$favicon);6888print"<image>\n".6889"<url>$img</url>\n".6890"<title>$title</title>\n".6891"<link>$alt_url</link>\n".6892"</image>\n";6893}6894if(%latest_date) {6895print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";6896print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";6897}6898print"<generator>gitweb v.$version/$git_version</generator>\n";6899}elsif($formateq'atom') {6900print<<XML;6901<feed xmlns="http://www.w3.org/2005/Atom">6902XML6903print"<title>$title</title>\n".6904"<subtitle>$descr</subtitle>\n".6905'<link rel="alternate" type="text/html" href="'.6906$alt_url.'" />'."\n".6907'<link rel="self" type="'.$content_type.'" href="'.6908$cgi->self_url() .'" />'."\n".6909"<id>". href(-full=>1) ."</id>\n".6910# use project owner for feed author6911"<author><name>$owner</name></author>\n";6912if(defined$favicon) {6913print"<icon>". esc_url($favicon) ."</icon>\n";6914}6915if(defined$logo_url) {6916# not twice as wide as tall: 72 x 27 pixels6917print"<logo>". esc_url($logo) ."</logo>\n";6918}6919if(!%latest_date) {6920# dummy date to keep the feed valid until commits trickle in:6921print"<updated>1970-01-01T00:00:00Z</updated>\n";6922}else{6923print"<updated>$latest_date{'iso-8601'}</updated>\n";6924}6925print"<generator version='$version/$git_version'>gitweb</generator>\n";6926}69276928# contents6929for(my$i=0;$i<=$#commitlist;$i++) {6930my%co= %{$commitlist[$i]};6931my$commit=$co{'id'};6932# we read 150, we always show 30 and the ones more recent than 48 hours6933if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {6934last;6935}6936my%cd= parse_date($co{'author_epoch'});69376938# get list of changed files6939open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6940$co{'parent'} ||"--root",6941$co{'id'},"--", (defined$file_name?$file_name: ())6942ornext;6943my@difftree=map{chomp;$_} <$fd>;6944close$fd6945ornext;69466947# print element (entry, item)6948my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);6949if($formateq'rss') {6950print"<item>\n".6951"<title>". esc_html($co{'title'}) ."</title>\n".6952"<author>". esc_html($co{'author'}) ."</author>\n".6953"<pubDate>$cd{'rfc2822'}</pubDate>\n".6954"<guid isPermaLink=\"true\">$co_url</guid>\n".6955"<link>$co_url</link>\n".6956"<description>". esc_html($co{'title'}) ."</description>\n".6957"<content:encoded>".6958"<![CDATA[\n";6959}elsif($formateq'atom') {6960print"<entry>\n".6961"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".6962"<updated>$cd{'iso-8601'}</updated>\n".6963"<author>\n".6964" <name>". esc_html($co{'author_name'}) ."</name>\n";6965if($co{'author_email'}) {6966print" <email>". esc_html($co{'author_email'}) ."</email>\n";6967}6968print"</author>\n".6969# use committer for contributor6970"<contributor>\n".6971" <name>". esc_html($co{'committer_name'}) ."</name>\n";6972if($co{'committer_email'}) {6973print" <email>". esc_html($co{'committer_email'}) ."</email>\n";6974}6975print"</contributor>\n".6976"<published>$cd{'iso-8601'}</published>\n".6977"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".6978"<id>$co_url</id>\n".6979"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".6980"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";6981}6982my$comment=$co{'comment'};6983print"<pre>\n";6984foreachmy$line(@$comment) {6985$line= esc_html($line);6986print"$line\n";6987}6988print"</pre><ul>\n";6989foreachmy$difftree_line(@difftree) {6990my%difftree= parse_difftree_raw_line($difftree_line);6991next if!$difftree{'from_id'};69926993my$file=$difftree{'file'} ||$difftree{'to_file'};69946995print"<li>".6996"[".6997$cgi->a({-href => href(-full=>1, action=>"blobdiff",6998 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},6999 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},7000 file_name=>$file, file_parent=>$difftree{'from_file'}),7001-title =>"diff"},'D');7002if($have_blame) {7003print$cgi->a({-href => href(-full=>1, action=>"blame",7004 file_name=>$file, hash_base=>$commit),7005-title =>"blame"},'B');7006}7007# if this is not a feed of a file history7008if(!defined$file_name||$file_namene$file) {7009print$cgi->a({-href => href(-full=>1, action=>"history",7010 file_name=>$file, hash=>$commit),7011-title =>"history"},'H');7012}7013$file= esc_path($file);7014print"] ".7015"$file</li>\n";7016}7017if($formateq'rss') {7018print"</ul>]]>\n".7019"</content:encoded>\n".7020"</item>\n";7021}elsif($formateq'atom') {7022print"</ul>\n</div>\n".7023"</content>\n".7024"</entry>\n";7025}7026}70277028# end of feed7029if($formateq'rss') {7030print"</channel>\n</rss>\n";7031}elsif($formateq'atom') {7032print"</feed>\n";7033}7034}70357036sub git_rss {7037 git_feed('rss');7038}70397040sub git_atom {7041 git_feed('atom');7042}70437044sub git_opml {7045my@list= git_get_projects_list();70467047print$cgi->header(7048-type =>'text/xml',7049-charset =>'utf-8',7050-content_disposition =>'inline; filename="opml.xml"');70517052print<<XML;7053<?xml version="1.0" encoding="utf-8"?>7054<opml version="1.0">7055<head>7056 <title>$site_nameOPML Export</title>7057</head>7058<body>7059<outline text="git RSS feeds">7060XML70617062foreachmy$pr(@list) {7063my%proj=%$pr;7064my$head= git_get_head_hash($proj{'path'});7065if(!defined$head) {7066next;7067}7068$git_dir="$projectroot/$proj{'path'}";7069my%co= parse_commit($head);7070if(!%co) {7071next;7072}70737074my$path= esc_html(chop_str($proj{'path'},25,5));7075my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);7076my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);7077print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";7078}7079print<<XML;7080</outline>7081</body>7082</opml>7083XML7084}